id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17,974
|
audio_sink.h
|
anbox_anbox/src/anbox/platform/sdl/audio_sink.h
|
/*
* Copyright (C) 2017 Simon Fels <morphis@gravedo.de>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3, as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranties of
* MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef ANBOX_PLATFORM_SDL_AUDIO_SINK_H_
#define ANBOX_PLATFORM_SDL_AUDIO_SINK_H_
#include "anbox/audio/sink.h"
#include "anbox/graphics/buffer_queue.h"
#include "anbox/platform/sdl/sdl_wrapper.h"
#include <thread>
namespace anbox::platform::sdl {
class AudioSink : public audio::Sink {
public:
AudioSink();
~AudioSink();
void write_data(const std::vector<std::uint8_t> &data) override;
private:
bool connect_audio();
void disconnect_audio();
void read_data(std::uint8_t *buffer, int size);
static void on_data_requested(void *user_data, std::uint8_t *buffer, int size);
std::mutex lock_;
SDL_AudioSpec spec_;
SDL_AudioDeviceID device_id_;
graphics::BufferQueue queue_;
graphics::Buffer read_buffer_;
size_t read_buffer_left_ = 0;
};
}
#endif
| 1,453
|
C++
|
.h
| 42
| 32.380952
| 81
| 0.748396
|
anbox/anbox
| 8,865
| 1,152
| 381
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
17,976
|
mir_display_connection.h
|
anbox_anbox/src/anbox/platform/sdl/mir_display_connection.h
|
/*
* Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3, as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranties of
* MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef ANBOX_PLATFORM_SDL_MIR_DISPLAY_CONNECTION_H_
#define ANBOX_PLATFORM_SDL_MIR_DISPLAY_CONNECTION_H_
#define MIR_EGL_PLATFORM
#include <mirclient/mir_toolkit/mir_client_library.h>
#include <EGL/egl.h>
namespace anbox::sdl {
class MirDisplayConnection {
public:
MirDisplayConnection();
~MirDisplayConnection();
MirPixelFormat default_pixel_format() const;
MirConnection* connection() const;
EGLNativeDisplayType native_display() const;
int output_id() const;
int vertical_resolution() const;
int horizontal_resolution() const;
private:
MirConnection* connection_;
int output_id_;
int vertical_resolution_;
int horizontal_resolution_;
};
}
#endif
| 1,359
|
C++
|
.h
| 40
| 31.725
| 76
| 0.773282
|
anbox/anbox
| 8,865
| 1,152
| 381
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
17,978
|
fd_socket_transmission.h
|
anbox_anbox/src/anbox/network/fd_socket_transmission.h
|
/*
* Copyright © 2014 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Kevin DuBois <kevin.dubois@canonical.com>
*/
#ifndef ANBOX_NETWORK_FD_SOCKET_TRANSMISSION_H_
#define ANBOX_NETWORK_FD_SOCKET_TRANSMISSION_H_
#include "anbox/common/fd.h"
#include <stdexcept>
#include <system_error>
#include <vector>
namespace anbox {
struct socket_error : std::system_error {
socket_error(std::string const& message);
};
struct socket_disconnected_error : std::system_error {
socket_disconnected_error(std::string const& message);
};
struct fd_reception_error : std::runtime_error {
fd_reception_error(std::string const& message);
};
bool socket_error_is_transient(int error_code);
void send_fds(Fd const& socket, std::vector<Fd> const& fd);
void receive_data(Fd const& socket, void* buffer, size_t bytes_requested,
std::vector<Fd>& fds);
}
#endif
| 1,462
|
C++
|
.h
| 39
| 35.25641
| 75
| 0.754064
|
anbox/anbox
| 8,865
| 1,152
| 381
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
17,979
|
tcp_socket_connector.h
|
anbox_anbox/src/anbox/network/tcp_socket_connector.h
|
/*
* Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3, as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranties of
* MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef ANBOX_TCPSOCKETCONNECTOR_H
#define ANBOX_TCPSOCKETCONNECTOR_H
#include <boost/asio/ip/tcp.hpp>
#include "anbox/do_not_copy_or_move.h"
#include "anbox/runtime.h"
#include "anbox/network/connection_creator.h"
#include "anbox/network/connector.h"
namespace anbox::network {
class TcpSocketConnector : public DoNotCopyOrMove, public Connector {
public:
explicit TcpSocketConnector(
const boost::asio::ip::address_v4 &address, unsigned short port,
const std::shared_ptr<Runtime> &rt,
const std::shared_ptr<ConnectionCreator<boost::asio::ip::tcp>>
&connection_creator);
~TcpSocketConnector() noexcept;
unsigned short port() const { return port_; }
private:
void start_accept();
void on_new_connection(
std::shared_ptr<boost::asio::ip::tcp::socket> const &socket,
boost::system::error_code const &err);
boost::asio::ip::address_v4 address_;
unsigned short port_;
std::shared_ptr<Runtime> runtime_;
std::shared_ptr<ConnectionCreator<boost::asio::ip::tcp>> connection_creator_;
boost::asio::ip::tcp::acceptor acceptor_;
};
}
#endif
| 1,775
|
C++
|
.h
| 46
| 35.73913
| 79
| 0.746078
|
anbox/anbox
| 8,865
| 1,152
| 381
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
17,980
|
connection_context.h
|
anbox_anbox/src/anbox/network/connection_context.h
|
/*
* Copyright © 2014 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Alan Griffiths <alan@octopull.co.uk>
*/
#ifndef ANBOX_NETWORK_CONNECTION_CONTEXT_H_
#define ANBOX_NETWORK_CONNECTION_CONTEXT_H_
#include <functional>
#include <memory>
namespace anbox::network {
class Connector;
class ConnectionContext {
public:
ConnectionContext(Connector const* connector)
: ConnectionContext([]() {}, connector) {}
ConnectionContext(std::function<void()> const connect_handler,
Connector const* connector);
int fd_for_new_client(std::function<void()> const& connect_handler) const;
void handle_client_connect() const { connect_handler(); }
private:
std::function<void()> const connect_handler;
Connector const* const connector;
};
}
#endif
| 1,351
|
C++
|
.h
| 37
| 33.810811
| 76
| 0.750574
|
anbox/anbox
| 8,865
| 1,152
| 381
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
17,983
|
stream_socket_transport.h
|
anbox_anbox/src/anbox/network/stream_socket_transport.h
|
/*
* Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3, as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranties of
* MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef ANBOX_STREAM_SOCKET_TRANSPORT_H_
#define ANBOX_STREAM_SOCKET_TRANSPORT_H_
#include "anbox/common/fd.h"
#include "anbox/network/socket_messenger.h"
#include "anbox/runtime.h"
#include <memory>
#include <boost/asio.hpp>
namespace anbox::network {
class StreamSocketTransport {
public:
class Observer {
public:
Observer() = default;
virtual ~Observer() = default;
virtual void on_data_available() = 0;
virtual void on_disconnected() = 0;
Observer(Observer const&) = delete;
Observer& operator=(Observer const&) = delete;
};
StreamSocketTransport(const std::string& socket_path,
const std::shared_ptr<Runtime>& rt);
void register_observer(std::shared_ptr<Observer> const& observer_);
void unregister_observer(std::shared_ptr<Observer> const& observer_);
void send_message(std::vector<uint8_t> const& buffer);
void read_next_message();
private:
void on_read_size(const boost::system::error_code& ec,
std::size_t bytes_read);
std::shared_ptr<Observer> observer_;
std::shared_ptr<boost::asio::local::stream_protocol::socket> socket_;
SocketMessenger messenger_;
};
}
#endif // STREAM_SOCKET_TRANSPORT_H_
| 1,887
|
C++
|
.h
| 50
| 34.3
| 76
| 0.729863
|
anbox/anbox
| 8,865
| 1,152
| 381
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
17,984
|
tcp_socket_messenger.h
|
anbox_anbox/src/anbox/network/tcp_socket_messenger.h
|
/*
* Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3, as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranties of
* MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef ANBOX_NETWORK_TCP_SOCKET_MESSENGER_H_
#define ANBOX_NETWORK_TCP_SOCKET_MESSENGER_H_
#include "anbox/network/base_socket_messenger.h"
#include "anbox/runtime.h"
#include <boost/asio.hpp>
namespace anbox::network {
class TcpSocketMessenger : public BaseSocketMessenger<boost::asio::ip::tcp> {
public:
TcpSocketMessenger(const boost::asio::ip::address_v4 &addr,
unsigned short port, const std::shared_ptr<Runtime> &rt);
TcpSocketMessenger(
std::shared_ptr<boost::asio::ip::tcp::socket> const &socket);
~TcpSocketMessenger();
unsigned short local_port() const override;
private:
unsigned short local_port_;
};
}
#endif
| 1,342
|
C++
|
.h
| 35
| 35.628571
| 78
| 0.751729
|
anbox/anbox
| 8,865
| 1,152
| 381
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
17,989
|
delegate_message_processor.h
|
anbox_anbox/src/anbox/network/delegate_message_processor.h
|
/*
* Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3, as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranties of
* MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef ANBOX_NETWORK_DELEGATE_MESSAGE_PROCESSOR_H_
#define ANBOX_NETWORK_DELEGATE_MESSAGE_PROCESSOR_H_
#include "anbox/network/message_processor.h"
#include <functional>
namespace anbox::network {
class DelegateMessageProcessor : public MessageProcessor {
public:
DelegateMessageProcessor(
std::function<bool(const std::vector<std::uint8_t> &)> process_data);
~DelegateMessageProcessor();
bool process_data(const std::vector<std::uint8_t> &data) override;
private:
std::function<bool(const std::vector<std::uint8_t> &)> process_data_;
};
}
#endif
| 1,244
|
C++
|
.h
| 32
| 36.71875
| 76
| 0.766169
|
anbox/anbox
| 8,865
| 1,152
| 381
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
17,991
|
credentials.h
|
anbox_anbox/src/anbox/network/credentials.h
|
/*
* Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3, as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranties of
* MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef ANBOX_NETWORK_CREDENTIALS_H_
#define ANBOX_NETWORK_CREDENTIALS_H_
#include <sys/types.h>
namespace anbox::network {
class Credentials {
public:
Credentials(pid_t pid, uid_t uid, gid_t gid);
pid_t pid() const;
uid_t uid() const;
gid_t gid() const;
private:
Credentials() = delete;
pid_t pid_;
uid_t uid_;
gid_t gid_;
};
}
#endif
| 1,034
|
C++
|
.h
| 34
| 28.264706
| 76
| 0.740443
|
anbox/anbox
| 8,865
| 1,152
| 381
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
17,992
|
message_processor.h
|
anbox_anbox/src/anbox/network/message_processor.h
|
/*
* Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3, as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranties of
* MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef ANBOX_NETWORK_MESSAGE_PROCESSOR_H
#define ANBOX_NETWORK_MESSAGE_PROCESSOR_H
#include <cstdint>
#include <vector>
#include "anbox/common/small_vector.h"
namespace anbox::network {
using MessageBuffer = anbox::common::SmallFixedVector<char, 512>;
class MessageProcessor {
public:
virtual ~MessageProcessor() {}
virtual bool process_data(const std::vector<std::uint8_t> &) { return false; }
virtual bool process_data(MessageBuffer &&) { return false; }
};
}
#endif
| 1,154
|
C++
|
.h
| 31
| 35.419355
| 80
| 0.764286
|
anbox/anbox
| 8,865
| 1,152
| 381
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
17,994
|
socket_messenger.h
|
anbox_anbox/src/anbox/network/socket_messenger.h
|
/*
* Copyright © 2013-2014 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Kevin DuBois <kevin.dubois@canonical.com>
*/
#ifndef ANBOX_NETWORK_SOCKET_MESSENGER_H_
#define ANBOX_NETWORK_SOCKET_MESSENGER_H_
#include <mutex>
#include "anbox/network/credentials.h"
#include "anbox/network/message_receiver.h"
#include "anbox/network/message_sender.h"
namespace anbox::network {
class SocketMessenger : public MessageSender, public MessageReceiver {
public:
virtual Credentials creds() const = 0;
virtual unsigned short local_port() const = 0;
virtual void set_no_delay() = 0;
virtual void close() = 0;
};
}
#endif
| 1,195
|
C++
|
.h
| 33
| 34.333333
| 72
| 0.765976
|
anbox/anbox
| 8,865
| 1,152
| 381
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
17,995
|
connector.h
|
anbox_anbox/src/anbox/network/connector.h
|
/*
* Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3, as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranties of
* MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef ANBOX_NETWORK_CONNECTOR_H
#define ANBOX_NETWORK_CONNECTOR_H
namespace anbox::network {
class Connector {
public:
};
}
#endif
| 810
|
C++
|
.h
| 24
| 32
| 76
| 0.766582
|
anbox/anbox
| 8,865
| 1,152
| 381
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
17,996
|
published_socket_connector.h
|
anbox_anbox/src/anbox/network/published_socket_connector.h
|
/*
* Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3, as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranties of
* MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef ANBOX_PUBLISHEDSOCKETCONNECTOR_H
#define ANBOX_PUBLISHEDSOCKETCONNECTOR_H
#include <boost/asio/local/stream_protocol.hpp>
#include "anbox/do_not_copy_or_move.h"
#include "anbox/runtime.h"
#include "anbox/network/connection_creator.h"
#include "anbox/network/connector.h"
namespace anbox::network {
class PublishedSocketConnector : public DoNotCopyOrMove, public Connector {
public:
explicit PublishedSocketConnector(
const std::string& socket_file, const std::shared_ptr<Runtime>& rt,
const std::shared_ptr<ConnectionCreator<
boost::asio::local::stream_protocol>>& connection_creator);
~PublishedSocketConnector() noexcept;
std::string socket_file() const { return socket_file_; }
private:
void start_accept();
void on_new_connection(
std::shared_ptr<boost::asio::local::stream_protocol::socket> const& socket,
boost::system::error_code const& err);
const std::string socket_file_;
std::shared_ptr<Runtime> runtime_;
std::shared_ptr<ConnectionCreator<boost::asio::local::stream_protocol>>
connection_creator_;
boost::asio::local::stream_protocol::acceptor acceptor_;
};
}
#endif
| 1,829
|
C++
|
.h
| 45
| 37.8
| 81
| 0.758446
|
anbox/anbox
| 8,865
| 1,152
| 381
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,103
|
itemfakevim.cpp
|
hluk_CopyQ/plugins/itemfakevim/itemfakevim.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemfakevim.h"
#include "ui_itemfakevimsettings.h"
#include "tests/itemfakevimtests.h"
#include "common/contenttype.h"
#include "fakevim/fakevimhandler.h"
using namespace FakeVim::Internal;
#include <QIcon>
#include <QLabel>
#include <QDialogButtonBox>
#include <QLineEdit>
#include <QMessageBox>
#include <QMetaMethod>
#include <QKeyEvent>
#include <QPaintEvent>
#include <QPainter>
#include <QRegularExpression>
#include <QStatusBar>
#include <QTextBlock>
#include <QTextEdit>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QAbstractTextDocumentLayout>
#include <QScrollBar>
#include <QSettings>
#include <QStyle>
#include <QStyleHints>
#include <QVariantMap>
#include <QtPlugin>
#define EDITOR(s) (m_textEdit ? m_textEdit->s : m_plainTextEdit->s)
namespace {
const char propertyWrapped[] = "CopyQ_fakevim_wrapped";
const QLatin1String configReallyEnabled("really_enable");
const QLatin1String configSourceFile("source_file");
// The same method for rendering document doesn't work for QPlainTextEdit.
// This is simplified code from Qt source code.
void drawPlainTextDocument(
QPlainTextEdit *textEdit,
const QAbstractTextDocumentLayout::PaintContext context,
QPainter *painter)
{
// WORKAROUND: Access protected members of QPlainTextEdit.
class PlainTextEdit final : public QPlainTextEdit {
public:
static QPointF getContentOffset(QPlainTextEdit *edit) {
return (edit->*(&PlainTextEdit::contentOffset))();
}
static QTextBlock getFirstVisibleBlock(QPlainTextEdit *edit) {
return (edit->*(&PlainTextEdit::firstVisibleBlock))();
}
};
QPointF offset = PlainTextEdit::getContentOffset(textEdit);
QTextBlock block = PlainTextEdit::getFirstVisibleBlock(textEdit);
QTextDocument *doc = textEdit->document();
const auto documentLayout = doc->documentLayout();
painter->setBrushOrigin(offset);
while (block.isValid()) {
const QRectF r = documentLayout->blockBoundingRect(block).translated(offset);
if (block.isVisible()) {
QTextLayout *layout = block.layout();
QVector<QTextLayout::FormatRange> selections;
int blpos = block.position();
int bllen = block.length();
for (int i = 0; i < context.selections.size(); ++i) {
const QAbstractTextDocumentLayout::Selection &range = context.selections.at(i);
const int selStart = range.cursor.selectionStart() - blpos;
const int selEnd = range.cursor.selectionEnd() - blpos;
if (selStart < bllen && selEnd > 0
&& selEnd > selStart) {
QTextLayout::FormatRange o;
o.start = selStart;
o.length = selEnd - selStart;
o.format = range.format;
selections.append(o);
} else if (!range.cursor.hasSelection() && range.format.hasProperty(QTextFormat::FullWidthSelection)
&& block.contains(range.cursor.position())) {
// for full width selections we don't require an actual selection, just
// a position to specify the line. that's more convenience in usage.
QTextLayout::FormatRange o;
QTextLine l = layout->lineForTextPosition(range.cursor.position() - blpos);
o.start = l.textStart();
o.length = l.textLength();
if (o.start + o.length == bllen - 1)
++o.length; // include newline
o.format = range.format;
selections.append(o);
}
}
layout->draw(painter, offset, selections);
}
offset.ry() += r.height();
if (offset.y() > context.clip.bottom())
break;
block = block.next();
}
}
class TextEditWrapper final : public QObject
{
public:
explicit TextEditWrapper(QAbstractScrollArea *editor)
: QObject(editor)
, m_textEditWidget(editor)
, m_textEdit(qobject_cast<QTextEdit *>(editor))
, m_plainTextEdit(qobject_cast<QPlainTextEdit *>(editor))
, m_handler(new FakeVimHandler(editor, nullptr))
, m_hasBlockSelection(false)
{
editor->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
if (m_textEdit) {
connect( m_textEdit, &QTextEdit::selectionChanged,
this, &TextEditWrapper::onSelectionChanged );
connect( m_textEdit, &QTextEdit::cursorPositionChanged,
this, &TextEditWrapper::onSelectionChanged );
} else if (m_plainTextEdit) {
connect( m_plainTextEdit, &QPlainTextEdit::selectionChanged,
this, &TextEditWrapper::onSelectionChanged );
connect( m_plainTextEdit, &QPlainTextEdit::cursorPositionChanged,
this, &TextEditWrapper::onSelectionChanged );
}
setLineWrappingEnabled(true);
editor->viewport()->installEventFilter(this);
auto completer = editor->findChild<QObject*>("CommandCompleter");
if (completer) {
m_completerPopup = completer->property("popup").value<QWidget*>();
Q_ASSERT(m_completerPopup);
if (m_completerPopup)
m_completerPopup->installEventFilter(this);
}
// Let FakeVim handle indentation.
m_handler->handleCommand(QLatin1String("set nopasskeys"));
}
~TextEditWrapper()
{
m_handler->disconnectFromEditor();
m_handler->deleteLater();
}
void install()
{
m_handler->installEventFilter();
m_handler->setupWidget();
m_handler->enterCommandMode();
}
bool eventFilter(QObject *obj, QEvent *ev) override
{
// Handle completion popup.
if (obj == m_completerPopup) {
if ( ev->type() == QEvent::KeyPress ) {
const auto kev = static_cast<QKeyEvent *>(ev);
const auto key = kev->key();
const auto mods = kev->modifiers();
if (mods.testFlag(Qt::ControlModifier)) {
if (key == Qt::Key_N || key == Qt::Key_P) {
const auto key2 = key == Qt::Key_N ? Qt::Key_Down : Qt::Key_Up;
QKeyEvent kev2(QEvent::KeyPress, key2, Qt::NoModifier);
QCoreApplication::sendEvent(obj, &kev2);
return true;
}
}
switch (key) {
case Qt::Key_Enter:
case Qt::Key_Return:
return false;
case Qt::Key_Down:
case Qt::Key_Up:
case Qt::Key_PageDown:
case Qt::Key_PageUp:
return false;
default:
QCoreApplication::sendEvent(m_textEditWidget, ev);
return true;
}
}
return false;
}
if ( ev->type() != QEvent::Paint )
return false;
QWidget *viewport = editor()->viewport();
QPaintEvent *e = static_cast<QPaintEvent*>(ev);
const QRect r = e->rect();
QPainter painter(viewport);
const QTextCursor tc = EDITOR(textCursor());
m_context.cursorPosition = -1;
m_context.palette = editor()->palette();
const int h = m_textEdit ? horizontalOffset() : 0;
const int v = m_textEdit ? verticalOffset() : 0;
m_context.clip = r.translated(h, v);
painter.save();
// Draw base and text.
painter.translate(-h, -v);
paintDocument(&painter);
// Draw block selection.
if ( hasBlockSelection() ) {
QRect rect;
QTextCursor tc2 = tc;
tc2.setPosition(tc.position());
rect = EDITOR(cursorRect(tc2));
tc2.setPosition(tc.anchor());
rect = rect.united( EDITOR(cursorRect(tc2)) );
m_context.palette.setColor(QPalette::Base, m_context.palette.color(QPalette::Highlight));
m_context.palette.setColor(QPalette::Text, m_context.palette.color(QPalette::HighlightedText));
m_context.clip = rect.translated(h, v);
paintDocument(&painter);
}
painter.restore();
// Draw text cursor.
QRect rect = EDITOR(cursorRect());
if (EDITOR(overwriteMode()) || hasBlockSelection() ) {
QTextCursor tc2 = tc;
tc2.movePosition(QTextCursor::Right);
const QRect nextRect = EDITOR(cursorRect(tc2));
const int w = nextRect.left() - rect.left();
if (w > 3) {
rect.setWidth(w);
} else {
const QFontMetrics fm(editor()->font());
rect.setWidth( fm.averageCharWidth() );
}
} else {
rect.setWidth(2);
rect.adjust(-1, 0, 0, 0);
}
if ( hasBlockSelection() ) {
int from = tc.positionInBlock();
int to = tc.anchor() - tc.document()->findBlock(tc.anchor()).position();
if (from > to)
rect.moveLeft(rect.left() - rect.width());
}
painter.setCompositionMode(QPainter::CompositionMode_Difference);
const auto color = editor()->hasFocus() ? Qt::white : Qt::darkGray;
painter.fillRect(rect, color);
if (!hasBlockSelection() && m_cursorRect.width() != rect.width())
viewport->update();
m_cursorRect = rect;
return true;
}
FakeVimHandler &fakeVimHandler() { return *m_handler; }
void highlightMatches(const QString &pattern)
{
QTextCursor cur = EDITOR(textCursor());
Selection selection;
selection.format.setBackground(Qt::yellow);
selection.format.setForeground(Qt::black);
// Highlight matches.
QTextDocument *doc = document();
QRegularExpression re(pattern);
cur = doc->find(re);
m_searchSelection.clear();
int a = cur.position();
while ( !cur.isNull() ) {
if ( cur.hasSelection() ) {
selection.cursor = cur;
m_searchSelection.append(selection);
} else {
cur.movePosition(QTextCursor::NextCharacter);
}
cur = doc->find(re, cur);
int b = cur.position();
if (a == b) {
cur.movePosition(QTextCursor::NextCharacter);
cur = doc->find(re, cur);
b = cur.position();
if (a == b) break;
}
a = b;
}
updateSelections();
}
void setBlockSelection(bool on)
{
m_hasBlockSelection = on;
m_selection.clear();
updateSelections();
}
bool hasBlockSelection() const
{
return m_hasBlockSelection;
}
void setTextCursor(const QTextCursor &tc)
{
EDITOR(setTextCursor(tc));
}
QTextCursor textCursor() const
{
return EDITOR(textCursor());
}
QTextDocument *document() const
{
return EDITOR(document());
}
QAbstractScrollArea *editor() const { return m_textEditWidget; }
void setLineWrappingEnabled(bool enable)
{
if (m_textEdit)
m_textEdit->setLineWrapMode(enable ? QTextEdit::WidgetWidth : QTextEdit::NoWrap);
else if (m_plainTextEdit)
m_plainTextEdit->setLineWrapMode(enable ? QPlainTextEdit::WidgetWidth : QPlainTextEdit::NoWrap);
}
private:
void onSelectionChanged() {
m_hasBlockSelection = false;
m_selection.clear();
Selection selection;
const QPalette pal = editor()->palette();
selection.format.setBackground( pal.color(QPalette::Highlight) );
selection.format.setForeground( pal.color(QPalette::HighlightedText) );
selection.cursor = EDITOR(textCursor());
if ( selection.cursor.hasSelection() )
m_selection.append(selection);
updateSelections();
}
int horizontalOffset() const
{
QScrollBar *hbar = editor()->horizontalScrollBar();
return editor()->isRightToLeft() ? (hbar->maximum() - hbar->value()) : hbar->value();
}
int verticalOffset() const
{
return editor()->verticalScrollBar()->value();
}
void paintDocument(QPainter *painter)
{
painter->setClipRect(m_context.clip);
painter->fillRect(m_context.clip, m_context.palette.base());
if (m_textEdit)
document()->documentLayout()->draw(painter, m_context);
else if (m_plainTextEdit)
drawPlainTextDocument(m_plainTextEdit, m_context, painter);
}
void updateSelections()
{
m_context.selections.clear();
m_context.selections.reserve( m_searchSelection.size() + m_selection.size() );
m_context.selections << m_searchSelection << m_selection;
editor()->viewport()->update();
}
QAbstractScrollArea *m_textEditWidget;
QTextEdit *m_textEdit;
QPlainTextEdit *m_plainTextEdit;
FakeVimHandler *m_handler;
QObject *m_completerPopup = nullptr;
QRect m_cursorRect;
bool m_hasBlockSelection;
using Selection = QAbstractTextDocumentLayout::Selection;
using SelectionList = QVector<Selection>;
SelectionList m_searchSelection;
SelectionList m_selection;
QAbstractTextDocumentLayout::PaintContext m_context;
};
class Proxy final : public QObject
{
public:
Proxy(TextEditWrapper *editorWidget, QStatusBar *statusBar, QObject *parent = nullptr)
: QObject(parent)
, m_editorWidget(editorWidget)
, m_statusBar(statusBar)
, m_edit(new QLineEdit(statusBar))
, m_statusBarMessage(new QLabel(statusBar))
, m_statusBarData(new QLabel(statusBar))
, m_statusBarIcon(new QLabel(statusBar))
{
connect(m_edit, &QLineEdit::textEdited, this, &Proxy::cmdLineChanged);
connect(m_edit, &QLineEdit::cursorPositionChanged, this, &Proxy::cmdLineChanged);
connect(m_edit, &QLineEdit::selectionChanged, this, &Proxy::cmdLineChanged);
m_edit->setFrame(false);
m_edit->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
m_edit->installEventFilter( &m_editorWidget->fakeVimHandler() );
m_statusBar->insertWidget(0, m_edit, 4);
m_edit->hide();
m_statusBar->insertWidget(1, m_statusBarMessage, 1);
m_statusBarMessage->show();
m_statusBar->addPermanentWidget(m_statusBarData);
m_statusBarData->show();
m_statusBar->addPermanentWidget(m_statusBarIcon);
m_statusBarIcon->show();
}
void changeStatusData(const QString &info)
{
m_statusBarData->setText(info);
}
void highlightMatches(const QString &pattern)
{
m_editorWidget->highlightMatches(pattern);
}
void setStatusIcon(QStyle::StandardPixmap standardPixmap)
{
const auto icon = m_statusBarIcon->style()->standardIcon(standardPixmap);
const auto maxHeight = m_statusBarIcon->contentsRect().height();
const auto window = m_statusBarIcon->windowHandle();
auto sizes = icon.availableSizes();
std::sort(std::begin(sizes), std::end(sizes), [](const QSize &lhs, const QSize &rhs){
return lhs.height() > rhs.height();
});
const auto it = std::lower_bound(
sizes.begin(), sizes.end(), maxHeight,
[](const QSize &size, int height){
return size.height() > height;
});
const auto size = it == sizes.end() ? icon.actualSize(window, QSize(maxHeight, maxHeight)) : *it;
const auto pixmap = icon.pixmap(window, size);
m_statusBarIcon->setPixmap(pixmap);
}
void changeStatusMessage(
const QString &contents, int cursorPos, int anchorPos, int messageLevel)
{
if (cursorPos == -1) {
if ( m_edit->hasFocus() )
m_editorWidget->editor()->setFocus();
m_edit->hide();
m_statusBarMessage->setText(contents);
} else {
m_statusBarMessage->clear();
{
QSignalBlocker blocker(m_edit);
m_edit->setText(contents);
if (anchorPos != -1 && anchorPos != cursorPos)
m_edit->setSelection(anchorPos, cursorPos - anchorPos);
else
m_edit->setCursorPosition(cursorPos);
}
m_edit->show();
m_edit->setFocus();
}
if (messageLevel == MessageWarning)
setStatusIcon(QStyle::SP_MessageBoxWarning);
else if (messageLevel == MessageError)
setStatusIcon(QStyle::SP_MessageBoxCritical);
else
m_statusBarIcon->clear();
}
void changeExtraInformation(const QString &info)
{
QMessageBox::information(m_editorWidget->editor(), tr("Information"), info);
}
void handleExCommand(bool *handled, const ExCommand &cmd)
{
if ( m_edit->hasFocus() )
m_editorWidget->editor()->setFocus();
if (cmd.cmd == "set") {
QString arg = cmd.args;
bool enable = !arg.startsWith("no");
if (enable)
arg.remove(0, 2);
*handled = setOption(arg, enable);
} else if ( wantSaveAndQuit(cmd) ) {
// :wq
saveAndClose();
*handled = true;
} else if ( wantSave(cmd) ) {
save(); // :w
*handled = true;
} else if ( wantQuit(cmd) ) {
if (cmd.hasBang)
invalidate(); // :q!
else
cancel(); // :q
*handled = true;
} else {
*handled = false;
}
}
void requestSetBlockSelection(const QTextCursor &cursor)
{
m_editorWidget->setTextCursor(cursor);
m_editorWidget->setBlockSelection(true);
}
void requestDisableBlockSelection()
{
m_editorWidget->setBlockSelection(false);
}
void requestBlockSelection(QTextCursor *cursor)
{
*cursor = m_editorWidget->textCursor();
m_editorWidget->setBlockSelection(true);
}
private:
void cmdLineChanged()
{
const int cursorPos = m_edit->cursorPosition();
int anchorPos = m_edit->selectionStart();
if (anchorPos == cursorPos)
anchorPos = cursorPos + m_edit->selectedText().length();
edited(m_edit->text(), cursorPos, anchorPos);
}
void edited(const QString &text, int cursorPos, int anchorPos)
{
m_editorWidget->fakeVimHandler().miniBufferTextEdited(text, cursorPos, anchorPos);
}
bool emitEditorSignal(const char *signal)
{
const auto editor = m_editorWidget->editor();
const QMetaObject *metaObject = editor->metaObject();
const int i = metaObject->indexOfSignal(signal);
if (i == -1)
return false;
metaObject->method(i).invoke(editor);
return true;
}
void clickDialogButton(QDialogButtonBox::StandardButton standardButton)
{
const auto window = m_editorWidget->editor()->window();
const auto buttonBox = window->findChild<QDialogButtonBox*>();
QPushButton *button = buttonBox->button(standardButton);
if (button)
button->click();
}
void save()
{
if ( !emitEditorSignal("save()") )
clickDialogButton(QDialogButtonBox::Apply);
}
void saveAndClose()
{
if ( !emitEditorSignal("save()") || !emitEditorSignal("cancel()") )
clickDialogButton(QDialogButtonBox::Ok);
}
void cancel()
{
if ( !emitEditorSignal("cancel()") )
clickDialogButton(QDialogButtonBox::Cancel);
}
void invalidate()
{
if ( !emitEditorSignal("invalidate()") )
clickDialogButton(QDialogButtonBox::Cancel);
}
bool wantSaveAndQuit(const ExCommand &cmd)
{
return cmd.cmd == "wq";
}
bool wantSave(const ExCommand &cmd)
{
return cmd.matches("w", "write") || cmd.matches("wa", "wall");
}
bool wantQuit(const ExCommand &cmd)
{
return cmd.matches("q", "quit") || cmd.matches("qa", "qall");
}
bool setOption(const QString &option, bool enable)
{
if (option == "linebreak" || option == "lbr")
m_editorWidget->setLineWrappingEnabled(enable);
else
return false;
return true;
}
TextEditWrapper *m_editorWidget;
QStatusBar *m_statusBar;
QLineEdit *m_edit;
QLabel *m_statusBarMessage;
QLabel *m_statusBarData;
QLabel *m_statusBarIcon;
};
void connectSignals(FakeVimHandler *handler, Proxy *proxy)
{
handler->commandBufferChanged
.connect([proxy](const QString &contents, int cursorPos, int anchorPos, int messageLevel) {
proxy->changeStatusMessage(contents, cursorPos, anchorPos, messageLevel);
}
);
handler->extraInformationChanged.connect(
[proxy](const QString &msg) {
proxy->changeExtraInformation(msg);
}
);
handler->statusDataChanged.connect(
[proxy](const QString &msg) {
proxy->changeStatusData(msg);
}
);
handler->highlightMatches.connect(
[proxy](const QString &needle) {
proxy->highlightMatches(needle);
}
);
handler->handleExCommandRequested.connect(
[proxy](bool *handled, const ExCommand &cmd) {
proxy->handleExCommand(handled, cmd);
}
);
handler->requestSetBlockSelection.connect(
[proxy](const QTextCursor &cursor) {
proxy->requestSetBlockSelection(cursor);
}
);
handler->requestDisableBlockSelection.connect(
[proxy]() {
proxy->requestDisableBlockSelection();
}
);
handler->requestBlockSelection.connect(
[proxy](QTextCursor *cursor) {
proxy->requestBlockSelection(cursor);
}
);
}
bool installEditor(QAbstractScrollArea *textEdit, const QString &sourceFileName, ItemFakeVimLoader *loader)
{
auto wrapper = new TextEditWrapper(textEdit);
// Position text cursor at the beginning of text instead of selecting all.
wrapper->setTextCursor( QTextCursor(wrapper->document()) );
QStatusBar *statusBar = new QStatusBar(textEdit);
statusBar->setObjectName("editor_status_bar");
const auto layout = textEdit->parentWidget()->layout();
if (layout)
layout->addWidget(statusBar);
statusBar->setFont(textEdit->font());
// Connect slots to FakeVimHandler signals.
auto proxy = new Proxy(wrapper, statusBar, wrapper);
connectSignals( &wrapper->fakeVimHandler(), proxy );
wrapper->install();
if (!sourceFileName.isEmpty())
wrapper->fakeVimHandler().handleCommand("source " + sourceFileName);
QObject::connect(loader, &ItemFakeVimLoader::deleteAllWrappers, wrapper, &QObject::deleteLater);
QObject::connect(loader, &ItemFakeVimLoader::deleteAllWrappers, statusBar, &QObject::deleteLater);
QObject::connect(loader, &ItemFakeVimLoader::deleteAllWrappers, textEdit, [textEdit](){
textEdit->setProperty(propertyWrapped, false);
});
return true;
}
template <typename TextEdit>
bool installEditor(QObject *obj, const QString &sourceFileName, ItemFakeVimLoader *loader)
{
auto textEdit = qobject_cast<TextEdit *>(obj);
return textEdit && !textEdit->isReadOnly() && installEditor(textEdit, sourceFileName, loader);
}
} // namespace
ItemFakeVimLoader::ItemFakeVimLoader()
{
}
ItemFakeVimLoader::~ItemFakeVimLoader() = default;
QVariant ItemFakeVimLoader::icon() const
{
return QIcon(":/fakevim/fakevim.png");
}
void ItemFakeVimLoader::setEnabled(bool enabled)
{
ItemLoaderInterface::setEnabled(enabled);
updateCurrentlyEnabledState();
}
void ItemFakeVimLoader::applySettings(QSettings &settings)
{
settings.setValue(configReallyEnabled, ui->checkBoxEnable->isChecked());
settings.setValue(configSourceFile, ui->lineEditSourceFileName->text());
}
void ItemFakeVimLoader::loadSettings(const QSettings &settings)
{
m_reallyEnabled = settings.value(configReallyEnabled, false).toBool();
m_sourceFileName = settings.value(configSourceFile).toString();
updateCurrentlyEnabledState();
}
QWidget *ItemFakeVimLoader::createSettingsWidget(QWidget *parent)
{
ui.reset(new Ui::ItemFakeVimSettings);
QWidget *w = new QWidget(parent);
ui->setupUi(w);
ui->checkBoxEnable->setChecked(m_reallyEnabled);
ui->lineEditSourceFileName->setText(m_sourceFileName);
return w;
}
QObject *ItemFakeVimLoader::tests(const TestInterfacePtr &test) const
{
#ifdef HAS_TESTS
QVariantMap settings;
settings["really_enable"] = true;
settings["source_file"] = QString(ItemFakeVimTests::fileNameToSource());
QObject *tests = new ItemFakeVimTests(test);
tests->setProperty("CopyQ_test_settings", settings);
return tests;
#else
Q_UNUSED(test)
return nullptr;
#endif
}
bool ItemFakeVimLoader::eventFilter(QObject *watched, QEvent *event)
{
if (event->type() == QEvent::Show)
wrapEditWidget(watched);
return false;
}
void ItemFakeVimLoader::updateCurrentlyEnabledState()
{
if ( qobject_cast<QGuiApplication*>(qApp) == nullptr )
return;
const bool enable = isEnabled() && m_reallyEnabled;
if (m_currentlyEnabled == enable)
return;
if (enable) {
// WORKAROUND: Disallow blinking text cursor application-wide
// (unfortunately, there doesn't seem other way to do this).
m_oldCursorFlashTime = qApp->cursorFlashTime();
qApp->setCursorFlashTime(0);
qApp->installEventFilter(this);
for (auto topLevel : qApp->topLevelWidgets()) {
for ( auto textEdit : topLevel->findChildren<QTextEdit*>() )
wrapEditWidget(textEdit);
for ( auto textEdit : topLevel->findChildren<QPlainTextEdit*>() )
wrapEditWidget(textEdit);
}
} else {
emit deleteAllWrappers();
qApp->removeEventFilter(this);
qApp->setCursorFlashTime(m_oldCursorFlashTime);
}
m_currentlyEnabled = enable;
}
void ItemFakeVimLoader::wrapEditWidget(QObject *obj)
{
if ( !obj->property(propertyWrapped).toBool()
&& ( installEditor<QTextEdit>(obj, m_sourceFileName, this)
|| installEditor<QPlainTextEdit>(obj, m_sourceFileName, this) )
)
{
obj->setProperty(propertyWrapped, true);
}
}
| 26,921
|
C++
|
.cpp
| 715
| 29.039161
| 116
| 0.620531
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,104
|
fakevimactions.cpp
|
hluk_CopyQ/plugins/itemfakevim/fakevim/fakevimactions.cpp
|
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0
#include "fakevimactions.h"
#include "fakevimhandler.h"
// Please do not add any direct dependencies to other Qt Creator code here.
// Instead emit signals and let the FakeVimPlugin channel the information to
// Qt Creator. The idea is to keep this file here in a "clean" state that
// allows easy reuse with any QTextEdit or QPlainTextEdit derived class.
namespace FakeVim {
namespace Internal {
#ifdef FAKEVIM_STANDALONE
FvBaseAspect::FvBaseAspect()
{
}
void FvBaseAspect::setValue(const QVariant &value)
{
m_value = value;
}
QVariant FvBaseAspect::value() const
{
return m_value;
}
void FvBaseAspect::setDefaultValue(const QVariant &value)
{
m_defaultValue = value;
m_value = value;
}
QVariant FvBaseAspect::defaultValue() const
{
return m_defaultValue;
}
void FvBaseAspect::setSettingsKey(const QString &group, const QString &key)
{
m_settingsGroup = group;
m_settingsKey = key;
}
QString FvBaseAspect::settingsKey() const
{
return m_settingsKey;
}
// unused but kept for compile
void setAutoApply(bool ) {}
#endif
FakeVimSettings::FakeVimSettings()
{
setAutoApply(false);
#ifndef FAKEVIM_STANDALONE
setup(&useFakeVim, false, "UseFakeVim", {}, tr("Use FakeVim"));
#endif
// Specific FakeVim settings
setup(&readVimRc, false, "ReadVimRc", {}, tr("Read .vimrc from location:"));
setup(&vimRcPath, QString(), "VimRcPath", {}, {}); // tr("Path to .vimrc")
setup(&showMarks, false, "ShowMarks", "sm", tr("Show position of text marks"));
setup(&passControlKey, false, "PassControlKey", "pck", tr("Pass control keys"));
setup(&passKeys, true, "PassKeys", "pk", tr("Pass keys in insert mode"));
// Emulated Vsetting
setup(&startOfLine, true, "StartOfLine", "sol", tr("Start of line"));
setup(&tabStop, 8, "TabStop", "ts", tr("Tabulator size:"));
setup(&smartTab, false, "SmartTab", "sta", tr("Smart tabulators"));
setup(&hlSearch, true, "HlSearch", "hls", tr("Highlight search results"));
setup(&shiftWidth, 8, "ShiftWidth", "sw", tr("Shift width:"));
setup(&expandTab, false, "ExpandTab", "et", tr("Expand tabulators"));
setup(&autoIndent, false, "AutoIndent", "ai", tr("Automatic indentation"));
setup(&smartIndent, false, "SmartIndent", "si", tr("Smart indentation"));
setup(&incSearch, true, "IncSearch", "is", tr("Incremental search"));
setup(&useCoreSearch, false, "UseCoreSearch", "ucs", tr("Use search dialog"));
setup(&smartCase, false, "SmartCase", "scs", tr("Use smartcase"));
setup(&ignoreCase, false, "IgnoreCase", "ic", tr("Use ignorecase"));
setup(&wrapScan, true, "WrapScan", "ws", tr("Use wrapscan"));
setup(&tildeOp, false, "TildeOp", "top", tr("Use tildeop"));
setup(&showCmd, true, "ShowCmd", "sc", tr("Show partial command"));
setup(&relativeNumber, false, "RelativeNumber", "rnu", tr("Show line numbers relative to cursor"));
setup(&blinkingCursor, false, "BlinkingCursor", "bc", tr("Blinking cursor"));
setup(&scrollOff, 0, "ScrollOff", "so", tr("Scroll offset:"));
setup(&backspace, "indent,eol,start",
"Backspace", "bs", tr("Backspace:"));
setup(&isKeyword, "@,48-57,_,192-255,a-z,A-Z",
"IsKeyword", "isk", tr("Keyword characters:"));
setup(&clipboard, {}, "Clipboard", "cb", tr(""));
setup(&formatOptions, {}, "formatoptions", "fo", tr("")); // pragma: codespell-ignore
// Emulated plugins
setup(&emulateVimCommentary, false, "commentary", {}, "vim-commentary");
setup(&emulateReplaceWithRegister, false, "ReplaceWithRegister", {}, "ReplaceWithRegister");
setup(&emulateExchange, false, "exchange", {}, "vim-exchange");
setup(&emulateArgTextObj, false, "argtextobj", {}, "argtextobj.vim");
setup(&emulateSurround, false, "surround", {}, "vim-surround");
// Some polish
useFakeVim.setDisplayName(tr("Use Vim-style Editing"));
relativeNumber.setToolTip(tr("Displays line numbers relative to the line containing "
"text cursor."));
passControlKey.setToolTip(tr("Does not interpret key sequences like Ctrl-S in FakeVim "
"but handles them as regular shortcuts. This gives easier access to core functionality "
"at the price of losing some features of FakeVim."));
passKeys.setToolTip(tr("Does not interpret some key presses in insert mode so that "
"code can be properly completed and expanded."));
tabStop.setToolTip(tr("Vim tabstop option."));
#ifndef FAKEVIM_STANDALONE
backspace.setDisplayStyle(FvStringAspect::LineEditDisplay);
isKeyword.setDisplayStyle(FvStringAspect::LineEditDisplay);
const QString vimrcDefault = QLatin1String(
#ifdef Q_OS_UNIX
"$HOME/.vimrc"
#else
"%USERPROFILE%\\_vimrc"
#endif
)
vimRcPath.setExpectedKind(PathChooser::File);
vimRcPath.setToolTip(tr("Keep empty to use the default path, i.e. "
"%USERPROFILE%\\_vimrc on Windows, ~/.vimrc otherwise."));
vimRcPath.setPlaceHolderText(tr("Default: %1").arg(vimrcDefault));
vimRcPath.setDisplayStyle(FvStringAspect::PathChooserDisplay);
#endif
}
FakeVimSettings::~FakeVimSettings() = default;
FvBaseAspect *FakeVimSettings::item(const QString &name)
{
return m_nameToAspect.value(name, nullptr);
}
QString FakeVimSettings::trySetValue(const QString &name, const QString &value)
{
FvBaseAspect *aspect = m_nameToAspect.value(name, nullptr);
if (!aspect)
return tr("Unknown option: %1").arg(name);
if (aspect == &tabStop || aspect == &shiftWidth) {
if (value.toInt() <= 0)
return tr("Argument must be positive: %1=%2")
.arg(name).arg(value);
}
aspect->setValue(value);
return QString();
}
void FakeVimSettings::setup(FvBaseAspect *aspect,
const QVariant &value,
const QString &settingsKey,
const QString &shortName,
const QString &labelText)
{
aspect->setSettingsKey("FakeVim", settingsKey);
aspect->setDefaultValue(value);
#ifndef FAKEVIM_STANDALONE
aspect->setLabelText(labelText);
aspect->setAutoApply(false);
registerAspect(aspect);
if (auto boolAspect = dynamic_cast<FvBoolAspect *>(aspect))
boolAspect->setLabelPlacement(FvBoolAspect::LabelPlacement::AtCheckBoxWithoutDummyLabel);
#else
Q_UNUSED(labelText)
#endif
const QString longName = settingsKey.toLower();
if (!longName.isEmpty()) {
m_nameToAspect[longName] = aspect;
m_aspectToName[aspect] = longName;
}
if (!shortName.isEmpty())
m_nameToAspect[shortName] = aspect;
}
FakeVimSettings *fakeVimSettings()
{
static FakeVimSettings s;
return &s;
}
} // namespace Internal
} // namespace FakeVim
| 7,241
|
C++
|
.cpp
| 163
| 39.319018
| 103
| 0.655931
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,106
|
itemfakevimtests.cpp
|
hluk_CopyQ/plugins/itemfakevim/tests/itemfakevimtests.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemfakevimtests.h"
#include "tests/test_utils.h"
#include <QDir>
#ifdef Q_OS_DARWIN
#define FAKEVIM_CTRL "META"
#else
#define FAKEVIM_CTRL "CTRL"
#endif
ItemFakeVimTests::ItemFakeVimTests(const TestInterfacePtr &test, QObject *parent)
: QObject(parent)
, m_test(test)
{
}
QString ItemFakeVimTests::fileNameToSource()
{
return QDir::tempPath() + "/itemfakevim.rc";
}
void ItemFakeVimTests::initTestCase()
{
TEST(m_test->initTestCase());
}
void ItemFakeVimTests::cleanupTestCase()
{
TEST(m_test->cleanupTestCase());
}
void ItemFakeVimTests::init()
{
TEST(m_test->init());
// Don't use default external editor.
RUN("config" << "editor" << "", "\n");
}
void ItemFakeVimTests::cleanup()
{
TEST( m_test->cleanup() );
}
void ItemFakeVimTests::createItem()
{
const QString tab1 = testTab(1);
const Args args = Args() << "tab" << tab1;
RUN(args << "size", "0\n");
RUN(args << "edit", "");
RUN(args << "keys" << ":iABC" << "ENTER" << ":DEF"
<< "ESC" << "::wq" << "ENTER", "");
RUN(args << "read" << "0", "ABC\nDEF");
RUN(args << "keys" << "F2" << ":GccXYZ" << "ESC" << "::w" << "ENTER", "");
RUN(args << "read" << "0", "ABC\nXYZ");
RUN(args << "keys" << ":p:wq" << "ENTER", "");
RUN(args << "read" << "0", "ABC\nXYZ\nDEF");
}
void ItemFakeVimTests::blockSelection()
{
const QString tab1 = testTab(1);
const Args args = Args() << "tab" << tab1;
RUN(args << "edit", "");
RUN(args << "keys"
<< ":iABC" << "ENTER" << ":DEF" << "ENTER" << ":GHI" << "ESC" << "::wq" << "ENTER", "");
RUN(args << "read" << "0", "ABC\nDEF\nGHI");
RUN(args << "edit" << "0", "");
RUN(args << "keys"
<< ":ggl" << FAKEVIM_CTRL "+V" << ":jjs_" << "ESC" << "::wq" << "ENTER", "");
RUN(args << "read" << "0", "A_C\nD_F\nG_I");
}
void ItemFakeVimTests::search()
{
const QString tab1 = testTab(1);
const Args args = Args() << "tab" << tab1;
RUN(args << "edit", "");
RUN(args << "keys"
<< ":iABC" << "ENTER" << ":DEF" << "ENTER" << ":GHI" << "ESC" << "::wq" << "ENTER", "");
RUN(args << "read" << "0", "ABC\nDEF\nGHI");
RUN(args << "edit" << "0", "");
RUN(args << "keys"
<< ":gg/[EH]" << "ENTER" << ":r_nr_" << "F2", "");
RUN(args << "read" << "0", "ABC\nD_F\nG_I");
}
void ItemFakeVimTests::incDecNumbers()
{
const QString tab1 = testTab(1);
const Args args = Args() << "tab" << tab1;
RUN(args << "add" << " 0", "");
RUN(args << "edit" << "0", "");
RUN(args << "keys" << FAKEVIM_CTRL "+a" << "F2", "");
RUN(args << "read" << "0", " 1");
RUN(args << "add" << " -1", "");
RUN(args << "edit" << "0", "");
RUN(args << "keys" << FAKEVIM_CTRL "+a" << "F2", "");
RUN(args << "read" << "0", " 0");
RUN(args << "add" << " 0xff", "");
RUN(args << "edit" << "0", "");
RUN(args << "keys" << FAKEVIM_CTRL "+a" << "F2", "");
RUN(args << "read" << "0", " 0x100");
RUN(args << "add" << "9 9 9", "");
RUN(args << "edit" << "0", "");
RUN(args << "keys" << "l" << FAKEVIM_CTRL "+a" << "l" << FAKEVIM_CTRL "+a" << "F2", "");
RUN(args << "read" << "0", "9 10 10");
RUN(args << "add" << "-1 -1 -1", "");
RUN(args << "edit" << "0", "");
RUN(args << "keys" << ":ll" << "2" << FAKEVIM_CTRL "+a" << "l" << "3" << FAKEVIM_CTRL "+a" << "F2", "");
RUN(args << "read" << "0", "-1 1 2");
RUN(args << "add" << "1 1 1", "");
RUN(args << "edit" << "0", "");
RUN(args << "keys" << "l" << "2" << FAKEVIM_CTRL "+x" << "l" << "3" << FAKEVIM_CTRL "+x" << "F2", "");
RUN(args << "read" << "0", "1 -1 -2");
}
| 3,694
|
C++
|
.cpp
| 105
| 31.2
| 108
| 0.490449
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,107
|
itemsync.cpp
|
hluk_CopyQ/plugins/itemsync/itemsync.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemsync.h"
#include "ui_itemsyncsettings.h"
#include "filewatcher.h"
#include "common/appconfig.h"
#include "common/compatibility.h"
#include "common/contenttype.h"
#include "common/log.h"
#include "common/mimetypes.h"
#include "common/regexp.h"
#include "gui/iconselectbutton.h"
#include "gui/icons.h"
#include "gui/iconfont.h"
#include "gui/iconwidget.h"
#include "item/itemfilter.h"
#ifdef HAS_TESTS
# include "tests/itemsynctests.h"
#endif
#include <QBoxLayout>
#include <QDir>
#include <QFile>
#include <QFileDialog>
#include <QLabel>
#include <QMessageBox>
#include <QMouseEvent>
#include <QPushButton>
#include <QSettings>
#include <QTextEdit>
#include <QTimer>
#include <QtPlugin>
#include <QUrl>
#include <QVariantMap>
#include <memory>
namespace {
namespace syncTabsTableColumns {
enum {
tabName,
path,
browse
};
}
namespace formatSettingsTableColumns {
enum {
formats,
itemMime,
icon
};
}
const int currentVersion = 1;
const QLatin1String dataFileHeader("CopyQ_itemsync_tab");
const QLatin1String configVersion("copyq_itemsync_version");
const QLatin1String configSyncTabs("sync_tabs");
const QLatin1String configFormatSettings("format_settings");
const QLatin1String tabConfigSavedFiles("saved_files");
bool readConfigHeader(QDataStream *stream)
{
QString header;
*stream >> header;
return header == dataFileHeader;
}
bool readConfig(QIODevice *file, QVariantMap *config)
{
QDataStream stream(file);
stream.setVersion(QDataStream::Qt_4_7);
if ( !readConfigHeader(&stream) )
return false;
stream >> *config;
return stream.status() == QDataStream::Ok
&& config->value(configVersion, 0).toInt() == currentVersion;
}
void writeConfiguration(QIODevice *file, const QStringList &savedFiles)
{
QVariantMap config;
config.insert(configVersion, currentVersion);
config.insert(tabConfigSavedFiles, savedFiles);
QDataStream stream(file);
stream.setVersion(QDataStream::Qt_4_7);
stream << QString(dataFileHeader);
stream << config;
}
QString iconFromId(int id)
{
return id != -1 ? QString(QChar(id)) : QString();
}
QPushButton *createBrowseButton()
{
std::unique_ptr<QPushButton> button(new QPushButton);
button->setFont( iconFont() );
button->setText( iconFromId(IconFolderOpen) );
button->setToolTip( ItemSyncLoader::tr("Browse...",
"Button text for opening file dialog to select synchronization directory") );
return button.release();
}
bool hasVideoExtension(const QString &ext)
{
return ext == "avi"
|| ext == "mkv"
|| ext == "mp4"
|| ext == "mpg"
|| ext == "mpeg"
|| ext == "ogv"
|| ext == "flv";
}
bool hasAudioExtension(const QString &ext)
{
return ext == "mp3"
|| ext == "wav"
|| ext == "ogg"
|| ext == "m4a";
}
bool hasImageExtension(const QString &ext)
{
return ext == "png"
|| ext == "jpg"
|| ext == "gif"
|| ext == "bmp"
|| ext == "svg"
|| ext == "tga"
|| ext == "tiff"
|| ext == "psd"
|| ext == "xcf"
|| ext == "ico"
|| ext == "pbm"
|| ext == "ppm"
|| ext == "eps"
|| ext == "pcx"
|| ext == "jpx"
|| ext == "jp2";
}
bool hasArchiveExtension(const QString &ext)
{
static const auto re = anchoredRegExp("r\\d\\d");
return ext == "zip"
|| ext == "7z"
|| ext == "tar"
|| ext == "rar"
|| ext.contains(re)
|| ext == "arj";
}
bool hasTextExtension(const QString &ext)
{
return ext == "txt"
|| ext == "log"
|| ext == "xml"
|| ext == "html"
|| ext == "htm"
|| ext == "pdf"
|| ext == "doc"
|| ext == "docx"
|| ext == "odt"
|| ext == "xls"
|| ext == "rtf"
|| ext == "csv"
|| ext == "ppt";
}
int iconFromBaseNameExtensionHelper(const QString &baseName)
{
const int i = baseName.lastIndexOf('.');
if (i != -1) {
const QString ext = baseName.mid(i + 1);
if ( hasVideoExtension(ext) )
return IconFileVideo;
if ( hasAudioExtension(ext) )
return IconFileAudio;
if ( hasImageExtension(ext) )
return IconFileImage;
if ( hasArchiveExtension(ext) )
return IconFileZipper;
if ( hasTextExtension(ext) )
return IconFileLines;
}
return -1;
}
int iconFromMimeHelper(const QString &format)
{
if ( format.startsWith("video/") )
return IconCirclePlay;
if ( format.startsWith("audio/") )
return IconVolumeHigh;
if ( format.startsWith("image/") )
return IconCamera;
if ( format.startsWith("text/") )
return IconFileLines;
return -1;
}
QString iconFromUserExtension(const QStringList &fileNames, const QList<FileFormat> &formatSettings)
{
for ( const auto &format : formatSettings ) {
if ( format.icon.isEmpty() )
continue;
for (const auto &ext : format.extensions) {
for (const auto &fileName : fileNames) {
if ( fileName.endsWith(ext) )
return format.icon;
}
}
}
return QString();
}
QString iconFromMime(const QString &format)
{
return iconFromId(iconFromMimeHelper(format));
}
QString iconForItem(const QVariantMap &dataMap, const QString &baseName, const QList<FileFormat> &formatSettings)
{
const QVariantMap mimeToExtension = dataMap.value(mimeExtensionMap).toMap();
QStringList fileNames;
for (auto it = mimeToExtension.constBegin(); it != mimeToExtension.constEnd(); ++it) {
// Don't change icon for notes.
if (it.key() != mimeItemNotes)
fileNames.append( baseName + it.value().toString() );
}
// Try to get user icon from file extension.
const QString icon = iconFromUserExtension(fileNames, formatSettings);
if ( !icon.isEmpty() )
return icon;
// Try to get default icon from MIME type.
for (auto it = dataMap.constBegin(); it != dataMap.constEnd(); ++it) {
const auto &format = it.key();
const auto mimeIcon = iconFromMime(format);
if ( !mimeIcon.isEmpty() )
return mimeIcon;
}
// Try to get default icon from file extension.
for (const auto &fileName : fileNames) {
const int id = iconFromBaseNameExtensionHelper(fileName);
if (id != -1)
return iconFromId(id);
}
// Return icon for unknown files.
return iconFromId(IconFile);
}
/**
* Return true only if the item was created by CopyQ
* (i.e. has no file assigned or the file name matches internal format).
*/
bool isOwnFile(const QString &baseName)
{
return baseName.isEmpty() || FileWatcher::isOwnBaseName(baseName);
}
bool isOwnItem(const QModelIndex &index)
{
const QString baseName = FileWatcher::getBaseName(index);
return baseName.isEmpty() || FileWatcher::isOwnBaseName(baseName);
}
bool containsItemsWithNotOwnedFiles(const QList<QModelIndex> &indexList)
{
return !std::all_of( std::begin(indexList), std::end(indexList), isOwnItem );
}
void fixUserExtensions(QStringList *exts)
{
for (int i = 0; i < exts->size(); ++i) {
QString &ext = (*exts)[i];
if ( !ext.startsWith('.') )
ext.prepend('.');
// Use "_user.dat" instead of "*.dat" to avoid collisions with extension "_copy.dat"
// internally used to store data of unknown MIME type.
if ( ext.endsWith(".dat", Qt::CaseInsensitive) )
ext.insert(ext.size() - 4, "_user");
// Remove invalid extensions containing path separator.
if ( ext.contains('/') )
exts->removeAt(i--);
}
}
void fixUserMimeType(QString *mimeType)
{
// Don't allow user to override internal formats.
if ( mimeType->startsWith(COPYQ_MIME_PREFIX_ITEMSYNC) )
mimeType->clear();
}
void setNormalStretchFixedColumns(QTableWidget *table, int normalColumn, int stretchColumn, int fixedColumn)
{
QHeaderView *header = table->horizontalHeader();
header->setSectionResizeMode(stretchColumn, QHeaderView::Stretch);
header->setSectionResizeMode(fixedColumn, QHeaderView::Fixed);
header->resizeSection(fixedColumn, table->rowHeight(0));
table->resizeColumnToContents(normalColumn);
}
bool hasOnlyInternalData(const QVariantMap &data)
{
for (auto it = data.constBegin(); it != data.constEnd(); ++it) {
const auto &format = it.key();
if ( !format.startsWith(COPYQ_MIME_PREFIX) )
return false;
}
return true;
}
} // namespace
ItemSync::ItemSync(const QString &label, const QString &icon, ItemWidget *childItem)
: QWidget( childItem->widget()->parentWidget() )
, ItemWidgetWrapper(childItem, this)
, m_label( new QTextEdit(this) )
, m_icon( new IconWidget(icon, this) )
{
auto layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
layout->setSizeConstraint(QLayout::SetMinimumSize);
auto labelLayout = new QHBoxLayout;
connect( layout, &QVBoxLayout::destroyed,
labelLayout, &QHBoxLayout::deleteLater );
labelLayout->setContentsMargins(0, 0, 0, 0);
labelLayout->setSpacing(0);
labelLayout->addWidget(m_icon);
labelLayout->addWidget(m_label);
labelLayout->addStretch();
layout->addLayout(labelLayout);
QWidget *w = childItem->widget();
layout->addWidget(w);
w->setObjectName("item_child");
w->setParent(this);
m_label->setObjectName("item_child");
m_label->document()->setDefaultFont(font());
QTextOption option = m_label->document()->defaultTextOption();
option.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
m_label->document()->setDefaultTextOption(option);
m_label->setReadOnly(true);
m_label->setUndoRedoEnabled(false);
m_label->setFocusPolicy(Qt::NoFocus);
m_label->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_label->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_label->setFrameStyle(QFrame::NoFrame);
m_label->setContextMenuPolicy(Qt::NoContextMenu);
m_label->viewport()->installEventFilter(this);
m_label->setPlainText(label);
}
void ItemSync::updateSize(QSize maximumSize, int idealWidth)
{
setMaximumSize(maximumSize);
const int w = idealWidth - m_icon->width() - 8;
QTextDocument *doc = m_label->document();
doc->setTextWidth(w);
m_label->setFixedSize( w, static_cast<int>(doc->size().height()) );
ItemWidgetWrapper::updateSize(maximumSize, idealWidth);
adjustSize();
setFixedSize(sizeHint());
}
bool ItemSync::eventFilter(QObject *, QEvent *event)
{
return ItemWidget::filterMouseEvents(m_label, event);
}
ItemSyncSaver::ItemSyncSaver(const QString &tabPath, FileWatcher *watcher)
: m_tabPath(tabPath)
, m_watcher(watcher)
{
if (m_watcher)
m_watcher->setParent(this);
}
bool ItemSyncSaver::saveItems(const QString &tabName, const QAbstractItemModel &model, QIODevice *file)
{
// Don't save items if path is empty.
if (!m_watcher) {
writeConfiguration(file, QStringList());
return true;
}
const QString path = m_watcher->path();
QStringList savedFiles;
if ( !m_watcher->isValid() ) {
log( tr("Failed to synchronize tab \"%1\" with directory \"%2\"!")
.arg(tabName, path),
LogError );
return false;
}
QDir dir(path);
for (int row = 0; row < model.rowCount(); ++row) {
const QModelIndex index = model.index(row, 0);
const QVariantMap itemData = index.data(contentType::data).toMap();
const QVariantMap mimeToExtension = itemData.value(mimeExtensionMap).toMap();
const QString baseName = FileWatcher::getBaseName(index);
const QString filePath = dir.absoluteFilePath(baseName);
for (const auto &ext : mimeToExtension)
savedFiles.prepend( filePath + ext.toString() );
}
writeConfiguration(file, savedFiles);
return true;
}
bool ItemSyncSaver::canRemoveItems(const QList<QModelIndex> &indexList, QString *error)
{
if ( !containsItemsWithNotOwnedFiles(indexList) )
return true;
if (error) {
*error = "Removing synchronized items with assigned files from script is not allowed (remove the files instead)";
return false;
}
return QMessageBox::question(
QApplication::activeWindow(), tr("Remove Items?"),
tr("Do you really want to <strong>remove items and associated files</strong>?"),
QMessageBox::No | QMessageBox::Yes,
QMessageBox::Yes ) == QMessageBox::Yes;
}
void ItemSyncSaver::itemsRemovedByUser(const QList<QPersistentModelIndex> &indexList)
{
if ( m_tabPath.isEmpty() )
return;
// Remove unneeded files (remaining records in the hash map).
for (const auto &index : indexList)
FileWatcher::removeFilesForRemovedIndex(m_tabPath, index);
}
QVariantMap ItemSyncSaver::copyItem(const QAbstractItemModel &, const QVariantMap &itemData)
{
if (m_watcher)
m_watcher->updateItemsIfNeeded();
QVariantMap copiedItemData;
for (auto it = itemData.begin(); it != itemData.constEnd(); ++it) {
const auto &format = it.key();
if ( !format.startsWith(mimePrivateSyncPrefix) )
copiedItemData[format] = it.value();
}
copiedItemData.insert(mimeSyncPath, m_tabPath);
// Add text/uri-list if no data are present.
if ( hasOnlyInternalData(copiedItemData) ) {
QByteArray uriData;
const QVariantMap mimeToExtension = itemData.value(mimeExtensionMap).toMap();
const QString basePath = m_tabPath + '/' + itemData.value(mimeBaseName).toString();
for (const auto &extension : mimeToExtension) {
const QString filePath = basePath + extension.toString();
if ( !uriData.isEmpty() )
uriData.append("\n");
uriData.append( QUrl::fromLocalFile(filePath).toEncoded() );
}
QVariantMap noSaveData;
noSaveData.insert(mimeUriList, FileWatcher::calculateHash(uriData));
copiedItemData.insert(mimeUriList, uriData);
copiedItemData.insert(mimeNoSave, noSaveData);
}
return copiedItemData;
}
void ItemSyncSaver::setFocus(bool focus)
{
if (m_watcher)
m_watcher->setUpdatesEnabled(focus);
}
QString ItemSyncScriptable::getMimeBaseName() const
{
return mimeBaseName;
}
QString ItemSyncScriptable::selectedTabPath()
{
const auto tab = call("selectedTab", QVariantList()).toString();
return m_tabPaths.value(tab).toString();
}
ItemSyncLoader::ItemSyncLoader()
{
registerSyncDataFileConverter();
}
ItemSyncLoader::~ItemSyncLoader() = default;
void ItemSyncLoader::applySettings(QSettings &settings)
{
// Apply settings from tab sync path table.
QTableWidget *t = ui->tableWidgetSyncTabs;
QStringList tabPaths;
m_tabPaths.clear();
for (int row = 0; row < t->rowCount(); ++row) {
const QString tabName = t->item(row, syncTabsTableColumns::tabName)->text();
if ( !tabName.isEmpty() ) {
const QString tabPath = t->item(row, syncTabsTableColumns::path)->text();
tabPaths << tabName << tabPath;
m_tabPaths.insert(tabName, tabPath);
}
}
// Apply settings from file format table.
t = ui->tableWidgetFormatSettings;
QVariantList formatSettings;
m_formatSettings.clear();
for (int row = 0; row < t->rowCount(); ++row) {
FileFormat fileFormat;
fileFormat.extensions = t->item(row, formatSettingsTableColumns::formats)->text()
.split( QRegularExpression("[,;\\s]"), SKIP_EMPTY_PARTS );
fileFormat.itemMime = t->item(row, formatSettingsTableColumns::itemMime)->text();
if ( fileFormat.extensions.isEmpty() && fileFormat.itemMime.isEmpty() )
continue;
fileFormat.icon = t->cellWidget(row, formatSettingsTableColumns::icon)
->property("currentIcon").toString();
QVariantMap format;
format["formats"] = fileFormat.extensions;
format["itemMime"] = fileFormat.itemMime;
format["icon"] = fileFormat.icon;
formatSettings.append(format);
fixUserExtensions(&fileFormat.extensions);
fixUserMimeType(&fileFormat.itemMime);
m_formatSettings.append(fileFormat);
}
settings.setValue(configSyncTabs, tabPaths);
settings.setValue(configFormatSettings, formatSettings);
}
void ItemSyncLoader::loadSettings(const QSettings &settings)
{
m_tabPaths.clear();
m_tabPathsSaved.clear();
const QStringList tabPaths = settings.value(configSyncTabs).toStringList();
for (int i = 0; i < tabPaths.size(); i += 2) {
const QString &name = tabPaths[i];
const QString &path = tabPaths.value(i + 1);
m_tabPaths.insert(name, path);
m_tabPathsSaved.append(name);
m_tabPathsSaved.append(path);
}
m_formatSettings.clear();
const QVariantList formatSettings = settings.value(configFormatSettings).toList();
for (const auto &formatSetting : formatSettings) {
QVariantMap format = formatSetting.toMap();
FileFormat fileFormat;
fileFormat.extensions = format.value("formats").toStringList();
fileFormat.itemMime = format.value("itemMime").toString();
fileFormat.icon = format.value("icon").toString();
fixUserExtensions(&fileFormat.extensions);
fixUserMimeType(&fileFormat.itemMime);
m_formatSettings.append(fileFormat);
}
const QSettings settingsTopLevel(settings.fileName(), settings.format());
m_itemDataThreshold = settingsTopLevel.value(
QStringLiteral("Options/") + Config::item_data_threshold::name(),
Config::item_data_threshold::defaultValue()
).toInt();
}
QWidget *ItemSyncLoader::createSettingsWidget(QWidget *parent)
{
ui.reset(new Ui::ItemSyncSettings);
QWidget *w = new QWidget(parent);
ui->setupUi(w);
// Init tab sync path table.
QTableWidget *t = ui->tableWidgetSyncTabs;
for (int row = 0, i = 0; i < m_tabPathsSaved.size() + 20; ++row, i += 2) {
t->insertRow(row);
t->setItem( row, syncTabsTableColumns::tabName, new QTableWidgetItem(m_tabPathsSaved.value(i)) );
t->setItem( row, syncTabsTableColumns::path, new QTableWidgetItem(m_tabPathsSaved.value(i + 1)) );
QPushButton *button = createBrowseButton();
t->setCellWidget(row, syncTabsTableColumns::browse, button);
connect( button, &QAbstractButton::clicked,
this, &ItemSyncLoader::onBrowseButtonClicked );
}
setNormalStretchFixedColumns(t, syncTabsTableColumns::tabName, syncTabsTableColumns::path,
syncTabsTableColumns::browse);
// Init file format table.
t = ui->tableWidgetFormatSettings;
for (int row = 0; row < m_formatSettings.size() + 10; ++row) {
const FileFormat format = m_formatSettings.value(row);
const QString formats = format.extensions.join(", ");
t->insertRow(row);
t->setItem( row, formatSettingsTableColumns::formats, new QTableWidgetItem(formats) );
t->setItem( row, formatSettingsTableColumns::itemMime, new QTableWidgetItem(format.itemMime) );
auto button = new IconSelectButton();
button->setCurrentIcon(format.icon);
t->setCellWidget(row, formatSettingsTableColumns::icon, button);
}
setNormalStretchFixedColumns(t, formatSettingsTableColumns::formats,
formatSettingsTableColumns::itemMime,
formatSettingsTableColumns::icon);
return w;
}
bool ItemSyncLoader::canLoadItems(QIODevice *file) const
{
QDataStream stream(file);
stream.setVersion(QDataStream::Qt_4_7);
return readConfigHeader(&stream);
}
bool ItemSyncLoader::canSaveItems(const QString &tabName) const
{
return m_tabPaths.contains(tabName);
}
ItemSaverPtr ItemSyncLoader::loadItems(const QString &tabName, QAbstractItemModel *model, QIODevice *file, int maxItems)
{
QVariantMap config;
if ( !readConfig(file, &config) )
return nullptr;
const QStringList files = config.value(tabConfigSavedFiles).toStringList();
return loadItems(tabName, model, files, maxItems);
}
ItemSaverPtr ItemSyncLoader::initializeTab(const QString &tabName, QAbstractItemModel *model, int maxItems)
{
return loadItems(tabName, model, QStringList(), maxItems);
}
ItemWidget *ItemSyncLoader::transform(ItemWidget *itemWidget, const QVariantMap &data)
{
const auto baseName = FileWatcher::getBaseName(data);
if ( isOwnFile(baseName) )
return nullptr;
itemWidget->setTagged(true);
const auto icon = iconForItem(data, baseName, m_formatSettings);
return new ItemSync(baseName, icon, itemWidget);
}
bool ItemSyncLoader::matches(const QModelIndex &index, const ItemFilter &filter) const
{
const QVariantMap dataMap = index.data(contentType::data).toMap();
const QString text = dataMap.value(mimeBaseName).toString();
return filter.matches(text);
}
QObject *ItemSyncLoader::tests(const TestInterfacePtr &test) const
{
#ifdef HAS_TESTS
QStringList tabPaths;
for (int i = 0; i < 10; ++i) {
tabPaths.append(ItemSyncTests::testTab(i));
tabPaths.append(ItemSyncTests::testDir(i));
}
QVariantList formatSettings;
QVariantMap format;
format["formats"] = QStringList() << "xxx";
format["itemMime"] = QString(COPYQ_MIME_PREFIX "test-xxx");
format["icon"] = QString(iconFromId(IconTrash));
formatSettings << format;
format["formats"] = QStringList() << "zzz" << ".yyy";
format["itemMime"] = QString(COPYQ_MIME_PREFIX "test-zzz");
format["icon"] = QString();
formatSettings << format;
QVariantMap settings;
settings[configSyncTabs] = tabPaths;
settings[configFormatSettings] = formatSettings;
QObject *tests = new ItemSyncTests(test);
tests->setProperty("CopyQ_test_settings", settings);
return tests;
#else
Q_UNUSED(test)
return nullptr;
#endif
}
ItemScriptable *ItemSyncLoader::scriptableObject()
{
QVariantMap tabPaths;
for (auto it = m_tabPaths.constBegin(); it != m_tabPaths.constEnd(); ++it)
tabPaths.insert( it.key(), it.value() );
return new ItemSyncScriptable(tabPaths);
}
void ItemSyncLoader::onBrowseButtonClicked()
{
QObject *button = sender();
if (button == nullptr)
return;
QTableWidget *t = ui->tableWidgetSyncTabs;
int row = 0;
for ( ; row < t->rowCount() && t->cellWidget(row, syncTabsTableColumns::browse) != button; ++row ) {}
Q_ASSERT( row == t->rowCount() );
if ( row == t->rowCount() )
return;
QTableWidgetItem *item = t->item(row, syncTabsTableColumns::path);
const QString path =
QFileDialog::getExistingDirectory( t, tr("Open Directory for Synchronization"), item->text() );
if ( !path.isEmpty() )
item->setText(path);
}
ItemSaverPtr ItemSyncLoader::loadItems(const QString &tabName, QAbstractItemModel *model, const QStringList &files, int maxItems)
{
const auto tabPath = m_tabPaths.value(tabName);
const auto path = files.isEmpty() ? tabPath : QFileInfo(files.first()).absolutePath();
if ( path.isEmpty() )
return std::make_shared<ItemSyncSaver>(tabPath, nullptr);
QDir dir(path);
if ( !dir.mkpath(".") ) {
emit error( tr("Failed to create synchronization directory"));
return nullptr;
}
auto *watcher = new FileWatcher(
path, files, model, maxItems, m_formatSettings, m_itemDataThreshold);
return std::make_shared<ItemSyncSaver>(tabPath, watcher);
}
| 24,119
|
C++
|
.cpp
| 655
| 30.868702
| 129
| 0.667209
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,108
|
filewatcher.cpp
|
hluk_CopyQ/plugins/itemsync/filewatcher.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "filewatcher.h"
#include "common/contenttype.h"
#include "common/log.h"
#include "item/serialize.h"
#include <QAbstractItemModel>
#include <QCryptographicHash>
#include <QDataStream>
#include <QDateTime>
#include <QDir>
#include <QElapsedTimer>
#include <QMimeData>
#include <QRegularExpression>
#include <QUrl>
#include <array>
#include <vector>
constexpr int staleLockTimeMs = 10'000;
const QLatin1String mimeExtensionMap(COPYQ_MIME_PREFIX_ITEMSYNC "mime-to-extension-map");
const QLatin1String mimeBaseName(COPYQ_MIME_PREFIX_ITEMSYNC "basename");
const QLatin1String mimeNoSave(COPYQ_MIME_PREFIX_ITEMSYNC "no-save");
const QLatin1String mimeSyncPath(COPYQ_MIME_PREFIX_ITEMSYNC "sync-path");
const QLatin1String mimeNoFormat(COPYQ_MIME_PREFIX_ITEMSYNC "no-format");
const QLatin1String mimeUnknownFormats(COPYQ_MIME_PREFIX_ITEMSYNC "unknown-formats");
const QLatin1String mimePrivateSyncPrefix(COPYQ_MIME_PREFIX_ITEMSYNC_PRIVATE);
const QLatin1String mimeOldBaseName(COPYQ_MIME_PREFIX_ITEMSYNC_PRIVATE "old-basename");
const QLatin1String mimeHashPrefix(COPYQ_MIME_PREFIX_ITEMSYNC_PRIVATE "hash");
class SyncDataFile {
public:
SyncDataFile() = default;
explicit SyncDataFile(const QString &path, const QString &format = QString())
: m_path(path)
, m_format(format)
{}
const QString &path() const { return m_path; }
void setPath(const QString &path) { m_path = path; }
const QString &format() const { return m_format; }
void setFormat(const QString &format) { m_format = format; }
qint64 size() const {
QFileInfo f(m_path);
return f.size();
}
QString toString() const {
if ( m_format.isEmpty() )
return m_path;
return QStringLiteral("%1\n%2").arg(m_path, m_format);
}
QByteArray readAll() const
{
COPYQ_LOG_VERBOSE( QStringLiteral("ItemSync: Reading file: %1").arg(m_path) );
QFile f(m_path);
if ( !f.open(QIODevice::ReadOnly) )
return QByteArray();
if ( m_format.isEmpty() )
return f.readAll();
QDataStream stream(&f);
QVariantMap dataMap;
if ( !deserializeData(&stream, &dataMap) ) {
log( QStringLiteral("ItemSync: Failed to read file \"%1\": %2")
.arg(m_path, f.errorString()), LogError );
return QByteArray();
}
return dataMap.value(m_format).toByteArray();
}
bool operator==(const SyncDataFile &other) const {
return m_path == other.m_path
&& m_format == other.m_format;
}
private:
QString m_path;
QString m_format;
};
Q_DECLARE_METATYPE(SyncDataFile)
QDataStream &operator<<(QDataStream &out, SyncDataFile value)
{
return out << value.path() << value.format();
}
QDataStream &operator>>(QDataStream &in, SyncDataFile &value)
{
QString path;
QString format;
in >> path >> format;
value.setPath(path);
value.setFormat(format);
return in;
}
void registerSyncDataFileConverter()
{
QMetaType::registerConverter(&SyncDataFile::readAll);
QMetaType::registerConverter(&SyncDataFile::toString);
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
qRegisterMetaTypeStreamOperators<SyncDataFile>("SyncDataFile");
#else
qRegisterMetaType<SyncDataFile>("SyncDataFile");
#endif
}
struct Ext {
Ext() : extension(), format() {}
Ext(const QString &extension, const QString &format)
: extension(extension)
, format(format)
{}
QString extension;
QString format;
};
using Exts = std::vector<Ext>;
struct BaseNameExtensions {
explicit BaseNameExtensions(const QString &baseName = QString(),
const Exts &exts = Exts())
: baseName(baseName)
, exts(exts)
{}
QString baseName;
Exts exts;
};
namespace {
const QLatin1String dataFileSuffix("_copyq.dat");
const QLatin1String noteFileSuffix("_note.txt");
const int defaultUpdateFocusItemsIntervalMs = 10000;
const int batchItemUpdateIntervalMs = 100;
const qint64 sizeLimit = 50'000'000;
FileFormat getFormatSettingsFromFileName(const QString &fileName,
const QList<FileFormat> &formatSettings,
QString *foundExt = nullptr)
{
for (const auto &format : formatSettings) {
for ( const auto &ext : format.extensions ) {
if ( fileName.endsWith(ext) ) {
if (foundExt)
*foundExt = ext;
return format;
}
}
}
return FileFormat();
}
void getBaseNameAndExtension(const QString &fileName, QString *baseName, QString *ext,
const QList<FileFormat> &formatSettings)
{
ext->clear();
const FileFormat fileFormat = getFormatSettingsFromFileName(fileName, formatSettings, ext);
if ( !fileFormat.isValid() ) {
const int i = fileName.lastIndexOf('.');
if (i != -1)
*ext = fileName.mid(i);
}
*baseName = fileName.left( fileName.size() - ext->size() );
if ( baseName->endsWith('.') ) {
baseName->chop(1);
ext->prepend('.');
}
}
const std::array<Ext, 12> &fileExtensionsAndFormats()
{
static const std::array<Ext, 12> exts = {
Ext(noteFileSuffix, mimeItemNotes),
Ext(".txt", mimeText),
Ext(".html", mimeHtml),
Ext(".uri", mimeUriList),
Ext(".png", "image/png"),
Ext("_inkscape.svg", "image/x-inkscape-svg-compressed"),
Ext(".svg", "image/svg+xml"),
Ext(".bmp", "image/bmp"),
Ext(".gif", "image/gif"),
Ext(".jpg", "image/jpeg"),
Ext(".xml", "application/xml"),
Ext(".xml", "text/xml"),
};
return exts;
}
QString findByFormat(const QString &format, const QList<FileFormat> &formatSettings)
{
// Find in default extensions.
for (const auto &ext : fileExtensionsAndFormats()) {
if (ext.format == format)
return ext.extension;
}
// Find in user defined extensions.
for (const auto &fileFormat : formatSettings) {
if ( !fileFormat.extensions.isEmpty() && fileFormat.itemMime != "-"
&& format == fileFormat.itemMime )
{
return fileFormat.extensions.first();
}
}
return QString();
}
Ext findByExtension(const QString &fileName, const QList<FileFormat> &formatSettings)
{
// Is internal data format?
if ( fileName.endsWith(dataFileSuffix) )
return Ext(dataFileSuffix, mimeUnknownFormats);
// Avoid conflicting notes with text.
if ( fileName.endsWith(noteFileSuffix) )
return Ext(noteFileSuffix, mimeItemNotes);
// Find in user defined formats.
bool hasUserFormat = false;
for (const auto &format : formatSettings) {
for (const auto &ext : format.extensions) {
if ( fileName.endsWith(ext) ) {
if ( format.itemMime.isEmpty() )
hasUserFormat = true;
else
return Ext(ext, format.itemMime);
}
}
}
// Find in default formats.
for (const auto &ext : fileExtensionsAndFormats()) {
if ( fileName.endsWith(ext.extension) )
return ext;
}
return hasUserFormat ? Ext(QString(), mimeNoFormat) : Ext();
}
bool saveItemFile(const QString &filePath, const QByteArray &bytes,
QStringList *existingFiles, bool hashChanged = true)
{
if ( !existingFiles->removeOne(filePath) || hashChanged ) {
QFile f(filePath);
if ( !f.open(QIODevice::WriteOnly) || f.write(bytes) == -1 ) {
log( QStringLiteral("ItemSync: %1").arg(f.errorString()), LogError );
return false;
}
}
return true;
}
bool canUseFile(const QFileInfo &info)
{
return !info.fileName().startsWith(QLatin1Char('.'));
}
bool getBaseNameExtension(const QString &filePath, const QList<FileFormat> &formatSettings,
QString *baseName, Ext *ext)
{
QFileInfo info(filePath);
if ( !canUseFile(info) )
return false;
*ext = findByExtension(filePath, formatSettings);
if ( ext->format.isEmpty() || ext->format == QLatin1String("-") )
return false;
const QString fileName = info.fileName();
*baseName = fileName.left( fileName.size() - ext->extension.size() );
return true;
}
BaseNameExtensionsList listFiles(const QStringList &files,
const QList<FileFormat> &formatSettings,
const int maxItemCount)
{
BaseNameExtensionsList fileList;
QMap<QString, int> fileMap;
for (const auto &filePath : files) {
QString baseName;
Ext ext;
if ( getBaseNameExtension(filePath, formatSettings, &baseName, &ext) ) {
int i = fileMap.value(baseName, -1);
if (i == -1) {
i = fileList.size();
fileList.append( BaseNameExtensions(baseName, {ext}) );
fileMap.insert(baseName, i);
if (fileList.size() >= maxItemCount)
break;
} else {
fileList[i].exts.push_back(ext);
}
}
}
return fileList;
}
bool isBaseNameLessThan(const QString &lhsBaseName, const QString &rhsBaseName)
{
const bool isLhsOwn = FileWatcher::isOwnBaseName(lhsBaseName);
const bool isRhsOwn = FileWatcher::isOwnBaseName(rhsBaseName);
if (isLhsOwn && isRhsOwn)
return lhsBaseName > rhsBaseName;
if (isLhsOwn)
return true;
if (isRhsOwn)
return false;
return lhsBaseName < rhsBaseName;
}
/// Sorts own files (copyq_*) first by creation date newer first and other
/// files by name alphabetically.
QFileInfoList sortedFilesInfos(const QDir &dir, const QDir::Filters &itemFileFilter)
{
QFileInfoList infoList = dir.entryInfoList(itemFileFilter);
std::sort(std::begin(infoList), std::end(infoList), [](const QFileInfo &lhs, const QFileInfo &rhs){
const QString lhsBaseName = lhs.baseName();
const QString rhsBaseName = rhs.baseName();
return isBaseNameLessThan(lhsBaseName, rhsBaseName);
});
return infoList;
}
QStringList listFiles(const QDir &dir)
{
QStringList files;
const QDir::Filters itemFileFilter = QDir::Files | QDir::Readable | QDir::Writable;
// Get files ordered by name to achieve same result on multiple platforms.
// NOTE: Sorting by modification time can be slow.
for ( const auto &info : sortedFilesInfos(dir, itemFileFilter) ) {
if ( canUseFile(info) )
files.append(info.absoluteFilePath());
}
return files;
}
/// Return true only if no file name in @a fileNames starts with @a baseName.
bool isUniqueBaseName(const QString &baseName, const QStringList &fileNames,
const QSet<QString> &baseNames = {})
{
if ( baseNames.contains(baseName) )
return false;
for (const auto &fileName : fileNames) {
if ( fileName.startsWith(baseName) )
return false;
}
return true;
}
void moveFormatFiles(const QString &oldPath, const QString &newPath,
const QVariantMap &mimeToExtension)
{
for (const auto &extValue : mimeToExtension) {
const QString ext = extValue.toString();
QFile::rename(oldPath + ext, newPath + ext);
}
}
void copyFormatFiles(const QString &oldPath, const QString &newPath,
const QVariantMap &mimeToExtension)
{
for (const auto &extValue : mimeToExtension) {
const QString ext = extValue.toString();
QFile::copy(oldPath + ext, newPath + ext);
}
}
void removeFormatFiles(const QString &path, const QVariantMap &mimeToExtension)
{
for (const auto &extValue : mimeToExtension)
QFile::remove(path + extValue.toString());
}
bool renameToUnique(
const QDir &dir, const QSet<QString> &baseNames, QString *name,
const QList<FileFormat> &formatSettings)
{
if ( name->isEmpty() ) {
const auto dateFormat = QStringLiteral("yyyyMMddhhmmsszzz");
const auto dateTime = QDateTime::currentDateTimeUtc();
const auto now = dateTime.toString(dateFormat);
*name = QStringLiteral("copyq_%1").arg(now);
} else {
// Replace/remove unsafe characters.
name->replace( QRegularExpression(QLatin1String(R"(/|\\|^\.)")),
QLatin1String("_") );
name->remove( QRegularExpression(QLatin1String(R"(\n|\r)")) );
}
const QStringList fileNames = dir.entryList();
if ( isUniqueBaseName(*name, fileNames, baseNames) )
return true;
QString ext;
QString baseName;
getBaseNameAndExtension(*name, &baseName, &ext, formatSettings);
int i = 0;
int fieldWidth = 4;
QRegularExpression re(QStringLiteral(R"(\d{1,4}$)"));
const auto m = re.match(baseName);
if (m.hasMatch()) {
const QString num = m.captured();
i = num.toInt();
fieldWidth = num.size();
baseName = baseName.mid( 0, baseName.size() - fieldWidth );
} else {
baseName.append('-');
}
for (int counter = 0; counter < 99999; ++counter) {
*name = baseName + QStringLiteral("%1").arg(++i, fieldWidth, 10, QLatin1Char('0')) + ext;
if ( isUniqueBaseName(*name, fileNames, baseNames) )
return true;
}
log( QStringLiteral(
"ItemSync: Failed to find unique base name with prefix: %1")
.arg(baseName), LogError);
return false;
}
QString findLastOwnBaseName(QAbstractItemModel *model, int fromRow) {
for (int row = fromRow; row < model->rowCount(); ++row) {
const QModelIndex index = model->index(row, 0);
const QString baseName = FileWatcher::getBaseName(index);
if ( FileWatcher::isOwnBaseName(baseName) )
return baseName;
}
return {};
}
} // namespace
QString FileWatcher::getBaseName(const QModelIndex &index)
{
return getBaseName( index.data(contentType::data).toMap() );
}
QString FileWatcher::getBaseName(const QVariantMap &data)
{
return data.value(mimeBaseName).toString();
}
bool FileWatcher::isOwnBaseName(const QString &baseName)
{
return baseName.startsWith(QLatin1String("copyq_"));
}
void FileWatcher::removeFilesForRemovedIndex(const QString &tabPath, const QModelIndex &index)
{
const QAbstractItemModel *model = index.model();
if (!model)
return;
const QString baseName = FileWatcher::getBaseName(index);
if ( baseName.isEmpty() )
return;
// Check if item is still present in list (drag'n'drop).
bool remove = true;
for (int i = 0; i < model->rowCount(); ++i) {
const QModelIndex index2 = model->index(i, 0);
if ( index2 != index && baseName == FileWatcher::getBaseName(index2) ) {
remove = false;
break;
}
}
if (!remove)
return;
const QVariantMap itemData = index.data(contentType::data).toMap();
const QVariantMap mimeToExtension = itemData.value(mimeExtensionMap).toMap();
if ( mimeToExtension.isEmpty() )
QFile::remove(tabPath + '/' + baseName);
else
removeFormatFiles(tabPath + '/' + baseName, mimeToExtension);
}
Hash FileWatcher::calculateHash(const QByteArray &bytes)
{
return QCryptographicHash::hash(bytes, QCryptographicHash::Sha1);
}
FileWatcher::FileWatcher(
const QString &path,
const QStringList &paths,
QAbstractItemModel *model,
int maxItems,
const QList<FileFormat> &formatSettings,
int itemDataThreshold,
QObject *parent)
: QObject(parent)
, m_model(model)
, m_formatSettings(formatSettings)
, m_path(path)
, m_valid(true)
, m_maxItems(maxItems)
, m_itemDataThreshold(itemDataThreshold)
, m_lock(m_path + QLatin1String("/.copyq_lock"))
{
m_updateTimer.setSingleShot(true);
m_moveTimer.setSingleShot(true);
m_lock.setStaleLockTime(staleLockTimeMs);
bool ok;
const int interval = qEnvironmentVariableIntValue("COPYQ_SYNC_UPDATE_INTERVAL_MS", &ok);
m_interval = ok && interval > 0 ? interval : defaultUpdateFocusItemsIntervalMs;
connect( &m_updateTimer, &QTimer::timeout,
this, &FileWatcher::updateItems );
connect( &m_moveTimer, &QTimer::timeout,
this, &FileWatcher::updateMovedRows );
connect( m_model, &QAbstractItemModel::rowsInserted,
this, &FileWatcher::onRowsInserted );
connect( m_model, &QAbstractItemModel::rowsAboutToBeRemoved,
this, &FileWatcher::onRowsRemoved );
connect( model, &QAbstractItemModel::rowsMoved,
this, &FileWatcher::onRowsMoved );
connect( m_model, &QAbstractItemModel::dataChanged,
this, &FileWatcher::onDataChanged );
if (model->rowCount() > 0)
saveItems(0, model->rowCount() - 1, UpdateType::Inserted);
prependItemsFromFiles( QDir(path), listFiles(paths, m_formatSettings, m_maxItems) );
}
bool FileWatcher::lock()
{
if ( !m_valid )
return false;
// Create path if doesn't exist.
QDir dir(m_path);
if ( !dir.mkpath(QStringLiteral(".")) ) {
log( tr("Failed to create synchronization directory \"%1\"!").arg(m_path), LogError );
return false;
}
if ( !m_lock.lock() ) {
log( QStringLiteral("Failed to create lock file in \"%1\"!").arg(m_path), LogError );
return false;
}
m_valid = false;
return true;
}
void FileWatcher::unlock()
{
m_lock.unlock();
m_valid = true;
}
QVariantMap FileWatcher::itemDataFromFiles(const QDir &dir, const BaseNameExtensions &baseNameWithExts)
{
QVariantMap dataMap;
QVariantMap mimeToExtension;
updateDataAndWatchFile(dir, baseNameWithExts, &dataMap, &mimeToExtension);
if ( !mimeToExtension.isEmpty() ) {
const QString baseName = QFileInfo(baseNameWithExts.baseName).fileName();
dataMap.insert(mimeBaseName, baseName);
dataMap.insert(mimeOldBaseName, baseName);
dataMap.insert(mimeExtensionMap, mimeToExtension);
}
return dataMap;
}
void FileWatcher::prependItemsFromFiles(const QDir &dir, const BaseNameExtensionsList &fileList)
{
QVector<QVariantMap> items;
items.reserve(fileList.size());
for (auto it = fileList.rbegin(); it != fileList.rend(); ++it) {
const QVariantMap item = itemDataFromFiles(dir, *it);
if ( !item.isEmpty() )
items.append(item);
}
createItems(items, 0);
}
void FileWatcher::insertItemsFromFiles(const QDir &dir, const BaseNameExtensionsList &fileList)
{
if ( fileList.isEmpty() )
return;
QVector<QVariantMap> items;
items.reserve(fileList.size());
for (const auto &baseNameWithExts : fileList) {
const QVariantMap item = itemDataFromFiles(dir, baseNameWithExts);
// Skip if the associated file was just removed.
if ( !item.isEmpty() )
items.append(item);
}
int row = 0;
int i = 0;
for (; i < items.size(); ++i) {
const QVariantMap &item = items[i];
const QString &newBaseName = getBaseName(item);
for ( ; row < m_model->rowCount(); ++row ) {
const QString rowBaseName = getBaseName( m_model->index(row, 0) );
if ( isBaseNameLessThan(newBaseName, rowBaseName) )
break;
}
if ( row >= m_model->rowCount() )
break;
createItems({item}, row);
++row;
}
// Append rest of the items.
if ( i < items.size() ) {
const int space = m_maxItems - m_model->rowCount();
if (space <= 0)
return;
items.erase(items.begin(), items.begin() + i);
if ( space < items.size() )
items.erase(items.begin(), items.begin() + space);
createItems( items, m_model->rowCount() );
}
// TODO: Remove excessive items, but not pinned.
// This must be done elsewhere using QTimer 0.
}
void FileWatcher::updateItems()
{
if ( !lock() ) {
m_updateTimer.start(m_interval);
return;
}
QElapsedTimer t;
t.start();
m_lastUpdateTimeMs = QDateTime::currentMSecsSinceEpoch();
const QDir dir(m_path);
if ( m_batchIndexData.isEmpty() ) {
const QStringList files = listFiles(dir);
m_fileList = listFiles(files, m_formatSettings, m_maxItems);
m_batchIndexData.reserve(m_model->rowCount());
for (int row = 0; row < m_model->rowCount(); ++row) {
const QModelIndex index = m_model->index(row, 0);
if ( !oldBaseName(index).isEmpty() )
m_batchIndexData.append(index);
else
COPYQ_LOG_VERBOSE("Would create item");
}
m_lastBatchIndex = -1;
if ( t.elapsed() > 100 )
log( QStringLiteral("ItemSync: Files listed in %1 ms").arg(t.elapsed()) );
}
for ( int i = m_lastBatchIndex + 1; i < m_batchIndexData.size(); ++i ) {
const QPersistentModelIndex &index = m_batchIndexData[i];
if ( !index.isValid() )
continue;
const QString baseName = oldBaseName(index);
if ( baseName.isEmpty() )
continue;
const auto it = std::find_if(
std::begin(m_fileList), std::end(m_fileList),
[&](const BaseNameExtensions &baseNameExtensions) {
return baseNameExtensions.baseName == baseName;
});
QVariantMap dataMap;
QVariantMap mimeToExtension;
if ( it != m_fileList.cend() ) {
updateDataAndWatchFile(dir, *it, &dataMap, &mimeToExtension);
m_fileList.erase(it);
}
if ( mimeToExtension.isEmpty() ) {
m_model->removeRow(index.row());
} else {
dataMap.insert(mimeBaseName, baseName);
dataMap.insert(mimeExtensionMap, mimeToExtension);
updateIndexData(index, &dataMap);
}
if ( t.elapsed() > 20 ) {
COPYQ_LOG_VERBOSE( QStringLiteral("ItemSync: Items updated in %1 ms, last row %2/%3")
.arg(t.elapsed())
.arg(i + 1)
.arg(m_batchIndexData.size()) );
m_lastBatchIndex = i;
unlock();
m_updateTimer.start(batchItemUpdateIntervalMs);
return;
}
}
t.restart();
insertItemsFromFiles(dir, m_fileList);
if ( t.elapsed() > 100 )
log( QStringLiteral("ItemSync: Items created in %1 ms").arg(t.elapsed()) );
m_fileList.clear();
m_batchIndexData.clear();
unlock();
if (m_updatesEnabled)
m_updateTimer.start(m_interval);
}
void FileWatcher::updateItemsIfNeeded()
{
const auto time = QDateTime::currentMSecsSinceEpoch();
if (time < m_lastUpdateTimeMs + m_interval)
return;
updateItems();
}
void FileWatcher::setUpdatesEnabled(bool enabled)
{
m_updatesEnabled = enabled;
if (enabled)
updateItems();
else if ( m_batchIndexData.isEmpty() )
m_updateTimer.stop();
}
void FileWatcher::onRowsInserted(const QModelIndex &, int first, int last)
{
if (first < m_moveEnd)
m_moveEnd += last - first + 1;
saveItems(first, last, UpdateType::Inserted);
}
void FileWatcher::onDataChanged(const QModelIndex &a, const QModelIndex &b)
{
saveItems(a.row(), b.row(), UpdateType::Changed);
}
void FileWatcher::onRowsRemoved(const QModelIndex &, int first, int last)
{
if (first < m_moveEnd)
m_moveEnd -= std::min(m_moveEnd, last) - first + 1;
const bool wasFull = m_maxItems >= m_model->rowCount();
for ( const auto &index : indexList(first, last) ) {
if ( !index.isValid() )
continue;
const QString baseName = oldBaseName(index);
if ( isOwnBaseName(baseName) )
removeFilesForRemovedIndex(m_path, index);
}
// If the tab is no longer full, try to add new files.
if (wasFull)
m_updateTimer.start(0);
}
void FileWatcher::onRowsMoved(const QModelIndex &, int start, int end, const QModelIndex &, int destinationRow)
{
// Update copyq_* base names for moved rows and all rows above so that file
// are ordered the same way as the rows.
//
// The update is postponed and batched since it may need to go through a
// lot of items.
const int count = end - start + 1;
if (destinationRow < start) {
m_moveEnd = std::max(m_moveEnd, destinationRow + count - 1);
} else if (destinationRow > end) {
m_moveEnd = std::max(m_moveEnd, destinationRow - 1);
} else {
m_moveEnd = std::max(m_moveEnd, end);
}
m_moveTimer.start(0);
}
void FileWatcher::updateMovedRows()
{
if ( !lock() ) {
m_moveTimer.start();
return;
}
QString baseName = findLastOwnBaseName(m_model, m_moveEnd + 1);
QSet<QString> baseNames;
QDir dir(m_path);
const int batchStart = std::max(0, m_moveEnd - 100);
const auto indexList = this->indexList(batchStart, m_moveEnd);
for (const auto &index : indexList) {
const QString currentBaseName = FileWatcher::getBaseName(index);
// Skip renaming non-owned items
if ( !currentBaseName.isEmpty() && !isOwnBaseName(currentBaseName) )
continue;
// Skip already sorted
if ( isBaseNameLessThan(currentBaseName, baseName) ) {
baseName = currentBaseName;
continue;
}
if ( !renameToUnique(dir, baseNames, &baseName, m_formatSettings) )
return;
baseNames.insert(baseName);
const QVariantMap data = {{mimeBaseName, baseName}};
m_model->setData(index, data, contentType::updateData);
}
if ( !renameMoveCopy(dir, indexList, UpdateType::Changed) )
return;
unlock();
m_moveEnd = batchStart - 1;
if (0 <= m_moveEnd)
m_moveTimer.start(batchItemUpdateIntervalMs);
else
m_moveEnd = -1;
}
QString FileWatcher::oldBaseName(const QModelIndex &index) const
{
return index.data(contentType::data).toMap().value(mimeOldBaseName).toString();
}
void FileWatcher::createItems(const QVector<QVariantMap> &items, int targetRow)
{
if ( items.isEmpty() )
return;
const int row = qMax( 0, qMin(targetRow, m_model->rowCount()) );
if ( !m_model->insertRows(row, items.size()) )
return;
// Find index if it was moved after inserted.
const int rows = m_model->rowCount();
auto it = std::begin(items);
for ( int i = 0; i < rows; ++i ) {
const int row2 = (row + i) % rows;
auto index = m_model->index(row2, 0);
if ( getBaseName(index).isEmpty() ) {
QVariantMap data = *it;
updateIndexData(index, &data);
++it;
if (it == std::end(items))
break;
}
}
}
void FileWatcher::updateIndexData(const QModelIndex &index, QVariantMap *itemData)
{
const QString baseName = getBaseName(*itemData);
if ( baseName.isEmpty() ) {
m_model->setData(index, *itemData, contentType::data);
return;
}
itemData->insert(mimeOldBaseName, baseName);
const QVariantMap mimeToExtension = itemData->value(mimeExtensionMap).toMap();
for ( auto it = mimeToExtension.begin(); it != mimeToExtension.end(); ++it ) {
if ( !it.key().startsWith(COPYQ_MIME_PREFIX_ITEMSYNC) && !it.key().startsWith(COPYQ_MIME_PRIVATE_PREFIX) ) {
const QString ext = it.value().toString();
const Hash hash = calculateHash(itemData->value(it.key()).toByteArray());
const QString mime = mimeHashPrefix + ext;
itemData->insert(mime, hash);
}
}
m_model->setData(index, *itemData, contentType::data);
}
QList<QPersistentModelIndex> FileWatcher::indexList(int first, int last)
{
QList<QPersistentModelIndex> indexList;
indexList.reserve(last - first + 1);
// List items in reverse order so the most recent file is created for the
// top item.
for (int i = last; i >= first; --i)
indexList.append( m_model->index(i, 0) );
return indexList;
}
void FileWatcher::saveItems(int first, int last, UpdateType updateType)
{
if ( !lock() )
return;
if ( !m_batchIndexData.isEmpty() ) {
COPYQ_LOG_VERBOSE( QStringLiteral("ItemSync: Batch updates interrupted") );
m_batchIndexData.clear();
}
const auto indexList = this->indexList(first, last);
QDir dir(m_path);
if ( !renameMoveCopy(dir, indexList, updateType) )
return;
QStringList existingFiles = listFiles(dir);
for (const auto &index : indexList) {
if ( !index.isValid() )
continue;
const QString baseName = getBaseName(index);
const QString filePath = dir.absoluteFilePath(baseName);
QVariantMap itemData = index.data(contentType::data).toMap();
QVariantMap oldMimeToExtension = itemData.value(mimeExtensionMap).toMap();
QVariantMap mimeToExtension;
QVariantMap dataMapUnknown;
const QVariantMap noSaveData = itemData.value(mimeNoSave).toMap();
QMutableMapIterator<QString, QVariant> it(itemData);
while (it.hasNext()) {
const auto item = it.next();
const QString &format = item.key();
if ( format.startsWith(COPYQ_MIME_PREFIX_ITEMSYNC) || format.startsWith(COPYQ_MIME_PRIVATE_PREFIX) )
continue; // skip internal data
const QByteArray bytes = it.value().toByteArray();
const Hash hash = calculateHash(bytes);
if ( noSaveData.contains(format) && noSaveData[format].toByteArray() == hash ) {
it.remove();
continue;
}
bool hasFile = oldMimeToExtension.contains(format);
const QString ext = hasFile ? oldMimeToExtension[format].toString()
: findByFormat(format, m_formatSettings);
if ( !hasFile && ext.isEmpty() ) {
dataMapUnknown.insert(format, bytes);
} else {
mimeToExtension.insert(format, ext);
const Hash oldHash = index.data(contentType::data).toMap().value(mimeHashPrefix + ext).toByteArray();
if ( !saveItemFile(filePath + ext, bytes, &existingFiles, hash != oldHash) )
return;
}
}
for ( auto it = oldMimeToExtension.constBegin();
it != oldMimeToExtension.constEnd(); ++it )
{
if ( it.key().startsWith(mimeNoFormat) )
mimeToExtension.insert( it.key(), it.value() );
}
if ( mimeToExtension.isEmpty() || !dataMapUnknown.isEmpty() ) {
mimeToExtension.insert(mimeUnknownFormats, dataFileSuffix);
QByteArray data = serializeData(dataMapUnknown);
if ( !saveItemFile(filePath + dataFileSuffix, data, &existingFiles) )
return;
}
if ( !noSaveData.isEmpty() || mimeToExtension != oldMimeToExtension ) {
itemData.remove(mimeNoSave);
for ( auto format = mimeToExtension.keyBegin(); format != mimeToExtension.keyEnd(); ++format )
oldMimeToExtension.remove(*format);
itemData.insert(mimeExtensionMap, mimeToExtension);
updateIndexData(index, &itemData);
// Remove files of removed formats.
removeFormatFiles(filePath, oldMimeToExtension);
}
}
unlock();
}
bool FileWatcher::renameMoveCopy(
const QDir &dir, const QList<QPersistentModelIndex> &indexList, UpdateType updateType)
{
if ( indexList.isEmpty() )
return false;
QSet<QString> baseNames;
QString baseName = findLastOwnBaseName(m_model, indexList.first().row() + 1);
for (const auto &index : indexList) {
if ( !index.isValid() )
continue;
QString olderBaseName = oldBaseName(index);
const QString oldBaseName = getBaseName(index);
if (updateType == UpdateType::Changed && olderBaseName.isEmpty())
olderBaseName = oldBaseName;
if ( !oldBaseName.isEmpty() )
baseName = oldBaseName;
bool newItem = updateType != UpdateType::Changed && olderBaseName.isEmpty();
bool itemRenamed = olderBaseName != baseName;
if ( newItem || itemRenamed ) {
if ( !renameToUnique(dir, baseNames, &baseName, m_formatSettings) )
return false;
itemRenamed = olderBaseName != baseName;
baseNames.insert(baseName);
}
QVariantMap itemData = index.data(contentType::data).toMap();
const QString syncPath = itemData.value(mimeSyncPath).toString();
bool copyFilesFromOtherTab = !syncPath.isEmpty() && syncPath != m_path;
if (copyFilesFromOtherTab || itemRenamed) {
const QVariantMap mimeToExtension = itemData.value(mimeExtensionMap).toMap();
const QString newBasePath = m_path + '/' + baseName;
if ( !syncPath.isEmpty() ) {
copyFormatFiles(syncPath + '/' + oldBaseName, newBasePath, mimeToExtension);
} else {
// Move files.
if ( !olderBaseName.isEmpty() )
moveFormatFiles(m_path + '/' + olderBaseName, newBasePath, mimeToExtension);
}
itemData.remove(mimeSyncPath);
itemData.insert(mimeBaseName, baseName);
updateIndexData(index, &itemData);
if ( oldBaseName.isEmpty() && itemData.contains(mimeUriList) ) {
if ( copyFilesFromUriList(itemData[mimeUriList].toByteArray(), index.row(), baseNames) )
m_model->removeRow(index.row());
}
}
}
return true;
}
void FileWatcher::updateDataAndWatchFile(const QDir &dir, const BaseNameExtensions &baseNameWithExts,
QVariantMap *dataMap, QVariantMap *mimeToExtension)
{
const QString basePath = dir.absoluteFilePath(baseNameWithExts.baseName);
for (const auto &ext : baseNameWithExts.exts) {
if ( ext.format.isEmpty() )
continue;
const QString fileName = basePath + ext.extension;
const QString path = dir.absoluteFilePath(fileName);
QFile f(path);
if ( !f.open(QIODevice::ReadOnly) )
continue;
if ( ext.extension == dataFileSuffix ) {
QDataStream stream(&f);
QVariantMap dataMap2;
if ( deserializeData(&stream, &dataMap2) ) {
for (auto it = dataMap2.constBegin(); it != dataMap2.constEnd(); ++it) {
const QVariant &value = it.value();
const qint64 size = value.type() == QVariant::ByteArray
? value.toByteArray().size()
: value.value<SyncDataFile>().size();
if (m_itemDataThreshold >= 0 && size > m_itemDataThreshold) {
const QVariant syncDataFile = QVariant::fromValue(SyncDataFile(path, it.key()));
dataMap->insert(it.key(), syncDataFile);
} else {
dataMap->insert(it.key(), value);
}
}
mimeToExtension->insert(mimeUnknownFormats, dataFileSuffix);
}
} else if ( f.size() > sizeLimit || ext.format.startsWith(mimeNoFormat)
|| dataMap->contains(ext.format) )
{
mimeToExtension->insert(mimeNoFormat + ext.extension, ext.extension);
} else if ( m_itemDataThreshold >= 0 && f.size() > m_itemDataThreshold ) {
const QVariant value = QVariant::fromValue(SyncDataFile(path));
dataMap->insert(ext.format, value);
mimeToExtension->insert(ext.format, ext.extension);
} else {
dataMap->insert(ext.format, f.readAll());
mimeToExtension->insert(ext.format, ext.extension);
}
}
}
bool FileWatcher::copyFilesFromUriList(const QByteArray &uriData, int targetRow, const QSet<QString> &baseNames)
{
QMimeData tmpData;
tmpData.setData(mimeUriList, uriData);
const QDir dir(m_path);
QVector<QVariantMap> items;
for ( const auto &url : tmpData.urls() ) {
if ( !url.isLocalFile() )
continue;
QFile f(url.toLocalFile());
if ( !f.exists() )
continue;
QString extName;
QString baseName;
getBaseNameAndExtension( QFileInfo(f).fileName(), &baseName, &extName,
m_formatSettings );
if ( !renameToUnique(dir, baseNames, &baseName, m_formatSettings) )
continue;
const QString targetFilePath = dir.absoluteFilePath(baseName + extName);
f.copy(targetFilePath);
Ext ext;
if ( getBaseNameExtension(targetFilePath, m_formatSettings, &baseName, &ext) ) {
BaseNameExtensions baseNameExts(baseName, {ext});
const QVariantMap item = itemDataFromFiles( QDir(m_path), baseNameExts );
items.append(item);
if (items.size() >= m_maxItems)
break;
}
}
createItems(items, targetRow);
return !items.isEmpty();
}
| 37,444
|
C++
|
.cpp
| 970
| 30.813402
| 117
| 0.629747
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,109
|
itemsynctests.cpp
|
hluk_CopyQ/plugins/itemsync/tests/itemsynctests.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemsynctests.h"
#include "common/commandstatus.h"
#include "common/mimetypes.h"
#include "common/sleeptimer.h"
#include "tests/test_utils.h"
#include <QDir>
#include <QFile>
#include <memory>
namespace {
using FilePtr = std::shared_ptr<QFile>;
const char sep[] = " ;; ";
const auto confirmRemoveDialogId = "focus::QPushButton in :QMessageBox";
class TestDir final {
public:
explicit TestDir(int i, bool createPath = true)
: m_dir(ItemSyncTests::testDir(i))
{
clear();
if (createPath)
create();
}
~TestDir()
{
clear();
}
void clear()
{
if (isValid())
m_dir.removeRecursively();
}
void create()
{
if ( !m_dir.mkpath(".") )
Q_ASSERT(false);
}
bool isValid() const
{
return m_dir.exists();
}
QStringList files() const
{
QStringList files = m_dir.entryList(QDir::AllEntries | QDir::NoDotAndDotDot, QDir::Name);
files.removeOne(QStringLiteral(".copyq_lock"));
return files;
}
FilePtr file(const QString &fileName) const
{
return std::make_shared<QFile>(filePath(fileName));
}
QString filePath(const QString &fileName) const
{
return m_dir.absoluteFilePath(fileName);
}
bool remove(const QString &fileName)
{
return QFile::remove(filePath(fileName));
}
private:
Q_DISABLE_COPY(TestDir)
QDir m_dir;
};
QByteArray createFile(const TestDir &dir, const QString &fileName, const QByteArray &content)
{
FilePtr file(dir.file(fileName));
if ( file->exists() )
return "File already exists!";
if ( !file->open(QIODevice::WriteOnly) )
return "Cannot open file!";
if ( file->write(content) == -1 )
return "Cannot write to file!";
file->close();
return "";
}
} // namespace
ItemSyncTests::ItemSyncTests(const TestInterfacePtr &test, QObject *parent)
: QObject(parent)
, m_test(test)
{
m_test->setEnv("COPYQ_SYNC_UPDATE_INTERVAL_MS", "100");
}
QString ItemSyncTests::testTab(int i)
{
return ::testTab(i);
}
QString ItemSyncTests::testDir(int i)
{
return QDir::tempPath() + "/copyq_test_dirs/itemsync_" + QString::number(i);
}
void ItemSyncTests::initTestCase()
{
TEST(m_test->initTestCase());
}
void ItemSyncTests::cleanupTestCase()
{
TEST(m_test->cleanupTestCase());
}
void ItemSyncTests::init()
{
TEST(m_test->init());
QDir tmpDir(QDir::cleanPath(testDir(0) + "/.."));
if ( tmpDir.exists() )
QVERIFY(tmpDir.removeRecursively());
}
void ItemSyncTests::cleanup()
{
TEST( m_test->cleanup() );
}
void ItemSyncTests::createRemoveTestDir()
{
TestDir dir1(1);
TestDir dir2(2);
QVERIFY(dir1.isValid());
QCOMPARE(dir1.files().join(sep), QString());
QVERIFY(dir2.isValid());
QCOMPARE(dir2.files().join(sep), QString());
const QString testFileName1 = "test1.txt";
FilePtr f1(dir1.file(testFileName1));
QVERIFY(!f1->exists());
QVERIFY(f1->open(QIODevice::WriteOnly));
f1->close();
QCOMPARE(dir1.files().join(sep), testFileName1);
dir1.clear();
QVERIFY(!dir1.isValid());
QVERIFY(!f1->exists());
QVERIFY(dir2.isValid());
dir2.clear();
QVERIFY(!dir1.isValid());
QVERIFY(!dir2.isValid());
dir1.create();
QVERIFY(dir1.isValid());
QCOMPARE(dir2.files().join(sep), QString());
}
void ItemSyncTests::itemsToFiles()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN(Args() << "show" << tab1, "");
const Args args = Args() << "tab" << tab1;
RUN(args << "add" << "A" << "B" << "C", "");
RUN(args << "read" << "0" << "1" << "2", "C\nB\nA");
RUN(args << "size", "3\n");
const auto files = dir1.files();
QVERIFY2( files.size() == 3, files.join(sep).toUtf8() );
QVERIFY2( files[0].startsWith("copyq_"), files[0].toUtf8() );
QVERIFY2( files[1].startsWith("copyq_"), files[1].toUtf8() );
QVERIFY2( files[2].startsWith("copyq_"), files[2].toUtf8() );
}
void ItemSyncTests::filesToItems()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN(Args() << "show" << tab1, "");
const Args args = Args() << "tab" << tab1;
RUN(args << "size", "0\n");
const QByteArray text1 = "Hello world!";
createFile(dir1, "test1.txt", text1);
QTest::qSleep(1200);
const QByteArray text2 = "And hello again!";
TEST(createFile(dir1, "test2.txt", text2));
WAIT_ON_OUTPUT(args << "size", "2\n");
// Older files first.
RUN(args << "read" << "0", text1);
RUN(args << "read" << "1", text2);
}
void ItemSyncTests::removeOwnItems()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN(Args() << "show" << tab1, "");
const Args args = Args() << "separator" << "," << "tab" << tab1;
RUN(args << "add" << "A" << "B" << "C" << "D", "");
const auto files = dir1.files();
QVERIFY2( files.size() == 4, files.join(sep).toUtf8() );
QVERIFY2( files[0].startsWith("copyq_"), files[0].toUtf8() );
QVERIFY2( files[1].startsWith("copyq_"), files[1].toUtf8() );
QVERIFY2( files[2].startsWith("copyq_"), files[2].toUtf8() );
QVERIFY2( files[3].startsWith("copyq_"), files[3].toUtf8() );
// Move to test tab and select second and third item.
RUN("setCurrentTab" << tab1, "");
RUN(args << "selectItems" << "1" << "2", "true\n");
RUN(args << "testSelected", tab1.toUtf8() + " 2 1 2\n");
// Remove selected items.
RUN(args << "keys" << m_test->shortcutToRemove(), "");
RUN(args << "read" << "0" << "1" << "2" << "3", "D,A,,");
QCOMPARE( dir1.files().join(sep),
files[0]
+ sep + files[3]
);
// Removing own items works from script.
RUN(args << "remove" << "1", "");
RUN(args << "read" << "0" << "1" << "2" << "3", "D,,,");
QCOMPARE( dir1.files().join(sep), files[3] );
}
void ItemSyncTests::removeNotOwnedItems()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN(Args() << "show" << tab1, "");
const Args args = Args() << "separator" << "," << "tab" << tab1;
const QString fileA = "test1.txt";
const QString fileB = "test2.txt";
const QString fileC = "test3.txt";
const QString fileD = "test4.txt";
TEST(createFile(dir1, fileA, "A"));
WAIT_ON_OUTPUT(args << "size", "1\n");
TEST(createFile(dir1, fileB, "B"));
WAIT_ON_OUTPUT(args << "size", "2\n");
TEST(createFile(dir1, fileC, "C"));
WAIT_ON_OUTPUT(args << "size", "3\n");
TEST(createFile(dir1, fileD, "D"));
WAIT_ON_OUTPUT(args << "size", "4\n");
QCOMPARE( dir1.files().join(sep),
fileA
+ sep + fileB
+ sep + fileC
+ sep + fileD
);
// Move to test tab and select second and third item.
RUN("setCurrentTab" << tab1, "");
RUN(args << "selectItems" << "1" << "2", "true\n");
RUN(args << "testSelected", tab1.toUtf8() + " 2 1 2\n");
// Accept the "Remove Items?" dialog.
RUN(args << "keys" << clipboardBrowserId << m_test->shortcutToRemove() << confirmRemoveDialogId, "");
RUN(args << "keys" << confirmRemoveDialogId << "ENTER" << clipboardBrowserId, "");
RUN(args << "read" << "0" << "1" << "2" << "3", "A,D,,");
QCOMPARE( dir1.files().join(sep),
fileA
+ sep + fileD
);
// Removing not owned items from script doesn't work.
RUN_EXPECT_ERROR(args << "remove" << "1", CommandException);
QCOMPARE( dir1.files().join(sep),
fileA
+ sep + fileD
);
}
void ItemSyncTests::removeNotOwnedItemsCancel()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN(Args() << "show" << tab1, "");
const Args args = Args() << "separator" << "," << "tab" << tab1;
const QString fileA = "test1.txt";
const QString fileB = "test2.txt";
TEST(createFile(dir1, fileA, "A"));
WAIT_ON_OUTPUT(args << "size", "1\n");
TEST(createFile(dir1, fileB, "B"));
WAIT_ON_OUTPUT(args << "size", "2\n");
QCOMPARE(dir1.files().join(sep), fileA + sep + fileB );
// Move to test tab and select second item.
RUN("setCurrentTab" << tab1, "");
RUN(args << "selectItems" << "1", "true\n");
RUN(args << "testSelected", tab1.toUtf8() + " 1 1\n");
// Don't accept the "Remove Items?" dialog.
RUN(args << "keys" << clipboardBrowserId << m_test->shortcutToRemove() << confirmRemoveDialogId, "");
RUN(args << "testSelected", tab1.toUtf8() + " 1 1\n");
RUN(args << "keys" << confirmRemoveDialogId << "ESCAPE" << clipboardBrowserId, "");
RUN(args << "read" << "0" << "1", "A,B");
QCOMPARE( dir1.files().join(sep), fileA + sep + fileB );
RUN(args << "testSelected", tab1.toUtf8() + " 1 1\n");
}
void ItemSyncTests::removeFiles()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN(Args() << "show" << tab1, "");
const Args args = Args() << "separator" << "," << "tab" << tab1;
RUN(args << "add" << "A" << "B" << "C" << "D", "");
const auto files = dir1.files();
QVERIFY2( files.size() == 4, files.join(sep).toUtf8() );
QVERIFY2( files[0].startsWith("copyq_"), files[0].toUtf8() );
QVERIFY2( files[1].startsWith("copyq_"), files[1].toUtf8() );
QVERIFY2( files[2].startsWith("copyq_"), files[2].toUtf8() );
QVERIFY2( files[3].startsWith("copyq_"), files[3].toUtf8() );
FilePtr file = dir1.file(files[2]);
QVERIFY(file->open(QIODevice::ReadOnly));
QCOMPARE(file->readAll().data(), QByteArray("C").data());
file->remove();
WAIT_ON_OUTPUT(args << "size", "3\n");
RUN(args << "read" << "0" << "1" << "2", "D,B,A");
dir1.file(files[1])->remove();
dir1.file(files[0])->remove();
WAIT_ON_OUTPUT(args << "size", "1\n");
RUN(args << "read" << "0", "D");
}
void ItemSyncTests::modifyItems()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN(Args() << "show" << tab1, "");
const Args args = Args() << "separator" << "," << "tab" << tab1;
RUN(args << "add" << "A" << "B" << "C" << "D", "");
const auto files = dir1.files();
QVERIFY2( files.size() == 4, files.join(sep).toUtf8() );
FilePtr file = dir1.file(files[2]);
QVERIFY(file->open(QIODevice::ReadOnly));
QCOMPARE(file->readAll().data(), QByteArray("C").data());
file->close();
RUN(args << "keys" << "HOME" << "DOWN" << "F2" << ":XXX" << "F2", "");
RUN(args << "size", "4\n");
RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "D,XXX,B,A,");
file = dir1.file(files[2]);
QVERIFY(file->open(QIODevice::ReadOnly));
QCOMPARE(file->readAll().data(), QByteArray("XXX").data());
file->close();
const auto script = R"(
setCommands([{
name: 'Modify current item',
inMenu: true,
shortcuts: ['Ctrl+F1'],
cmd: `
copyq: item = selectedItemsData()[0]
item[mimeText] = "ZZZ"
setSelectedItemData(0, item)
`
}])
)";
RUN(script, "");
RUN(args << "keys" << "HOME" << "DOWN" << "CTRL+F1", "");
WAIT_ON_OUTPUT(args << "read" << "1", "ZZZ");
RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "D,ZZZ,B,A,");
RUN(args << "unload" << tab1, "");
RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "D,ZZZ,B,A,");
file = dir1.file(files[2]);
QVERIFY(file->open(QIODevice::ReadOnly));
QCOMPARE(file->readAll().data(), QByteArray("ZZZ").data());
file->close();
}
void ItemSyncTests::modifyFiles()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN(Args() << "show" << tab1, "");
const Args args = Args() << "separator" << "," << "tab" << tab1;
RUN(args << "add" << "A" << "B" << "C" << "D", "");
const auto files = dir1.files();
QVERIFY2( files.size() == 4, files.join(sep).toUtf8() );
QVERIFY2( files[0].startsWith("copyq_"), files[0].toUtf8() );
QVERIFY2( files[1].startsWith("copyq_"), files[1].toUtf8() );
QVERIFY2( files[2].startsWith("copyq_"), files[2].toUtf8() );
QVERIFY2( files[3].startsWith("copyq_"), files[3].toUtf8() );
FilePtr file = dir1.file(files[2]);
QVERIFY(file->open(QIODevice::ReadWrite));
QCOMPARE(file->readAll().data(), QByteArray("C").data());
file->write("X");
file->close();
WAIT_ON_OUTPUT(args << "read" << "0" << "1" << "2" << "3", "D,CX,B,A");
RUN(args << "size", "4\n");
}
void ItemSyncTests::itemToClipboard()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN("show" << tab1, "");
const Args args = Args() << "tab" << tab1;
RUN(args << "add" << "TESTING2" << "TESTING1", "");
RUN(args << "read" << "0" << "1", "TESTING1\nTESTING2");
RUN("config"
<< "activate_closes" << "false"
<< "activate_focuses" << "false"
<< "activate_pastes" << "false"
,
"activate_closes=false\n"
"activate_focuses=false\n"
"activate_pastes=false\n"
);
// select second item and move to top
RUN("config" << "move" << "true", "true\n");
RUN(args << "selectItems" << "1", "true\n");
RUN(args << "keys" << "ENTER", "");
RUN(args << "read" << "0" << "1", "TESTING2\nTESTING1");
WAIT_FOR_CLIPBOARD("TESTING2");
RUN("clipboard", "TESTING2");
// select without moving
RUN("config" << "move" << "0", "false\n");
RUN(args << "selectItems" << "1", "true\n");
RUN(args << "keys" << "ENTER", "");
RUN(args << "read" << "0" << "1", "TESTING2\nTESTING1");
WAIT_FOR_CLIPBOARD("TESTING1");
RUN("clipboard", "TESTING1");
}
void ItemSyncTests::notes()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN(Args() << "show" << tab1, "");
const Args args = Args() << "separator" << ";" << "tab" << tab1;
RUN(args << "add" << "TEST1", "");
RUN(args << "keys"
<< "CTRL+N" << ":TEST2" << "F2"
<< "CTRL+N" << ":TEST3" << "F2", "");
RUN(args << "size", "3\n");
RUN(args << "read" << "0" << "1" << "2", "TEST3;TEST2;TEST1");
const auto files = dir1.files();
QVERIFY2( files.size() == 3, files.join(sep).toUtf8() );
QVERIFY2( files[0].startsWith("copyq_"), files[0].toUtf8() );
QVERIFY2( files[1].startsWith("copyq_"), files[1].toUtf8() );
QVERIFY2( files[2].startsWith("copyq_"), files[2].toUtf8() );
RUN(args << "keys" << "HOME" << "DOWN" << "SHIFT+F2" << ":NOTE1" << "F2", "");
RUN(args << "read" << mimeItemNotes << "0" << "1" << "2", ";NOTE1;");
// One new file for notes.
const QStringList files2 = dir1.files();
QCOMPARE( files2.size(), files.size() + 1 );
QString fileNote;
for (const auto &file : files2) {
if ( !files.contains(file) ) {
fileNote = file;
break;
}
}
// Read file with the notes.
FilePtr file = dir1.file(fileNote);
QVERIFY(file->open(QIODevice::ReadWrite));
QCOMPARE(file->readAll().data(), QByteArray("NOTE1").data());
// Modify notes.
file->write("+NOTE2");
file->close();
WAIT_ON_OUTPUT(args << "read" << mimeItemNotes << "0" << "1" << "2", ";NOTE1+NOTE2;");
RUN(args << "size", "3\n");
// Remove notes.
QVERIFY(file->remove());
WAIT_ON_OUTPUT(args << "read" << mimeItemNotes << "0" << "1" << "2", ";;");
RUN(args << "size", "3\n");
}
void ItemSyncTests::customFormats()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN(Args() << "show" << tab1, "");
const Args args = Args() << "separator" << ";" << "tab" << tab1;
createFile(dir1, "test1.xxx", "TEST1");
const auto mime1 = COPYQ_MIME_PREFIX "test-xxx";
const auto mime2 = COPYQ_MIME_PREFIX "test-zzz";
WAIT_ON_OUTPUT(args << "size", "1\n");
RUN(args << "read" << mime1 << "0", "TEST1");
createFile(dir1, "test2.yyy", "TEST2");
WAIT_ON_OUTPUT(args << "size", "2\n");
RUN(args << "read" << mime2 << "1", "TEST2");
createFile(dir1, "test3.zzz", "TEST3");
const auto script = QString(R"_(
print(' size: ')
print(size())
print(' basename: ')
print(read(plugins.itemsync.mimeBaseName, 0, 1, 2))
print(' mime1: ')
print(read('%1', 0, 1, 2))
print(' mime2: ')
print(read('%2', 0, 1, 2))
)_")
.arg(mime1)
.arg(mime2);
WAIT_ON_OUTPUT(
args << script,
" size: 3"
" basename: test1;test2;test3"
" mime1: TEST1;;"
" mime2: ;TEST2;TEST3"
);
// Remove
dir1.remove("test2.yyy");
WAIT_ON_OUTPUT(
args << script,
" size: 2"
" basename: test1;test3;"
" mime1: TEST1;;"
" mime2: ;TEST3;"
);
// Modify file
FilePtr file = dir1.file("test1.xxx");
QVERIFY(file->open(QIODevice::Append));
file->write("UPDATE");
file->close();
WAIT_ON_OUTPUT(
args << script,
" size: 2"
" basename: test1;test3;"
" mime1: TEST1UPDATE;;"
" mime2: ;TEST3;"
);
// Create item with custom data
RUN(args << "write" << mime2 << "NEW_ITEM", "");
RUN(args << "size", "3\n");
const auto files = dir1.files();
QVERIFY2( files[0].startsWith("copyq_"), files[0].toUtf8() );
const QString fileData = QString(files[0]).replace("txt", "zzz");
QVERIFY2( fileData.endsWith(".zzz"), fileData.toUtf8() );
// Check data
file = dir1.file(fileData);
QVERIFY(file->exists());
QVERIFY(file->open(QIODevice::ReadWrite));
QCOMPARE(file->readAll().data(), "NEW_ITEM");
// Modify data
file->write("+UPDATE");
file->close();
WAIT_ON_OUTPUT(
Args(args) << "read" << mime2 << "0" << "2" << mime1 << "1",
"NEW_ITEM+UPDATE;TEST3;TEST1UPDATE");
RUN(args << "size", "3\n");
}
void ItemSyncTests::getAbsoluteFilePath()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN(Args() << "show" << tab1, "");
const Args args = Args() << "separator" << ";" << "tab" << tab1;
const auto code = QString(
R"(
var path = plugins.itemsync.tabPaths["%1"]
var baseName = str(getItem(0)[plugins.itemsync.mimeBaseName])
var absoluteFilePath = Dir(path).absoluteFilePath(baseName)
print(absoluteFilePath)
)")
.arg(tab1);
createFile(dir1, "test1.txt", QByteArray());
WAIT_ON_OUTPUT(args << "size", "1\n");
RUN(args << code, dir1.filePath("test1"));
}
void ItemSyncTests::addItemsWhenFull()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
const Args args = Args() << "separator" << ";" << "tab" << tab1;
RUN(args << "show" << tab1, "");
RUN("config" << "maxitems" << "2", "2\n");
RUN(args << "add" << "A" << "B", "");
RUN(args << "read" << "0" << "1" << "2", "B;A;");
RUN(args << "add" << "C", "");
RUN(args << "read" << "0" << "1" << "2", "C;B;");
}
void ItemSyncTests::addItemsWhenFullOmitDeletingNotOwned()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
const Args args = Args() << "separator" << ";" << "tab" << tab1;
RUN(args << "show" << tab1, "");
RUN("config" << "maxitems" << "1", "1\n");
const QString testFileName1 = "test1.txt";
createFile(dir1, testFileName1, "NOT-OWNED");
WAIT_ON_OUTPUT(args << "size", "1\n");
RUN(args << "read" << "0" << "1", "NOT-OWNED;");
RUN(args << "add" << "A", "");
RUN(args << "read" << "0" << "1", "A;");
RUN(args << "remove" << "0", "");
WAIT_ON_OUTPUT(args << "size", "1\n");
RUN(args << "read" << "0" << "1", "NOT-OWNED;");
FilePtr f1(dir1.file(testFileName1));
QVERIFY(f1->exists());
}
void ItemSyncTests::moveOwnItemsSortsBaseNames()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN(Args() << "show" << tab1, "");
const Args args = Args() << "separator" << "," << "tab" << tab1;
const QString testScript = R"(
var baseNames = [];
for (var i = 0; i < 4; ++i) {
baseNames.push(str(read(plugins.itemsync.mimeBaseName, i)));
}
for (var i = 0; i < 3; ++i) {
var j = i + 1;
if (baseNames[i] <= baseNames[j]) {
print("Failed test: baseNames["+i+"] > baseNames["+j+"]\\n");
print(" Where baseNames["+i+"] = '" + baseNames[i] + "'\\n");
print(" baseNames["+j+"] = '" + baseNames[j] + "'\\n");
}
}
)";
RUN(args << "add" << "A" << "B" << "C" << "D", "");
RUN(args << "read(0,1,2,3)", "D,C,B,A");
RUN(args << testScript, "");
RUN(args << "keys" << "END" << "CTRL+UP", "");
RUN(args << "read(0,1,2,3)", "D,C,A,B");
RUN(args << testScript, "");
RUN(args << "keys" << "DOWN" << "CTRL+UP", "");
RUN(args << "read(0,1,2,3)", "D,C,B,A");
RUN(args << testScript, "");
RUN(args << "keys" << "DOWN" << "SHIFT+UP" << "CTRL+UP", "");
RUN(args << "read(0,1,2,3)", "D,B,A,C");
RUN(args << testScript, "");
RUN(args << "keys" << "CTRL+UP", "");
RUN(args << "read(0,1,2,3)", "B,A,D,C");
RUN(args << testScript, "");
RUN(args << "keys" << "CTRL+DOWN", "");
RUN(args << "read(0,1,2,3)", "D,B,A,C");
RUN(args << testScript, "");
RUN(args << "keys" << "END" << "CTRL+HOME", "");
RUN(args << "read(0,1,2,3)", "C,D,B,A");
RUN(args << testScript, "");
RUN(args << "keys" << "END" << "UP" << "CTRL+HOME", "");
RUN(args << "read(0,1,2,3)", "B,C,D,A");
RUN(args << testScript, "");
RUN(args << "keys" << "HOME" << "CTRL+END", "");
RUN(args << "read(0,1,2,3)", "C,D,A,B");
RUN(args << testScript, "");
}
void ItemSyncTests::avoidDuplicateItemsAddedFromClipboard()
{
TestDir dir1(1);
const QString tab1 = testTab(1);
RUN("show" << tab1, "");
const Args args = Args() << "separator" << "," << "tab" << tab1;
RUN("config" << "clipboard_tab" << tab1, tab1 + "\n");
WAIT_ON_OUTPUT("isClipboardMonitorRunning", "true\n");
TEST( m_test->setClipboard("one") );
WAIT_ON_OUTPUT(args << "read(0,1,2,3)", "one,,,");
TEST( m_test->setClipboard("two") );
WAIT_ON_OUTPUT(args << "read(0,1,2,3)", "two,one,,");
TEST( m_test->setClipboard("one") );
WAIT_ON_OUTPUT(args << "read(0,1,2,3)", "one,two,,");
}
void ItemSyncTests::saveLargeItem()
{
const auto tab = testTab(1);
const auto args = Args("tab") << tab;
const auto script = R"(
write(0, [{
'text/plain': '1234567890'.repeat(10000),
'application/x-copyq-test-data': 'abcdefghijklmnopqrstuvwxyz'.repeat(10000),
}])
)";
RUN(args << script, "");
for (int i = 0; i < 2; ++i) {
RUN(args << "read(0).left(20)", "12345678901234567890");
RUN(args << "read(0).length", "100000\n");
RUN(args << "getItem(0)[mimeText].left(20)", "12345678901234567890");
RUN(args << "getItem(0)[mimeText].length", "100000\n");
RUN(args << "getItem(0)['application/x-copyq-test-data'].left(26)", "abcdefghijklmnopqrstuvwxyz");
RUN(args << "getItem(0)['application/x-copyq-test-data'].length", "260000\n");
RUN(args << "ItemSelection().selectAll().itemAtIndex(0)[mimeText].length", "100000\n");
RUN("unload" << tab, tab + "\n");
}
RUN("show" << tab, "");
RUN("keys" << clipboardBrowserId << keyNameFor(QKeySequence::Copy), "");
WAIT_ON_OUTPUT("clipboard().left(20)", "12345678901234567890");
RUN("clipboard('application/x-copyq-test-data').left(26)", "abcdefghijklmnopqrstuvwxyz");
RUN("clipboard('application/x-copyq-test-data').length", "260000\n");
const auto tab2 = testTab(2);
const auto args2 = Args("tab") << tab2;
RUN("show" << tab2, "");
waitFor(waitMsPasteClipboard);
RUN("keys" << clipboardBrowserId << keyNameFor(QKeySequence::Paste), "");
RUN(args2 << "read(0).left(20)", "12345678901234567890");
RUN(args2 << "read(0).length", "100000\n");
RUN(args << "getItem(0)['application/x-copyq-test-data'].left(26)", "abcdefghijklmnopqrstuvwxyz");
RUN(args << "getItem(0)['application/x-copyq-test-data'].length", "260000\n");
}
| 24,272
|
C++
|
.cpp
| 648
| 31.686728
| 106
| 0.554556
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,110
|
itemtags.cpp
|
hluk_CopyQ/plugins/itemtags/itemtags.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemtags.h"
#include "ui_itemtagssettings.h"
#include "common/command.h"
#include "common/compatibility.h"
#include "common/contenttype.h"
#include "common/regexp.h"
#include "common/textdata.h"
#include "gui/iconfont.h"
#include "gui/iconselectbutton.h"
#include "gui/pixelratio.h"
#include "item/itemfilter.h"
#ifdef HAS_TESTS
# include "tests/itemtagstests.h"
#endif
#include <QBoxLayout>
#include <QColorDialog>
#include <QLabel>
#include <QMessageBox>
#include <QModelIndex>
#include <QPainter>
#include <QPixmap>
#include <QPushButton>
#include <QSettings>
#include <QtPlugin>
#include <QUrl>
#include <memory>
Q_DECLARE_METATYPE(ItemTags::Tag)
namespace {
const QLatin1String mimeTags("application/x-copyq-tags");
const QLatin1String configTags("tags");
const char propertyColor[] = "CopyQ_color";
namespace tagsTableColumns {
enum {
name,
match,
styleSheet,
color,
icon,
lock
};
}
class ElidedLabel final : public QLabel
{
public:
explicit ElidedLabel(const QString &text, QWidget *parent = nullptr)
: QLabel(text, parent)
{
}
protected:
void paintEvent(QPaintEvent *) override
{
QPainter p(this);
QFontMetrics fm = fontMetrics();
const QString elidedText = fm.elidedText(text(), Qt::ElideMiddle, rect().width());
p.drawText(rect(), Qt::AlignCenter, elidedText);
}
};
bool isTagValid(const ItemTags::Tag &tag)
{
return !tag.name.isEmpty()
|| !tag.icon.isEmpty()
|| !tag.styleSheet.isEmpty()
|| !tag.match.isEmpty();
}
QString serializeColor(const QColor &color)
{
if (color.alpha() == 255)
return color.name();
return QString::fromLatin1("rgba(%1,%2,%3,%4)")
.arg(color.red())
.arg(color.green())
.arg(color.blue())
.arg(color.alpha());
}
QColor deserializeColor(const QString &colorName)
{
if ( colorName.startsWith("rgba(") ) {
QStringList list = colorName.mid(5, colorName.indexOf(')') - 5).split(',');
int r = list.value(0).toInt();
int g = list.value(1).toInt();
int b = list.value(2).toInt();
int a = list.value(3).toInt();
return QColor(r, g, b, a);
}
return QColor(colorName);
}
void setColorIcon(QPushButton *button, const QColor &color)
{
QPixmap pix(button->iconSize());
pix.fill(color);
button->setIcon(pix);
button->setProperty(propertyColor, color);
}
void setFixedColumnSize(QTableWidget *table, int logicalIndex)
{
table->horizontalHeader()->setSectionResizeMode(logicalIndex, QHeaderView::Fixed);
table->resizeColumnToContents(logicalIndex);
}
QVariant cellWidgetProperty(QTableWidget *table, int row, int column, const char *property)
{
return table->cellWidget(row, column)->property(property);
}
QStringList tags(const QVariant &tags)
{
return getTextData( tags.toByteArray() )
.split(',', SKIP_EMPTY_PARTS);
}
QStringList tags(const QVariantMap &itemData)
{
return tags( itemData.value(mimeTags) );
}
QString toScriptString(const QString &text)
{
return "decodeURIComponent('" + QUrl::toPercentEncoding(text) + "')";
}
QString addTagText()
{
return ItemTagsLoader::tr("Add a Tag");
}
QString removeTagText()
{
return ItemTagsLoader::tr("Remove a Tag");
}
Command dummyTagCommand()
{
Command c;
c.icon = QString(QChar(IconTag));
c.inMenu = true;
return c;
}
void addTagCommands(const QString &tagName, const QString &match, QVector<Command> *commands)
{
Command c;
const QString name = !tagName.isEmpty() ? tagName : match;
const QString tagString = toScriptString(name);
const QString quotedTag = quoteString(name);
c = dummyTagCommand();
c.internalId = QStringLiteral("copyq_tags_tag:") + name;
c.name = ItemTagsLoader::tr("Toggle Tag %1").arg(quotedTag);
c.cmd = QStringLiteral(
"copyq: (plugins.itemtags.hasTag(%1) ? plugins.itemtags.untag : plugins.itemtags.tag)(%1)"
).arg(tagString);
commands->append(c);
}
QString escapeTagField(const QString &field)
{
return QString(field).replace("\\", "\\\\").replace(";;", ";\\;");
}
QString unescapeTagField(const QString &field)
{
return QString(field).replace(";\\;", ";;").replace("\\\\", "\\");
}
void initTagWidget(QWidget *tagWidget, const ItemTags::Tag &tag, const QFont &font)
{
tagWidget->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
tagWidget->setStyleSheet(
"* {"
";background:transparent"
";color:" + serializeColor(tag.color) +
";" + tag.styleSheet +
"}"
"QLabel {"
";background:transparent"
";border:none"
"}"
);
auto layout = new QHBoxLayout(tagWidget);
const int x = QFontMetrics(font).height() / 6;
layout->setContentsMargins(x, 0, x, 0);
layout->setSpacing(x * 2);
if (tag.icon.size() > 1) {
QLabel *iconLabel = new QLabel(tagWidget);
const QPixmap icon(tag.icon);
iconLabel->setPixmap(icon);
layout->addWidget(iconLabel);
} else if (tag.icon.size() == 1) {
QLabel *iconLabel = new QLabel(tagWidget);
iconLabel->setFont(iconFont());
iconLabel->setText(tag.icon);
layout->addWidget(iconLabel);
}
if (!tag.name.isEmpty()) {
auto label = new ElidedLabel(tag.name, tagWidget);
label->setFont(font);
layout->addWidget(label);
}
}
QFont smallerFont(QFont font)
{
if (font.pixelSize() != -1)
font.setPixelSize( static_cast<int>(0.75 * font.pixelSize()) );
else
font.setPointSizeF(0.75 * font.pointSizeF());
return font;
}
void addTagButtons(QBoxLayout *layout, const ItemTags::Tags &tags)
{
Q_ASSERT(layout->parentWidget());
layout->addStretch(1);
const QFont font = smallerFont(layout->parentWidget()->font());
for (const auto &tag : tags) {
if ( tag.name.isEmpty() && tag.icon.isEmpty() )
continue;
QWidget *tagWidget = new QWidget(layout->parentWidget());
initTagWidget(tagWidget, tag, font);
layout->addWidget(tagWidget);
}
}
ItemTags::Tag findMatchingTag(const QString &tagText, const ItemTags::Tags &tags)
{
for (const auto &tag : tags) {
if ( tag.match.isEmpty() ) {
if (tag.name == tagText)
return tag;
} else {
const auto re = anchoredRegExp(tag.match);
if (tagText.contains(re))
return tag;
}
}
return ItemTags::Tag();
}
bool isLocked(const QModelIndex &index, const ItemTags::Tags &tags)
{
const auto dataMap = index.data(contentType::data).toMap();
const auto itemTags = ::tags(dataMap);
return std::any_of(
std::begin(itemTags), std::end(itemTags),
[&tags](const QString &itemTag){
const auto tag = findMatchingTag(itemTag, tags);
return tag.lock;
});
}
bool containsLockedItems(const QModelIndexList &indexList, const ItemTags::Tags &tags)
{
return std::any_of(
std::begin(indexList), std::end(indexList),
[&tags](const QModelIndex &index){
return isLocked(index, tags);
});
}
class TagTableWidgetItem final : public QTableWidgetItem
{
public:
enum {
TagRole = Qt::UserRole
};
explicit TagTableWidgetItem(const QString &text)
: QTableWidgetItem(text)
{
}
QVariant data(int role) const override
{
if (role == Qt::DecorationRole)
return m_pixmap;
return QTableWidgetItem::data(role);
}
void setData(int role, const QVariant &value) override
{
if (role == TagRole)
setTag( value.value<ItemTags::Tag>() );
QTableWidgetItem::setData(role, value);
}
private:
void setTag(const ItemTags::Tag &tag)
{
if ( isTagValid(tag) ) {
QWidget tagWidget;
initTagWidget(&tagWidget, tag, smallerFont(QFont()));
const auto ratio = pixelRatio(&tagWidget);
m_pixmap = QPixmap( tagWidget.sizeHint() * ratio );
m_pixmap.setDevicePixelRatio(ratio);
m_pixmap.fill(Qt::transparent);
QPainter painter(&m_pixmap);
tagWidget.render(&painter);
} else {
m_pixmap = QPixmap();
}
}
QPixmap m_pixmap;
};
} // namespace
ItemTags::ItemTags(ItemWidget *childItem, const Tags &tags)
: QWidget( childItem->widget()->parentWidget() )
, ItemWidgetWrapper(childItem, this)
, m_tagWidget(new QWidget(childItem->widget()->parentWidget()))
{
QBoxLayout *tagLayout = new QHBoxLayout(m_tagWidget);
tagLayout->setContentsMargins({});
addTagButtons(tagLayout, tags);
childItem->widget()->setObjectName("item_child");
childItem->widget()->setParent(this);
QBoxLayout *layout = new QVBoxLayout(this);
layout->setContentsMargins({});
layout->setSpacing(0);
layout->addWidget(m_tagWidget, 0);
layout->addWidget( childItem->widget(), 1 );
}
void ItemTags::updateSize(QSize maximumSize, int idealWidth)
{
setMaximumSize(maximumSize);
m_tagWidget->setFixedWidth(idealWidth);
ItemWidgetWrapper::updateSize(maximumSize, idealWidth);
adjustSize();
}
QStringList ItemTagsScriptable::getUserTags() const
{
return m_userTags;
}
QString ItemTagsScriptable::getMimeTags() const
{
return mimeTags;
}
QStringList ItemTagsScriptable::tags()
{
const auto args = currentArguments();
const auto rows = this->rows(args, 0);
QStringList allTags;
for (int row : rows)
allTags << this->tags(row);
return allTags;
}
void ItemTagsScriptable::tag()
{
const auto args = currentArguments();
auto tagName = args.value(0).toString();
if ( tagName.isEmpty() ) {
tagName = askTagName( addTagText(), m_userTags );
if ( tagName.isEmpty() )
return;
}
if ( args.size() <= 1 ) {
const auto dataValueList = call("selectedItemsData").toList();
QVariantList dataList;
dataList.reserve( dataValueList.size() );
for (const auto &itemDataValue : dataValueList) {
auto itemData = itemDataValue.toMap();
auto itemTags = ::tags(itemData);
if ( addTag(tagName, &itemTags) )
itemData.insert( mimeTags, itemTags.join(",") );
dataList.append(itemData);
}
call( "setSelectedItemsData", QVariantList() << QVariant(dataList) );
} else {
for ( int row : rows(args, 1) ) {
auto itemTags = tags(row);
if ( addTag(tagName, &itemTags) )
setTags(row, itemTags);
}
}
}
void ItemTagsScriptable::untag()
{
const auto args = currentArguments();
auto tagName = args.value(0).toString();
if ( args.size() <= 1 ) {
const auto dataValueList = call("selectedItemsData").toList();
if ( tagName.isEmpty() ) {
QStringList allTags;
for (const auto &itemDataValue : dataValueList) {
const auto itemData = itemDataValue.toMap();
allTags.append( ::tags(itemData) );
}
tagName = askRemoveTagName(allTags);
if ( allTags.isEmpty() )
return;
}
QVariantList dataList;
dataList.reserve( dataValueList.size() );
for (const auto &itemDataValue : dataValueList) {
auto itemData = itemDataValue.toMap();
auto itemTags = ::tags(itemData);
if ( removeTag(tagName, &itemTags) )
itemData.insert( mimeTags, itemTags.join(",") );
dataList.append(itemData);
}
call( "setSelectedItemsData", QVariantList() << QVariant(dataList) );
} else {
const auto rows = this->rows(args, 1);
if ( tagName.isEmpty() ) {
QStringList allTags;
for (int row : rows)
allTags.append( this->tags(row) );
tagName = askRemoveTagName(allTags);
if ( allTags.isEmpty() )
return;
}
for (int row : rows) {
auto itemTags = tags(row);
if ( removeTag(tagName, &itemTags) )
setTags(row, itemTags);
}
}
}
void ItemTagsScriptable::clearTags()
{
const auto args = currentArguments();
if ( args.isEmpty() ) {
const auto dataValueList = call("selectedItemsData").toList();
QVariantList dataList;
for (const auto &itemDataValue : dataValueList) {
auto itemData = itemDataValue.toMap();
itemData.remove(mimeTags);
dataList.append(itemData);
}
call( "setSelectedItemsData", QVariantList() << QVariant(dataList) );
} else {
const auto rows = this->rows(args, 0);
for (int row : rows)
setTags(row, QStringList());
}
}
bool ItemTagsScriptable::hasTag()
{
const auto args = currentArguments();
const auto tagName = args.value(0).toString();
if ( args.size() <= 1 ) {
const auto dataValueList = call("selectedItemsData").toList();
for (const auto &itemDataValue : dataValueList) {
const auto itemData = itemDataValue.toMap();
const auto itemTags = ::tags(itemData);
if ( itemTags.contains(tagName) )
return true;
}
return false;
}
const auto row = args.value(1).toInt();
return tags(row).contains(tagName);
}
QString ItemTagsScriptable::askTagName(const QString &dialogTitle, const QStringList &tags)
{
const auto value = call( "dialog", QVariantList()
<< ".title" << dialogTitle
<< dialogTitle << tags );
return value.toString();
}
QString ItemTagsScriptable::askRemoveTagName(const QStringList &tags)
{
if ( tags.isEmpty() )
return QString();
if ( tags.size() == 1 )
return tags.first();
return askTagName( removeTagText(), tags );
}
QList<int> ItemTagsScriptable::rows(const QVariantList &arguments, int skip)
{
QList<int> rows;
for (int i = skip; i < arguments.size(); ++i) {
bool ok;
const auto row = arguments[i].toInt(&ok);
if (ok)
rows.append(row);
}
return rows;
}
QStringList ItemTagsScriptable::tags(int row)
{
const auto value = call("read", QVariantList() << mimeTags << row);
return ::tags(value);
}
void ItemTagsScriptable::setTags(int row, const QStringList &tags)
{
const auto value = tags.join(",");
call("change", QVariantList() << row << mimeTags << value);
}
bool ItemTagsScriptable::addTag(const QString &tagName, QStringList *tags)
{
if ( tags->contains(tagName) )
return false;
tags->append(tagName);
tags->sort();
return true;
}
bool ItemTagsScriptable::removeTag(const QString &tagName, QStringList *tags)
{
if ( !tags->contains(tagName) )
return false;
tags->removeOne(tagName);
return true;
}
ItemTagsSaver::ItemTagsSaver(const ItemTags::Tags &tags, const ItemSaverPtr &saver)
: ItemSaverWrapper(saver)
, m_tags(tags)
{
}
bool ItemTagsSaver::canRemoveItems(const QList<QModelIndex> &indexList, QString *error)
{
if ( !containsLockedItems(indexList, m_tags) )
return ItemSaverWrapper::canRemoveItems(indexList, error);
if (error) {
*error = "Removing items with locked tags is not allowed (untag items first)";
return false;
}
QMessageBox::information(
QApplication::activeWindow(),
ItemTagsLoader::tr("Cannot Remove Items With a Locked Tag"),
ItemTagsLoader::tr("Untag items first to remove them.") );
return false;
}
bool ItemTagsSaver::canDropItem(const QModelIndex &index)
{
return !isLocked(index, m_tags) && ItemSaverWrapper::canDropItem(index);
}
bool ItemTagsSaver::canMoveItems(const QList<QModelIndex> &indexList)
{
return !containsLockedItems(indexList, m_tags)
&& ItemSaverWrapper::canMoveItems(indexList);
}
ItemTagsLoader::ItemTagsLoader()
: m_blockDataChange(false)
{
}
ItemTagsLoader::~ItemTagsLoader() = default;
QStringList ItemTagsLoader::formatsToSave() const
{
return QStringList(mimeTags);
}
void ItemTagsLoader::applySettings(QSettings &settings)
{
QStringList tags;
for (int row = 0; row < ui->tableWidget->rowCount(); ++row) {
const Tag tag = tagFromTable(row);
if (isTagValid(tag))
tags.append(serializeTag(tag));
}
settings.setValue(configTags, tags);
}
void ItemTagsLoader::loadSettings(const QSettings &settings)
{
m_tags.clear();
for (const auto &tagField : settings.value(configTags).toStringList()) {
Tag tag = deserializeTag(tagField);
if (isTagValid(tag))
m_tags.append(tag);
}
}
QWidget *ItemTagsLoader::createSettingsWidget(QWidget *parent)
{
ui.reset(new Ui::ItemTagsSettings);
QWidget *w = new QWidget(parent);
ui->setupUi(w);
// Init tag table.
for (const auto &tag : m_tags)
addTagToSettingsTable(tag);
for (int i = 0; i < 10; ++i)
addTagToSettingsTable();
auto header = ui->tableWidget->horizontalHeader();
header->setSectionResizeMode(tagsTableColumns::name, QHeaderView::Stretch);
header->setSectionResizeMode(tagsTableColumns::styleSheet, QHeaderView::Stretch);
header->setSectionResizeMode(tagsTableColumns::match, QHeaderView::Stretch);
setFixedColumnSize(ui->tableWidget, tagsTableColumns::color);
setFixedColumnSize(ui->tableWidget, tagsTableColumns::icon);
setFixedColumnSize(ui->tableWidget, tagsTableColumns::lock);
connect( ui->tableWidget, &QTableWidget::itemChanged,
this, &ItemTagsLoader::onTableWidgetItemChanged );
return w;
}
ItemWidget *ItemTagsLoader::transform(ItemWidget *itemWidget, const QVariantMap &data)
{
const Tags tags = toTags(::tags(data));
if ( tags.isEmpty() )
return nullptr;
itemWidget->setTagged(true);
return new ItemTags(itemWidget, tags);
}
ItemSaverPtr ItemTagsLoader::transformSaver(const ItemSaverPtr &saver, QAbstractItemModel *)
{
// Avoid checking for locked items if no locked tags are specified in configuration.
const bool hasAnyLocks = std::any_of(
std::begin(m_tags), std::end(m_tags),
[](const ItemTags::Tag &tag){ return tag.lock; });
return hasAnyLocks ? std::make_shared<ItemTagsSaver>(m_tags, saver) : saver;
}
bool ItemTagsLoader::matches(const QModelIndex &index, const ItemFilter &filter) const
{
const QByteArray tagsData =
index.data(contentType::data).toMap().value(mimeTags).toByteArray();
const auto tags = getTextData(tagsData);
return filter.matches(tags) || filter.matches(accentsRemoved(tags));
}
QObject *ItemTagsLoader::tests(const TestInterfacePtr &test) const
{
#ifdef HAS_TESTS
QStringList tags;
for (const auto &tagName : ItemTagsTests::testTags()) {
Tag tag;
tag.name = tagName;
tags.append(serializeTag(tag));
}
QVariantMap settings;
settings[configTags] = tags;
QObject *tests = new ItemTagsTests(test);
tests->setProperty("CopyQ_test_settings", settings);
return tests;
#else
Q_UNUSED(test)
return nullptr;
#endif
}
ItemScriptable *ItemTagsLoader::scriptableObject()
{
return new ItemTagsScriptable(userTags());
}
QVector<Command> ItemTagsLoader::commands() const
{
QVector<Command> commands;
if (m_tags.isEmpty()) {
addTagCommands(tr("Important", "Tag name for example command"), QString(), &commands);
} else {
const QRegularExpression reCapture(R"(\(.*\))");
const QRegularExpression reGroup(R"(\\\d)");
for (const auto &tag : m_tags) {
if ( reCapture.match(tag.match).hasMatch() && reGroup.match(tag.name).hasMatch() )
continue;
addTagCommands(tag.name, tag.match, &commands);
}
}
Command c;
c = dummyTagCommand();
c.internalId = QStringLiteral("copyq_tags_tag");
c.name = addTagText();
c.cmd = "copyq: plugins.itemtags.tag()";
commands.append(c);
c = dummyTagCommand();
c.internalId = QStringLiteral("copyq_tags_untag");
c.input = mimeTags;
c.name = removeTagText();
c.cmd = "copyq: plugins.itemtags.untag()";
commands.append(c);
c = dummyTagCommand();
c.internalId = QStringLiteral("copyq_tags_clear");
c.input = mimeTags;
c.name = tr("Clear all tags");
c.cmd = "copyq: plugins.itemtags.clearTags()";
commands.append(c);
return commands;
}
QStringList ItemTagsLoader::userTags() const
{
QStringList tags;
tags.reserve( m_tags.size() );
for (const auto &tag : m_tags)
tags.append(tag.name);
return tags;
}
void ItemTagsLoader::onColorButtonClicked()
{
QPushButton *button = qobject_cast<QPushButton*>(sender());
Q_ASSERT(button);
const QColor color = button->property(propertyColor).value<QColor>();
QColorDialog dialog(button->window());
dialog.setOptions(dialog.options() | QColorDialog::ShowAlphaChannel | QColorDialog::DontUseNativeDialog);
dialog.setCurrentColor(color);
if ( dialog.exec() == QDialog::Accepted )
setColorIcon( button, dialog.selectedColor() );
onAllTableWidgetItemsChanged();
}
void ItemTagsLoader::onTableWidgetItemChanged(QTableWidgetItem *item)
{
// Omit calling this recursively.
if (m_blockDataChange)
return;
m_blockDataChange = true;
const int row = item->row();
QTableWidgetItem *tagItem = ui->tableWidget->item(row, tagsTableColumns::name);
const QVariant value = QVariant::fromValue(tagFromTable(row));
tagItem->setData(TagTableWidgetItem::TagRole, value);
m_blockDataChange = false;
}
void ItemTagsLoader::onAllTableWidgetItemsChanged()
{
for (int row = 0; row < ui->tableWidget->rowCount(); ++row)
onTableWidgetItemChanged(ui->tableWidget->item(row, 0));
}
QString ItemTagsLoader::serializeTag(const ItemTagsLoader::Tag &tag)
{
return escapeTagField(tag.name)
+ ";;" + escapeTagField(tag.color)
+ ";;" + escapeTagField(tag.icon)
+ ";;" + escapeTagField(tag.styleSheet)
+ ";;" + escapeTagField(tag.match)
+ ";;" + (tag.lock ? "L" : "");
}
ItemTagsLoader::Tag ItemTagsLoader::deserializeTag(const QString &tagText)
{
QStringList tagFields = tagText.split(";;");
Tag tag;
tag.name = unescapeTagField(tagFields.value(0));
tag.color = unescapeTagField(tagFields.value(1));
tag.icon = unescapeTagField(tagFields.value(2));
tag.styleSheet = unescapeTagField(tagFields.value(3));
tag.match = unescapeTagField(tagFields.value(4));
tag.lock = unescapeTagField(tagFields.value(5)) == QLatin1String("L");
return tag;
}
ItemTagsLoader::Tags ItemTagsLoader::toTags(const QStringList &tagList)
{
Tags tags;
for (const auto &tagText : tagList) {
QString tagName = tagText.trimmed();
Tag tag = findMatchingTag(tagName, m_tags);
if (isTagValid(tag)) {
if (tag.match.isEmpty()) {
tag.name = tagName;
} else {
const QRegularExpression re(tag.match);
tag.name = QString(tagName).replace(re, tag.name);
}
} else {
tag.name = tagName;
// Get default tag style from theme.
const QSettings settings;
tag.color = settings.value("Theme/num_fg").toString();
}
tags.append(tag);
}
return tags;
}
void ItemTagsLoader::addTagToSettingsTable(const ItemTagsLoader::Tag &tag)
{
QTableWidget *t = ui->tableWidget;
const int row = t->rowCount();
t->insertRow(row);
t->setItem( row, tagsTableColumns::name, new TagTableWidgetItem(tag.name) );
t->setItem( row, tagsTableColumns::match, new QTableWidgetItem(tag.match) );
t->setItem( row, tagsTableColumns::styleSheet, new QTableWidgetItem(tag.styleSheet) );
t->setItem( row, tagsTableColumns::color, new QTableWidgetItem() );
t->setItem( row, tagsTableColumns::icon, new QTableWidgetItem() );
auto lock = new QTableWidgetItem();
lock->setCheckState(tag.lock ? Qt::Checked : Qt::Unchecked);
const QString toolTip = t->horizontalHeaderItem(tagsTableColumns::lock)->toolTip();
lock->setToolTip(toolTip);
t->setItem( row, tagsTableColumns::lock, lock );
auto colorButton = new QPushButton(t);
const QColor color = tag.color.isEmpty()
? QColor::fromRgb(50, 50, 50)
: deserializeColor(tag.color);
setColorIcon(colorButton, color);
t->setCellWidget(row, tagsTableColumns::color, colorButton);
connect(colorButton, &QAbstractButton::clicked, this, &ItemTagsLoader::onColorButtonClicked);
auto iconButton = new IconSelectButton(t);
iconButton->setCurrentIcon(tag.icon);
t->setCellWidget(row, tagsTableColumns::icon, iconButton);
connect(iconButton, &IconSelectButton::currentIconChanged, this, &ItemTagsLoader::onAllTableWidgetItemsChanged);
onTableWidgetItemChanged(t->item(row, 0));
}
ItemTagsLoader::Tag ItemTagsLoader::tagFromTable(int row)
{
QTableWidget *t = ui->tableWidget;
Tag tag;
tag.name = t->item(row, tagsTableColumns::name)->text();
const QColor color =
cellWidgetProperty(t, row, tagsTableColumns::color, propertyColor).value<QColor>();
tag.color = serializeColor(color);
tag.icon = cellWidgetProperty(t, row, tagsTableColumns::icon, "currentIcon").toString();
tag.styleSheet = t->item(row, tagsTableColumns::styleSheet)->text();
tag.match = t->item(row, tagsTableColumns::match)->text();
tag.lock = t->item(row, tagsTableColumns::lock)->checkState() == Qt::Checked;
return tag;
}
| 26,003
|
C++
|
.cpp
| 761
| 28.256242
| 116
| 0.657267
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,111
|
itemtagstests.cpp
|
hluk_CopyQ/plugins/itemtags/tests/itemtagstests.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemtagstests.h"
#include "tests/test_utils.h"
namespace {
QString testTag(int i)
{
return "TAG_&" + QString::number(i);
}
} // namespace
ItemTagsTests::ItemTagsTests(const TestInterfacePtr &test, QObject *parent)
: QObject(parent)
, m_test(test)
{
}
QStringList ItemTagsTests::testTags()
{
return QStringList()
<< testTag(1)
<< testTag(2)
<< testTag(3)
<< testTag(4)
<< testTag(5);
}
void ItemTagsTests::initTestCase()
{
TEST(m_test->initTestCase());
}
void ItemTagsTests::cleanupTestCase()
{
TEST(m_test->cleanupTestCase());
}
void ItemTagsTests::init()
{
TEST(m_test->init());
}
void ItemTagsTests::cleanup()
{
TEST( m_test->cleanup() );
}
void ItemTagsTests::userTags()
{
RUN("-e" << "plugins.itemtags.userTags",
QString(testTags().join("\n") + "\n").toUtf8());
}
void ItemTagsTests::tag()
{
const QString tab1 = testTab(1);
const Args args = Args() << "tab" << tab1;
RUN(args << "-e" << "plugins.itemtags.tags(0)", "");
RUN(args << "add" << "A" << "B" << "C", "");
RUN(args << "-e" << "plugins.itemtags.tags(0)", "");
RUN(args << "-e" << "plugins.itemtags.tags(1)", "");
RUN(args << "-e" << "plugins.itemtags.tags(2)", "");
RUN(args << "-e" << "plugins.itemtags.tags(3)", "");
RUN(args << "size", "3\n");
RUN(args << "-e" << "plugins.itemtags.tag('x', 0)", "");
RUN(args << "-e" << "plugins.itemtags.tags(0)", "x\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('x', 0)", "true\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('y', 0)", "false\n");
RUN(args << "-e" << "plugins.itemtags.tags(1)", "");
RUN(args << "-e" << "plugins.itemtags.hasTag('x', 1)", "false\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('y', 1)", "false\n");
RUN(args << "-e" << "plugins.itemtags.tags(2)", "");
RUN(args << "-e" << "plugins.itemtags.hasTag('x', 2)", "false\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('y', 2)", "false\n");
RUN(args << "-e" << "plugins.itemtags.tags(3)", "");
RUN(args << "-e" << "plugins.itemtags.hasTag('x', 3)", "false\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('y', 3)", "false\n");
RUN(args << "size", "3\n");
RUN(args << "-e" << "plugins.itemtags.tag('y', 0, 1)", "");
RUN(args << "-e" << "plugins.itemtags.tags(0)", "x\ny\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('x', 0)", "true\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('y', 0)", "true\n");
RUN(args << "-e" << "plugins.itemtags.tags(1)", "y\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('x', 1)", "false\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('y', 1)", "true\n");
RUN(args << "-e" << "plugins.itemtags.tags(2)", "");
RUN(args << "-e" << "plugins.itemtags.hasTag('x', 2)", "false\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('y', 2)", "false\n");
RUN(args << "-e" << "plugins.itemtags.tags(3)", "");
RUN(args << "-e" << "plugins.itemtags.hasTag('x', 3)", "false\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('y', 3)", "false\n");
RUN(args << "size", "3\n");
RUN(args << "-e" << "plugins.itemtags.tag('z', 2, 3, 4)", "");
RUN(args << "-e" << "plugins.itemtags.tags(0)", "x\ny\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('x', 0)", "true\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('y', 0)", "true\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('z', 0)", "false\n");
RUN(args << "-e" << "plugins.itemtags.tags(1)", "y\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('x', 1)", "false\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('y', 1)", "true\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('z', 1)", "false\n");
RUN(args << "-e" << "plugins.itemtags.tags(2)", "z\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('x', 2)", "false\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('y', 2)", "false\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('z', 2)", "true\n");
RUN(args << "-e" << "plugins.itemtags.tags(3)", "");
RUN(args << "-e" << "plugins.itemtags.hasTag('x', 3)", "false\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('y', 3)", "false\n");
RUN(args << "-e" << "plugins.itemtags.hasTag('z', 3)", "false\n");
RUN(args << "size", "3\n");
}
void ItemTagsTests::untag()
{
const QString tab1 = testTab(1);
const Args args = Args() << "tab" << tab1;
RUN(args << "-e" << "plugins.itemtags.tags(0)", "");
RUN(args << "add" << "A" << "B" << "C", "");
RUN(args << "-e" << "plugins.itemtags.tag('x', 0, 1)", "");
RUN(args << "-e" << "plugins.itemtags.tag('y', 1, 2)", "");
RUN(args << "-e" << "plugins.itemtags.tags(0)", "x\n");
RUN(args << "-e" << "plugins.itemtags.tags(1)", "x\ny\n");
RUN(args << "-e" << "plugins.itemtags.tags(2)", "y\n");
RUN(args << "-e" << "plugins.itemtags.untag('x', 1)", "");
RUN(args << "-e" << "plugins.itemtags.tags(0)", "x\n");
RUN(args << "-e" << "plugins.itemtags.tags(1)", "y\n");
RUN(args << "-e" << "plugins.itemtags.tags(2)", "y\n");
RUN(args << "-e" << "plugins.itemtags.untag('y', 1, 2)", "");
RUN(args << "-e" << "plugins.itemtags.tags(0)", "x\n");
RUN(args << "-e" << "plugins.itemtags.tags(1)", "");
RUN(args << "-e" << "plugins.itemtags.tags(2)", "");
}
void ItemTagsTests::clearTags()
{
const QString tab1 = testTab(1);
const Args args = Args() << "tab" << tab1;
RUN(args << "-e" << "plugins.itemtags.tags(0)", "");
RUN(args << "add" << "A" << "B" << "C", "");
RUN(args << "-e" << "plugins.itemtags.tag('x', 0, 1)", "");
RUN(args << "-e" << "plugins.itemtags.tag('y', 1, 2)", "");
RUN(args << "-e" << "plugins.itemtags.tags(0)", "x\n");
RUN(args << "-e" << "plugins.itemtags.tags(1)", "x\ny\n");
RUN(args << "-e" << "plugins.itemtags.tags(2)", "y\n");
RUN(args << "-e" << "plugins.itemtags.clearTags(1)", "");
RUN(args << "-e" << "plugins.itemtags.tags(0)", "x\n");
RUN(args << "-e" << "plugins.itemtags.tags(1)", "");
RUN(args << "-e" << "plugins.itemtags.tags(2)", "y\n");
RUN(args << "-e" << "plugins.itemtags.tag('a', 1, 2)", "");
RUN(args << "-e" << "plugins.itemtags.tags(0)", "x\n");
RUN(args << "-e" << "plugins.itemtags.tags(1)", "a\n");
RUN(args << "-e" << "plugins.itemtags.tags(2)", "a\ny\n");
RUN(args << "-e" << "plugins.itemtags.clearTags(0, 2)", "");
RUN(args << "-e" << "plugins.itemtags.tags(0)", "");
RUN(args << "-e" << "plugins.itemtags.tags(1)", "a\n");
RUN(args << "-e" << "plugins.itemtags.tags(2)", "");
}
void ItemTagsTests::searchTags()
{
const QString tab1 = testTab(1);
const Args args = Args() << "tab" << tab1;
RUN(args << "-e" << "plugins.itemtags.tags(0)", "");
RUN(args << "add" << "A" << "B" << "C", "");
RUN(args << "-e" << "plugins.itemtags.tag('tag1', 0, 1)", "");
RUN(args << "-e" << "plugins.itemtags.tag('tag2', 1, 2)", "");
RUN(args << "-e" << "plugins.itemtags.tag('tag3', 2)", "");
RUN(args << "-e" << "plugins.itemtags.tags(0)", "tag1\n");
RUN(args << "-e" << "plugins.itemtags.tags(1)", "tag1\ntag2\n");
RUN(args << "-e" << "plugins.itemtags.tags(2)", "tag2\ntag3\n");
RUN(args << "keys" << "RIGHT", "");
RUN(args << "keys" << "t" << "a" << "g" << "1", "");
RUN(args << "keys" << "TAB" << "CTRL+A", "");
RUN(args << "testSelected", tab1 + " 0 0 1\n");
RUN(args << "keys" << "ESCAPE", "");
RUN(args << "keys" << "t" << "a" << "g" << "2", "");
RUN(args << "keys" << "TAB" << "CTRL+A", "");
RUN(args << "testSelected", tab1 + " 1 1 2\n");
RUN(args << "keys" << "ESCAPE", "");
RUN(args << "keys" << "t" << "a" << "g" << "3", "");
RUN(args << "keys" << "TAB" << "CTRL+A", "");
RUN(args << "testSelected", tab1 + " 2 2\n");
}
void ItemTagsTests::tagSelected()
{
const auto script = R"(
setCommands([{
name: 'Add Tag x',
inMenu: true,
shortcuts: ['Ctrl+F1'],
cmd: 'copyq: plugins.itemtags.tag("x")'
},
{
name: 'Add Tag y',
inMenu: true,
shortcuts: ['Ctrl+F2'],
cmd: 'copyq: plugins.itemtags.tag("y")'
}])
)";
RUN(script, "");
RUN("add" << "A" << "B" << "C", "");
RUN("keys" << "CTRL+F1", "");
WAIT_ON_OUTPUT("plugins.itemtags.tags(0)", "x\n");
RUN("plugins.itemtags.tags(1)", "");
RUN("plugins.itemtags.tags(2)", "");
RUN("selectItems(0,1)", "true\n");
RUN("keys" << "CTRL+F2", "");
WAIT_ON_OUTPUT("plugins.itemtags.tags(0)", "x\ny\n");
RUN("plugins.itemtags.tags(1)", "y\n");
RUN("plugins.itemtags.tags(2)", "");
}
void ItemTagsTests::untagSelected()
{
const auto script = R"(
setCommands([{
name: 'Remove Tag x',
inMenu: true,
shortcuts: ['Ctrl+F1'],
cmd: 'copyq: plugins.itemtags.untag("x")'
}])
)";
RUN(script, "");
RUN("add" << "A" << "B" << "C", "");
RUN("plugins.itemtags.tag('x', 0, 2)", "");
RUN("plugins.itemtags.tag('y', 1, 2)", "");
RUN("plugins.itemtags.tags(0)", "x\n");
RUN("selectItems(0,1,2)", "true\n");
RUN("keys" << "CTRL+F1", "");
WAIT_ON_OUTPUT("plugins.itemtags.tags(0)", "");
RUN("plugins.itemtags.tags(1)", "y\n");
RUN("plugins.itemtags.tags(2)", "y\n");
}
| 9,478
|
C++
|
.cpp
| 220
| 37.977273
| 75
| 0.512629
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,112
|
itemencrypted.cpp
|
hluk_CopyQ/plugins/itemencrypted/itemencrypted.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemencrypted.h"
#include "ui_itemencryptedsettings.h"
#include "common/command.h"
#include "common/config.h"
#include "common/contenttype.h"
#include "common/log.h"
#include "common/mimetypes.h"
#include "common/shortcuts.h"
#include "common/processsignals.h"
#include "common/textdata.h"
#include "gui/icons.h"
#include "gui/iconwidget.h"
#include "item/serialize.h"
#ifdef HAS_TESTS
# include "tests/itemencryptedtests.h"
#endif
#include <QAbstractItemModel>
#include <QDir>
#include <QIODevice>
#include <QLabel>
#include <QModelIndex>
#include <QSettings>
#include <QTextEdit>
#include <QtPlugin>
#include <QVBoxLayout>
#include <QVariantMap>
namespace {
const QLatin1String mimeEncryptedData("application/x-copyq-encrypted");
const QLatin1String dataFileHeader("CopyQ_encrypted_tab");
const QLatin1String dataFileHeaderV2("CopyQ_encrypted_tab v2");
const QLatin1String configEncryptTabs("encrypt_tabs");
const int maxItemCount = 100'000;
bool waitOrTerminate(QProcess *p, int timeoutMs)
{
p->waitForStarted();
if ( p->state() != QProcess::NotRunning && !p->waitForFinished(timeoutMs) ) {
p->terminate();
if ( !p->waitForFinished(5000) )
p->kill();
return false;
}
return true;
}
bool verifyProcess(QProcess *p, int timeoutMs = 30000)
{
if ( !waitOrTerminate(p, timeoutMs) ) {
log( QStringLiteral("ItemEncrypt: Process timed out; stderr: %1")
.arg(QString::fromUtf8(p->readAllStandardError())), LogError );
return false;
}
const int exitCode = p->exitCode();
if ( p->exitStatus() != QProcess::NormalExit ) {
log( QStringLiteral("ItemEncrypt: Failed to run GnuPG: %1")
.arg(p->errorString()), LogError );
return false;
}
if (exitCode != 0) {
if (const QString errors = p->readAllStandardError(); !errors.isEmpty()) {
log( QStringLiteral("ItemEncrypt: GnuPG stderr:\n%1")
.arg(errors), LogError );
}
return false;
}
return true;
}
QString getGpgVersionOutput(const QString &executable) {
QProcess p;
p.start(executable, QStringList("--version"), QIODevice::ReadWrite);
p.closeReadChannel(QProcess::StandardError);
if ( !verifyProcess(&p, 5000) )
return QString();
return p.readAllStandardOutput();
}
struct GpgVersion {
int major;
int minor;
};
GpgVersion parseVersion(const QString &versionOutput)
{
const int lineEndIndex = versionOutput.indexOf('\n');
#if QT_VERSION < QT_VERSION_CHECK(5,15,2)
const QStringRef firstLine = versionOutput.midRef(0, lineEndIndex);
#else
const auto firstLine = QStringView{versionOutput}.mid(0, lineEndIndex);
#endif
const QRegularExpression versionRegex(QStringLiteral(R"( (\d+)\.(\d+))"));
const QRegularExpressionMatch match = versionRegex.match(firstLine);
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
const int major = match.hasMatch() ? match.capturedView(1).toInt() : 0;
const int minor = match.hasMatch() ? match.capturedView(2).toInt() : 0;
#else
const int major = match.hasMatch() ? match.capturedRef(1).toInt() : 0;
const int minor = match.hasMatch() ? match.capturedRef(2).toInt() : 0;
#endif
return GpgVersion{major, minor};
}
class GpgExecutable {
public:
GpgExecutable() = default;
explicit GpgExecutable(const QString &executable)
: m_executable(executable)
{
const auto versionOutput = getGpgVersionOutput(executable);
if ( !versionOutput.isEmpty() ) {
COPYQ_LOG_VERBOSE(
QStringLiteral("ItemEncrypt INFO: '%1 --version' output: %2")
.arg(executable, versionOutput) );
const GpgVersion version = parseVersion(versionOutput);
m_isSupported = version.major >= 2;
COPYQ_LOG( QStringLiteral("ItemEncrypt INFO: %1 gpg version: %2.%3")
.arg(m_isSupported ? "Supported" : "Unsupported")
.arg(version.major)
.arg(version.minor) );
const bool needsSecring = version.major == 2 && version.minor == 0;
const QString path = getConfigurationFilePath("");
m_pubring = path + ".pub";
m_pubringNative = QDir::toNativeSeparators(m_pubring);
if (needsSecring) {
m_secring = path + ".sec";
m_secringNative = QDir::toNativeSeparators(m_secring);
}
#ifdef Q_OS_WIN
const bool isUnixGpg = versionOutput.contains("Home: /c/");
if (isUnixGpg) {
m_pubringNative = QString(m_pubring).replace(":", "").insert(0, '/');
if (needsSecring)
m_secringNative = QString(m_secring).replace(":", "").insert(0, '/');
}
#endif
}
}
const QString &executable() const { return m_executable; }
bool isSupported() const { return m_isSupported; }
bool needsSecring() const { return !m_secring.isEmpty(); }
const QString &pubring() const { return m_pubring; }
const QString &secring() const { return m_secring; }
const QString &pubringNative() const { return m_pubringNative; }
const QString &secringNative() const { return m_secringNative; }
private:
QString m_executable;
QString m_pubring;
QString m_secring;
QString m_pubringNative;
QString m_secringNative;
bool m_isSupported = false;
};
GpgExecutable findGpgExecutable()
{
for (const auto &executable : {"gpg2", "gpg"}) {
GpgExecutable gpg(executable);
if ( gpg.isSupported() )
return gpg;
}
return GpgExecutable();
}
const GpgExecutable &gpgExecutable()
{
static const auto gpg = findGpgExecutable();
return gpg;
}
QStringList getDefaultEncryptCommandArguments(const QString &publicKeyPath)
{
return QStringList() << "--trust-model" << "always" << "--recipient" << "copyq"
<< "--charset" << "utf-8" << "--display-charset" << "utf-8" << "--no-tty"
<< "--no-default-keyring" << "--keyring" << publicKeyPath;
}
void startGpgProcess(QProcess *p, const QStringList &args, QIODevice::OpenModeFlag mode)
{
const auto &gpg = gpgExecutable();
p->start(gpg.executable(), getDefaultEncryptCommandArguments(gpg.pubringNative()) + args, mode);
}
QString importGpgKey()
{
const auto &gpg = gpgExecutable();
if ( !gpg.needsSecring() )
return QString();
QProcess p;
p.start(gpg.executable(), getDefaultEncryptCommandArguments(gpg.pubringNative()) << "--import" << gpg.secringNative());
if ( !verifyProcess(&p) )
return "Failed to import private key (see log).";
return QString();
}
QString exportGpgKey()
{
const auto &gpg = gpgExecutable();
if ( !gpg.needsSecring() )
return QString();
// Private key already created or exported.
if ( QFile::exists(gpg.secring()) )
return QString();
QProcess p;
p.start(gpg.executable(), getDefaultEncryptCommandArguments(gpg.pubringNative()) << "--export-secret-key" << gpg.secringNative());
if ( !verifyProcess(&p) )
return "Failed to export private key (see log).";
QFile secKey(gpg.secring());
if ( !secKey.open(QIODevice::WriteOnly) )
return "Failed to create private key.";
if ( !secKey.setPermissions(QFile::ReadOwner | QFile::WriteOwner) )
return "Failed to set permissions for private key.";
const QByteArray secKeyData = p.readAllStandardOutput();
secKey.write(secKeyData);
secKey.close();
return QString();
}
QByteArray readGpgOutput(const QStringList &args, const QByteArray &input = QByteArray())
{
QProcess p;
startGpgProcess(&p, args, QIODevice::ReadWrite);
p.write(input);
p.closeWriteChannel();
p.waitForFinished();
verifyProcess(&p);
return p.readAllStandardOutput();
}
bool keysExist()
{
return !readGpgOutput( QStringList("--list-keys") ).isEmpty();
}
bool decryptMimeData(QVariantMap *data)
{
const QByteArray encryptedBytes = data->take(mimeEncryptedData).toByteArray();
const QByteArray bytes = readGpgOutput( QStringList() << "--decrypt", encryptedBytes );
if ( bytes.isEmpty() )
return false;
return deserializeData(data, bytes);
}
bool encryptMimeData(const QVariantMap &data, const QModelIndex &index, QAbstractItemModel *model)
{
QVariantMap dataToEncrypt;
QVariantMap dataMap;
for (auto it = data.constBegin(); it != data.constEnd(); ++it) {
if ( it.key().startsWith(COPYQ_MIME_PREFIX) )
dataMap.insert(it.key(), it.value());
else
dataToEncrypt.insert(it.key(), it.value());
}
if ( dataToEncrypt.isEmpty() )
return false;
const QByteArray bytes = serializeData(dataToEncrypt);
const QByteArray encryptedBytes = readGpgOutput( QStringList("--encrypt"), bytes );
if ( encryptedBytes.isEmpty() )
return false;
dataMap.insert(mimeEncryptedData, encryptedBytes);
return model->setData(index, dataMap, contentType::updateData);
}
void startGenerateKeysProcess(QProcess *process, bool useTransientPasswordlessKey = false)
{
const auto &gpg = gpgExecutable();
auto args = QStringList() << "--batch" << "--gen-key";
QByteArray transientOptions;
if (useTransientPasswordlessKey) {
args << "--debug-quick-random";
transientOptions =
"\n%no-protection"
"\n%transient-key";
}
startGpgProcess(process, args, QIODevice::ReadWrite);
process->write(
"\nKey-Type: RSA"
"\nKey-Usage: encrypt"
"\nKey-Length: 4096"
"\nName-Real: copyq"
+ transientOptions +
"\n%pubring " + gpg.pubringNative().toUtf8()
);
if ( gpg.needsSecring() )
process->write("\n%secring " + gpg.secringNative().toUtf8());
process->write("\n%commit\n");
process->closeWriteChannel();
}
QString exportImportGpgKeys()
{
if (const auto error = exportGpgKey(); !error.isEmpty())
return error;
return importGpgKey();
}
bool isGpgInstalled()
{
return gpgExecutable().isSupported();
}
} // namespace
ItemEncrypted::ItemEncrypted(QWidget *parent)
: QWidget(parent)
, ItemWidget(this)
{
auto layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
// Show small icon.
QWidget *iconWidget = new IconWidget(IconLock, this);
layout->addWidget(iconWidget);
}
bool ItemEncryptedSaver::saveItems(const QString &, const QAbstractItemModel &model, QIODevice *file)
{
const auto length = model.rowCount();
QByteArray bytes;
{
QDataStream stream(&bytes, QIODevice::WriteOnly);
stream.setVersion(QDataStream::Qt_4_7);
stream << static_cast<quint64>(length);
for (int i = 0; i < length && stream.status() == QDataStream::Ok; ++i) {
QModelIndex index = model.index(i, 0);
QVariantMap dataMap = index.data(contentType::data).toMap();
for (auto it = dataMap.begin(); it != dataMap.end(); ++it) {
if (it.value().type() != QVariant::ByteArray)
it.value() = it.value().toByteArray();
}
stream << dataMap;
}
}
bytes = readGpgOutput(QStringList("--encrypt"), bytes);
if ( bytes.isEmpty() ) {
emitEncryptFailed();
log("ItemEncrypt: Failed to read encrypted data", LogError);
return false;
}
QDataStream stream(file);
stream.setVersion(QDataStream::Qt_4_7);
stream << QString(dataFileHeaderV2);
stream.writeRawData( bytes.data(), bytes.size() );
if ( stream.status() != QDataStream::Ok ) {
emitEncryptFailed();
log("ItemEncrypt: Failed to write encrypted data", LogError);
return false;
}
return true;
}
void ItemEncryptedSaver::emitEncryptFailed()
{
emit error( ItemEncryptedLoader::tr("Encryption failed!") );
}
bool ItemEncryptedScriptable::isEncrypted()
{
const auto args = currentArguments();
for (const auto &arg : args) {
bool ok;
const int row = arg.toInt(&ok);
if (ok) {
const auto result = call("read", QVariantList() << "?" << row);
if ( result.toByteArray().contains(mimeEncryptedData.data()) )
return true;
}
}
return false;
}
QByteArray ItemEncryptedScriptable::encrypt()
{
const auto args = currentArguments();
const auto bytes = args.value(0).toByteArray();
return encrypt(bytes);
}
QByteArray ItemEncryptedScriptable::decrypt()
{
const auto args = currentArguments();
const auto bytes = args.value(0).toByteArray();
return decrypt(bytes);
}
void ItemEncryptedScriptable::encryptItem()
{
QVariantMap dataMap;
const auto formats = call("dataFormats").toList();
for (const auto &formatValue : formats) {
const auto format = formatValue.toString();
if ( !format.startsWith(COPYQ_MIME_PREFIX) ) {
const auto data = call("data", QVariantList() << format).toByteArray();
dataMap.insert(format, data);
}
}
const auto bytes = call("pack", QVariantList() << dataMap).toByteArray();
const auto encryptedBytes = encrypt(bytes);
if (encryptedBytes.isEmpty())
return;
call("setData", QVariantList() << mimeEncryptedData << encryptedBytes);
for (auto it = dataMap.constBegin(); it != dataMap.constEnd(); ++it)
call("removeData", QVariantList() << it.key());
}
void ItemEncryptedScriptable::decryptItem()
{
const auto encryptedBytes = call("data", QVariantList() << mimeEncryptedData).toByteArray();
const auto itemData = decrypt(encryptedBytes);
if (itemData.isEmpty())
return;
const auto dataMap = call("unpack", QVariantList() << itemData).toMap();
for (auto it = dataMap.constBegin(); it != dataMap.constEnd(); ++it) {
const auto &format = it.key();
call("setData", QVariantList() << format << dataMap[format]);
}
}
void ItemEncryptedScriptable::encryptItems()
{
const auto dataValueList = call("selectedItemsData").toList();
QVariantList dataList;
for (const auto &itemDataValue : dataValueList) {
auto itemData = itemDataValue.toMap();
QVariantMap itemDataToEncrypt;
const auto formats = itemData.keys();
for (const auto &format : formats) {
if ( !format.startsWith(COPYQ_MIME_PREFIX) ) {
itemDataToEncrypt.insert(format, itemData[format]);
itemData.remove(format);
}
}
const auto bytes = call("pack", QVariantList() << itemDataToEncrypt).toByteArray();
const auto encryptedBytes = encrypt(bytes);
if (encryptedBytes.isEmpty())
return;
itemData.insert(mimeEncryptedData, encryptedBytes);
dataList.append(itemData);
}
call( "setSelectedItemsData", QVariantList() << QVariant(dataList) );
}
void ItemEncryptedScriptable::decryptItems()
{
const auto dataValueList = call("selectedItemsData").toList();
QVariantList dataList;
for (const auto &itemDataValue : dataValueList) {
auto itemData = itemDataValue.toMap();
const auto encryptedBytes = itemData.value(mimeEncryptedData).toByteArray();
if ( !encryptedBytes.isEmpty() ) {
itemData.remove(mimeEncryptedData);
const auto decryptedBytes = decrypt(encryptedBytes);
if (decryptedBytes.isEmpty())
return;
const auto decryptedItemData = call("unpack", QVariantList() << decryptedBytes).toMap();
for (auto it = decryptedItemData.constBegin(); it != decryptedItemData.constEnd(); ++it)
itemData.insert(it.key(), it.value());
}
dataList.append(itemData);
}
call( "setSelectedItemsData", QVariantList() << QVariant(dataList) );
}
void ItemEncryptedScriptable::copyEncryptedItems()
{
const auto dataValueList = call("selectedItemsData").toList();
QString text;
for (const auto &dataValue : dataValueList) {
if ( !text.isEmpty() )
text.append('\n');
const auto data = dataValue.toMap();
const auto itemTextValue = data.value(mimeText);
if ( itemTextValue.isValid() ) {
text.append( getTextData(itemTextValue.toByteArray()) );
} else {
const auto encryptedBytes = data.value(mimeEncryptedData).toByteArray();
if ( !encryptedBytes.isEmpty() ) {
const auto itemData = decrypt(encryptedBytes);
if (itemData.isEmpty())
return;
const auto dataMap = call("unpack", QVariantList() << itemData).toMap();
text.append( getTextData(dataMap) );
}
}
}
const auto args = QVariantList()
<< mimeText << text
<< mimeHidden << "1";
call("copy", args);
call("copySelection", args);
}
void ItemEncryptedScriptable::pasteEncryptedItems()
{
copyEncryptedItems();
const auto script =
R"(
if (focused()) {
hide();
sleep(100);
}
paste();
sleep(2000);
copy('');
copySelection('');
)";
call("eval", QVariantList() << script);
}
QString ItemEncryptedScriptable::generateTestKeys()
{
const auto &gpg = gpgExecutable();
const QStringList keys = gpg.needsSecring()
? QStringList{gpg.pubring(), gpg.secring()}
: QStringList{gpg.pubring()};
for (const auto &keyFileName : keys) {
if ( QFile::exists(keyFileName) && !QFile::remove(keyFileName) )
return QString("Failed to remove \"%1\"").arg(keyFileName);
}
QProcess process;
startGenerateKeysProcess(&process, true);
if ( !verifyProcess(&process) ) {
return QString("ItemEncrypt: %1; stderr: %2")
.arg( process.errorString(),
QString::fromUtf8(process.readAllStandardError()) );
}
if ( const auto error = exportImportGpgKeys(); !error.isEmpty() )
return error;
for (const auto &keyFileName : keys) {
if ( !QFile::exists(keyFileName) )
return QString("Failed to create \"%1\"").arg(keyFileName);
}
return QString();
}
bool ItemEncryptedScriptable::isGpgInstalled()
{
return ::isGpgInstalled();
}
QByteArray ItemEncryptedScriptable::encrypt(const QByteArray &bytes)
{
const auto encryptedBytes = readGpgOutput(QStringList("--encrypt"), bytes);
if ( encryptedBytes.isEmpty() )
throwError("Failed to execute GPG!");
return encryptedBytes;
}
QByteArray ItemEncryptedScriptable::decrypt(const QByteArray &bytes)
{
importGpgKey();
const auto decryptedBytes = readGpgOutput(QStringList("--decrypt"), bytes);
if ( decryptedBytes.isEmpty() )
throwError("Failed to execute GPG!");
return decryptedBytes;
}
ItemEncryptedLoader::ItemEncryptedLoader()
: ui()
, m_gpgProcessStatus(GpgCheckIfInstalled)
, m_gpgProcess(nullptr)
{
}
ItemEncryptedLoader::~ItemEncryptedLoader()
{
terminateGpgProcess();
}
ItemWidget *ItemEncryptedLoader::create(const QVariantMap &data, QWidget *parent, bool) const
{
if ( data.value(mimeHidden).toBool() )
return nullptr;
return data.contains(mimeEncryptedData) ? new ItemEncrypted(parent) : nullptr;
}
QStringList ItemEncryptedLoader::formatsToSave() const
{
return QStringList(mimeEncryptedData);
}
void ItemEncryptedLoader::applySettings(QSettings &settings)
{
Q_ASSERT(ui != nullptr);
settings.setValue( configEncryptTabs, ui->plainTextEditEncryptTabs->toPlainText().split('\n') );
}
void ItemEncryptedLoader::loadSettings(const QSettings &settings)
{
m_encryptTabs = settings.value(configEncryptTabs).toStringList();
}
QWidget *ItemEncryptedLoader::createSettingsWidget(QWidget *parent)
{
ui.reset(new Ui::ItemEncryptedSettings);
QWidget *w = new QWidget(parent);
ui->setupUi(w);
ui->plainTextEditEncryptTabs->setPlainText(
m_encryptTabs.join('\n') );
if (status() != GpgNotInstalled) {
const auto &gpg = gpgExecutable();
ui->labelShareInfo->setTextFormat(Qt::RichText);
QString text = ItemEncryptedLoader::tr(
"To share encrypted items on other computer or"
" session, you'll need these secret key files (keep them in a safe place):"
);
if (gpg.needsSecring()) {
text.append( QStringLiteral(
"<ul>"
"<li>%1</li>"
"<li>%2</li>"
"</ul>"
).arg(quoteString(gpg.pubringNative()), quoteString(gpg.secringNative()))
);
} else {
text.append( QStringLiteral(
"<ul>"
"<li>%1</li>"
"</ul>"
).arg(quoteString(gpg.pubringNative()))
);
}
ui->labelShareInfo->setText(text);
}
updateUi();
connect( ui->pushButtonPassword, &QAbstractButton::clicked,
this, &ItemEncryptedLoader::setPassword );
return w;
}
bool ItemEncryptedLoader::canLoadItems(QIODevice *file) const
{
QDataStream stream(file);
stream.setVersion(QDataStream::Qt_4_7);
QString header;
stream >> header;
return stream.status() == QDataStream::Ok
&& (header == dataFileHeader || header == dataFileHeaderV2);
}
bool ItemEncryptedLoader::canSaveItems(const QString &tabName) const
{
for (const auto &encryptTabName : m_encryptTabs) {
if ( encryptTabName.isEmpty() )
continue;
QString tabName1 = tabName;
// Ignore ampersands (usually just for underlining mnemonics) if none is specified.
if ( !hasKeyHint(encryptTabName) )
removeKeyHint(&tabName1);
// Ignore path in tab tree if none path separator is specified.
if ( !encryptTabName.contains('/') ) {
const int i = tabName1.lastIndexOf('/');
tabName1.remove(0, i + 1);
}
if ( tabName1 == encryptTabName )
return true;
}
return false;
}
ItemSaverPtr ItemEncryptedLoader::loadItems(const QString &, QAbstractItemModel *model, QIODevice *file, int maxItems)
{
// This is needed to skip header.
if ( !canLoadItems(file) )
return nullptr;
if (status() == GpgNotInstalled) {
emit error( ItemEncryptedLoader::tr("GnuPG must be installed to view encrypted tabs.") );
return nullptr;
}
importGpgKey();
QProcess p;
startGpgProcess( &p, QStringList("--decrypt"), QIODevice::ReadWrite );
char encryptedBytes[4096];
QDataStream stream(file);
while ( !stream.atEnd() ) {
const int bytesRead = stream.readRawData(encryptedBytes, 4096);
if (bytesRead == -1) {
emitDecryptFailed();
log("ItemEncrypted: Failed to read encrypted data", LogError);
return nullptr;
}
p.write(encryptedBytes, bytesRead);
}
p.closeWriteChannel();
// Wait for password entry dialog.
p.waitForFinished(-1);
if ( !verifyProcess(&p) ) {
emitDecryptFailed();
return nullptr;
}
const QByteArray bytes = p.readAllStandardOutput();
if ( bytes.isEmpty() ) {
emitDecryptFailed();
log("ItemEncrypt: Failed to read encrypted data", LogError);
verifyProcess(&p);
return nullptr;
}
QDataStream stream2(bytes);
quint64 length;
stream2 >> length;
if ( stream2.status() != QDataStream::Ok ) {
emitDecryptFailed();
log("ItemEncrypt: Failed to parse item count", LogError);
return nullptr;
}
length = qMin(length, static_cast<quint64>(maxItems)) - static_cast<quint64>(model->rowCount());
const auto count = length < maxItemCount ? static_cast<int>(length) : maxItemCount;
for ( int i = 0; i < count && stream2.status() == QDataStream::Ok; ++i ) {
if ( !model->insertRow(i) ) {
emitDecryptFailed();
log("ItemEncrypt: Failed to insert item", LogError);
return nullptr;
}
QVariantMap dataMap;
stream2 >> dataMap;
model->setData( model->index(i, 0), dataMap, contentType::data );
}
if ( stream2.status() != QDataStream::Ok ) {
emitDecryptFailed();
log("ItemEncrypt: Failed to decrypt item", LogError);
return nullptr;
}
return createSaver();
}
ItemSaverPtr ItemEncryptedLoader::initializeTab(const QString &, QAbstractItemModel *, int)
{
if (status() == GpgNotInstalled)
return nullptr;
return createSaver();
}
QObject *ItemEncryptedLoader::tests(const TestInterfacePtr &test) const
{
#ifdef HAS_TESTS
QObject *tests = new ItemEncryptedTests(test);
return tests;
#else
Q_UNUSED(test)
return nullptr;
#endif
}
ItemScriptable *ItemEncryptedLoader::scriptableObject()
{
return new ItemEncryptedScriptable();
}
QVector<Command> ItemEncryptedLoader::commands() const
{
if ( status() == GpgNotInstalled || !keysExist() )
return QVector<Command>();
QVector<Command> commands;
Command c;
c.internalId = QStringLiteral("copyq_encrypted_encrypt");
c.name = ItemEncryptedLoader::tr("Encrypt (needs GnuPG)");
c.icon = QString(QChar(IconLock));
c.input = "!OUTPUT";
c.output = mimeEncryptedData;
c.inMenu = true;
c.cmd = "copyq: plugins.itemencrypted.encryptItems()";
c.shortcuts.append( toPortableShortcutText(ItemEncryptedLoader::tr("Ctrl+L")) );
commands.append(c);
c = Command();
c.internalId = QStringLiteral("copyq_encrypted_decrypt");
c.name = ItemEncryptedLoader::tr("Decrypt");
c.icon = QString(QChar(IconUnlock));
c.input = mimeEncryptedData;
c.output = mimeItems;
c.inMenu = true;
c.cmd = "copyq: plugins.itemencrypted.decryptItems()";
c.shortcuts.append( toPortableShortcutText(ItemEncryptedLoader::tr("Ctrl+L")) );
commands.append(c);
c = Command();
c.internalId = QStringLiteral("copyq_encrypted_decrypt_and_copy");
c.name = ItemEncryptedLoader::tr("Decrypt and Copy");
c.icon = QString(QChar(IconUnlockKeyhole));
c.input = mimeEncryptedData;
c.inMenu = true;
c.cmd = "copyq: plugins.itemencrypted.copyEncryptedItems()";
c.shortcuts.append( toPortableShortcutText(ItemEncryptedLoader::tr("Ctrl+Shift+L")) );
commands.append(c);
c = Command();
c.internalId = QStringLiteral("copyq_encrypted_decrypt_and_paste");
c.name = ItemEncryptedLoader::tr("Decrypt and Paste");
c.icon = QString(QChar(IconUnlockKeyhole));
c.input = mimeEncryptedData;
c.inMenu = true;
c.cmd = "copyq: plugins.itemencrypted.pasteEncryptedItems()";
c.shortcuts.append( toPortableShortcutText(ItemEncryptedLoader::tr("Enter")) );
commands.append(c);
return commands;
}
void ItemEncryptedLoader::setPassword()
{
if (status() != GpgNotRunning)
return;
if ( !keysExist() ) {
m_gpgProcessStatus = GpgGeneratingKeys;
m_gpgProcess = new QProcess(this);
startGenerateKeysProcess(m_gpgProcess);
} else {
// Change password.
m_gpgProcessStatus = GpgChangingPassword;
m_gpgProcess = new QProcess(this);
startGpgProcess( m_gpgProcess, QStringList() << "--edit-key" << "copyq" << "passwd" << "save", QIODevice::ReadOnly );
}
m_gpgProcess->waitForStarted();
if ( m_gpgProcess->state() == QProcess::NotRunning ) {
onGpgProcessFinished( m_gpgProcess->exitCode(), m_gpgProcess->exitStatus() );
} else {
connectProcessFinished(m_gpgProcess, this, &ItemEncryptedLoader::onGpgProcessFinished);
updateUi();
}
}
void ItemEncryptedLoader::terminateGpgProcess()
{
if (m_gpgProcess == nullptr)
return;
QProcess *p = m_gpgProcess;
m_gpgProcess = nullptr;
p->terminate();
p->waitForFinished();
p->deleteLater();
m_gpgProcessStatus = GpgNotRunning;
updateUi();
}
void ItemEncryptedLoader::onGpgProcessFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
QString error;
if (m_gpgProcess != nullptr) {
if (ui != nullptr) {
if (exitStatus != QProcess::NormalExit)
error = m_gpgProcess->errorString();
else if (exitCode != 0)
error = getTextData(m_gpgProcess->readAllStandardError());
else if ( m_gpgProcess->error() != QProcess::UnknownError )
error = m_gpgProcess->errorString();
else if ( !keysExist() )
error = ItemEncryptedLoader::tr("Failed to generate keys.");
}
m_gpgProcess->deleteLater();
m_gpgProcess = nullptr;
}
// Export and import private key to a file in configuration.
if ( status() == GpgGeneratingKeys && error.isEmpty() )
error = exportImportGpgKeys();
if (!error.isEmpty())
error = ItemEncryptedLoader::tr("Error: %1").arg(error);
m_gpgProcessStatus = GpgNotRunning;
updateUi();
ui->labelInfo->setText( error.isEmpty() ? ItemEncryptedLoader::tr("Done") : error );
}
void ItemEncryptedLoader::updateUi()
{
if (ui == nullptr)
return;
if (status() == GpgNotInstalled) {
ui->labelInfo->setText("To use item encryption, install"
" <a href=\"http://www.gnupg.org/\">GnuPG</a>"
" application and restart CopyQ.");
ui->pushButtonPassword->hide();
ui->groupBoxEncryptTabs->hide();
ui->groupBoxShareInfo->hide();
} else if (status() == GpgGeneratingKeys) {
ui->labelInfo->setText( ItemEncryptedLoader::tr("Creating new keys (this may take a few minutes)...") );
ui->pushButtonPassword->setText( ItemEncryptedLoader::tr("Cancel") );
} else if (status() == GpgChangingPassword) {
ui->labelInfo->setText( ItemEncryptedLoader::tr("Setting new password...") );
ui->pushButtonPassword->setText( ItemEncryptedLoader::tr("Cancel") );
} else if ( !keysExist() ) {
ui->labelInfo->setText( ItemEncryptedLoader::tr(
"Encryption keys <strong>must be generated</strong>"
" before item encryption can be used.") );
ui->pushButtonPassword->setText( ItemEncryptedLoader::tr("Generate New Keys...") );
} else {
ui->pushButtonPassword->setText( ItemEncryptedLoader::tr("Change Password...") );
}
}
void ItemEncryptedLoader::emitDecryptFailed()
{
emit error( ItemEncryptedLoader::tr("Decryption failed!") );
}
ItemSaverPtr ItemEncryptedLoader::createSaver()
{
auto saver = std::make_shared<ItemEncryptedSaver>();
connect( saver.get(), &ItemEncryptedSaver::error,
this, &ItemEncryptedLoader::error );
return saver;
}
ItemEncryptedLoader::GpgProcessStatus ItemEncryptedLoader::status() const
{
if (m_gpgProcessStatus == GpgCheckIfInstalled) {
if (isGpgInstalled())
m_gpgProcessStatus = GpgNotRunning;
else
m_gpgProcessStatus = GpgNotInstalled;
}
return m_gpgProcessStatus;
}
bool ItemEncryptedLoader::data(QVariantMap *data, const QModelIndex &) const
{
return !data->contains(mimeEncryptedData) || decryptMimeData(data);
}
bool ItemEncryptedLoader::setData(const QVariantMap &data, const QModelIndex &index, QAbstractItemModel *model) const
{
if ( !index.data(contentType::data).toMap().contains(mimeEncryptedData) )
return false;
return encryptMimeData(data, index, model);
}
| 31,710
|
C++
|
.cpp
| 859
| 30.463329
| 134
| 0.652734
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,113
|
itemencryptedtests.cpp
|
hluk_CopyQ/plugins/itemencrypted/tests/itemencryptedtests.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemencryptedtests.h"
#include "tests/test_utils.h"
ItemEncryptedTests::ItemEncryptedTests(const TestInterfacePtr &test, QObject *parent)
: QObject(parent)
, m_test(test)
{
}
void ItemEncryptedTests::initTestCase()
{
SKIP_ON_ENV("COPYQ_TESTS_SKIP_ITEMENCRYPT");
TEST(m_test->initTestCase());
}
void ItemEncryptedTests::cleanupTestCase()
{
TEST(m_test->cleanupTestCase());
}
void ItemEncryptedTests::init()
{
TEST(m_test->init());
QVERIFY(isGpgInstalled());
}
void ItemEncryptedTests::cleanup()
{
TEST( m_test->cleanup() );
}
void ItemEncryptedTests::encryptDecryptData()
{
RUN("plugins.itemencrypted.generateTestKeys()", "\n");
// Test gpg errors first.
RUN("plugins.itemencrypted.encrypt(input());print('')", "");
const QByteArray input("\x00\x01\x02\x03\x04", 5);
QByteArray stdoutActual;
// Encrypted data differs.
QCOMPARE( m_test->run(Args("-e") << "plugins.itemencrypted.encrypt(input())", &stdoutActual, nullptr, input), 0 );
QVERIFY(!stdoutActual.isEmpty());
QVERIFY(stdoutActual != input);
QCOMPARE( m_test->run(Args("-e") << "plugins.itemencrypted.decrypt(plugins.itemencrypted.encrypt(input()))", &stdoutActual, nullptr, input), 0 );
QCOMPARE(stdoutActual, input);
}
void ItemEncryptedTests::encryptDecryptItems()
{
#ifdef Q_OS_MAC
SKIP("Ctrl+L shortcut doesn't seem work on OS X");
#endif
RUN("plugins.itemencrypted.generateTestKeys()", "\n");
// Load commands from the plugin generating keys.
RUN("keys" << "Ctrl+P" << "ENTER", "");
RUN("commands().length", "4\n");
const auto tab = testTab(1);
RUN("setCurrentTab" << tab, "");
RUN("tab" << tab << "add" << "TEST", "");
RUN("tab" << tab << "read" << "0", "TEST");
// Encrypt.
RUN("keys" << "Ctrl+L", "");
WAIT_ON_OUTPUT("tab" << tab << "read" << "?" << "0", "application/x-copyq-encrypted\n");
// Decrypt and check text.
RUN("keys" << "Ctrl+L", "");
WAIT_ON_OUTPUT("tab" << tab << "read" << "?" << "0", "text/plain\n");
RUN("tab" << tab << "read" << "0", "TEST");
// Encrypt and add note.
RUN("keys" << "Ctrl+L", "");
WAIT_ON_OUTPUT("tab" << tab << "read" << "?" << "0", "application/x-copyq-encrypted\n");
RUN("keys" << "Shift+F2" << ":NOTE" << "F2", "");
RUN("tab" << tab << "read" << "application/x-copyq-item-notes" << "0", "NOTE");
// Decrypt and check note and text.
RUN("keys" << "Ctrl+L", "");
WAIT_ON_OUTPUT("tab" << tab << "read" << "0", "TEST");
RUN("tab" << tab << "read" << "application/x-copyq-item-notes" << "0", "NOTE");
}
bool ItemEncryptedTests::isGpgInstalled() const
{
QByteArray actualStdout;
const auto exitCode = m_test->run(Args("-e") << "plugins.itemencrypted.isGpgInstalled()", &actualStdout);
Q_ASSERT(exitCode == 0);
Q_ASSERT(actualStdout == "true\n" || actualStdout == "false\n");
return actualStdout == "true\n";
}
| 2,982
|
C++
|
.cpp
| 78
| 34.423077
| 149
| 0.628254
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,114
|
itempinned.cpp
|
hluk_CopyQ/plugins/itempinned/itempinned.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itempinned.h"
#include "common/command.h"
#include "common/contenttype.h"
#include "common/display.h"
#ifdef HAS_TESTS
# include "tests/itempinnedtests.h"
#endif
#include <QApplication>
#include <QBoxLayout>
#include <QMessageBox>
#include <QModelIndex>
#include <QPalette>
#include <QPainter>
#include <algorithm>
namespace {
const QLatin1String mimePinned("application/x-copyq-item-pinned");
bool isPinned(const QModelIndex &index)
{
const auto dataMap = index.data(contentType::data).toMap();
return dataMap.contains(mimePinned);
}
Command dummyPinCommand()
{
Command c;
c.icon = QString(QChar(IconThumbtack));
c.inMenu = true;
return c;
}
bool containsPinnedItems(const QModelIndexList &indexList)
{
return std::any_of( std::begin(indexList), std::end(indexList), isPinned );
}
} // namespace
ItemPinned::ItemPinned(ItemWidget *childItem)
: QWidget( childItem->widget()->parentWidget() )
, ItemWidgetWrapper(childItem, this)
{
childItem->widget()->setObjectName("item_child");
childItem->widget()->setParent(this);
QBoxLayout *layout;
layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(childItem->widget());
layout->setAlignment(Qt::AlignTop | Qt::AlignLeft);
}
void ItemPinned::paintEvent(QPaintEvent *paintEvent)
{
const auto *parent = parentWidget();
auto color = parent->palette().color(QPalette::Window);
const int lightThreshold = 100;
const bool menuBackgrounIsLight = color.lightness() > lightThreshold;
color.setHsl(
color.hue(),
color.saturation(),
qMax(0, qMin(255, color.lightness() + (menuBackgrounIsLight ? -200 : 200)))
);
QPainter painter(this);
const int border = pointsToPixels(6, this);
const QRect rect(width() - border, 0, width(), height());
painter.setOpacity(0.15);
painter.fillRect(rect, color);
QWidget::paintEvent(paintEvent);
}
void ItemPinned::updateSize(QSize maximumSize, int idealWidth)
{
setMinimumWidth(idealWidth);
setMaximumWidth(maximumSize.width());
const int border = pointsToPixels(12, this);
const int childItemWidth = idealWidth - border;
const auto childItemMaximumSize = QSize(maximumSize.width() - border, maximumSize.height());
ItemWidgetWrapper::updateSize(childItemMaximumSize, childItemWidth);
adjustSize();
}
bool ItemPinnedScriptable::isPinned()
{
const auto args = currentArguments();
for (const auto &arg : args) {
bool ok;
const int row = arg.toInt(&ok);
if (ok) {
const auto result = call("read", QVariantList() << "?" << row);
if ( result.toByteArray().contains(mimePinned.data()) )
return true;
}
}
return false;
}
void ItemPinnedScriptable::pin()
{
const auto args = currentArguments();
if (args.isEmpty()) {
pinData();
} else {
for (const auto &arg : args) {
bool ok;
const int row = arg.toInt(&ok);
if (ok)
call("change", QVariantList() << row << mimePinned << QString());
}
}
}
void ItemPinnedScriptable::unpin()
{
const auto args = currentArguments();
if (args.isEmpty()) {
unpinData();
} else {
for (const auto &arg : args) {
bool ok;
const int row = arg.toInt(&ok);
if (ok)
call("change", QVariantList() << row << mimePinned << QVariant());
}
}
}
void ItemPinnedScriptable::pinData()
{
call("setData", QVariantList() << mimePinned << QString());
}
void ItemPinnedScriptable::unpinData()
{
call("removeData", QVariantList() << mimePinned);
}
QString ItemPinnedScriptable::getMimePinned() const
{
return ::mimePinned;
}
ItemPinnedSaver::ItemPinnedSaver(QAbstractItemModel *model, const ItemSaverPtr &saver)
: ItemSaverWrapper(saver)
, m_model(model)
{
connect( model, &QAbstractItemModel::rowsInserted,
this, &ItemPinnedSaver::onRowsInserted );
connect( model, &QAbstractItemModel::rowsRemoved,
this, &ItemPinnedSaver::onRowsRemoved );
connect( model, &QAbstractItemModel::rowsMoved,
this, &ItemPinnedSaver::onRowsMoved );
connect( model, &QAbstractItemModel::dataChanged,
this, &ItemPinnedSaver::onDataChanged );
updateLastPinned( 0, m_model->rowCount() );
}
bool ItemPinnedSaver::canRemoveItems(const QList<QModelIndex> &indexList, QString *error)
{
if ( !containsPinnedItems(indexList) )
return ItemSaverWrapper::canRemoveItems(indexList, error);
if (error) {
*error = "Removing pinned item is not allowed (unpin item first)";
return false;
}
QMessageBox::information(
QApplication::activeWindow(),
ItemPinnedLoader::tr("Cannot Remove Pinned Items"),
ItemPinnedLoader::tr("Unpin items first to remove them.") );
return false;
}
bool ItemPinnedSaver::canDropItem(const QModelIndex &index)
{
return !isPinned(index) && ItemSaverWrapper::canDropItem(index);
}
bool ItemPinnedSaver::canMoveItems(const QList<QModelIndex> &indexList)
{
return !containsPinnedItems(indexList)
&& ItemSaverWrapper::canMoveItems(indexList);
}
void ItemPinnedSaver::onRowsInserted(const QModelIndex &, int start, int end)
{
if (!m_model || m_lastPinned < start) {
updateLastPinned(start, end);
return;
}
disconnect( m_model.data(), &QAbstractItemModel::rowsMoved,
this, &ItemPinnedSaver::onRowsMoved );
// Shift rows below inserted up.
const int rowCount = end - start + 1;
for (int row = end + 1; row <= m_lastPinned + rowCount; ++row) {
const auto index = m_model->index(row, 0);
if ( isPinned(index) )
moveRow(row, row - rowCount);
}
connect( m_model.data(), &QAbstractItemModel::rowsMoved,
this, &ItemPinnedSaver::onRowsMoved );
}
void ItemPinnedSaver::onRowsRemoved(const QModelIndex &, int start, int end)
{
if (!m_model || m_lastPinned < start)
return;
disconnect( m_model.data(), &QAbstractItemModel::rowsMoved,
this, &ItemPinnedSaver::onRowsMoved );
// Shift rows below removed down.
const int rowCount = end - start + 1;
for (int row = m_lastPinned - rowCount; row >= start; --row) {
const auto index = m_model->index(row, 0);
if ( isPinned(index) )
moveRow(row, row + rowCount + 1);
}
connect( m_model.data(), &QAbstractItemModel::rowsMoved,
this, &ItemPinnedSaver::onRowsMoved );
}
void ItemPinnedSaver::onRowsMoved(const QModelIndex &, int start, int end, const QModelIndex &, int destinationRow)
{
if (!m_model)
return;
if ( (m_lastPinned >= start || m_lastPinned >= destinationRow)
&& (end >= m_lastPinned || destinationRow >= m_lastPinned) )
{
if (start < destinationRow)
updateLastPinned(start, destinationRow + end - start + 1);
else
updateLastPinned(destinationRow, end);
}
if (destinationRow != 0 || start < destinationRow)
return;
const int rowCount = end - start + 1;
for (int row = destinationRow; row < destinationRow + rowCount; ++row) {
if ( isPinned(m_model->index(row, 0)) )
return;
}
disconnect( m_model.data(), &QAbstractItemModel::rowsMoved,
this, &ItemPinnedSaver::onRowsMoved );
// Shift rows below inserted up.
for (int row = destinationRow + rowCount; row <= std::min(m_lastPinned, end); ++row) {
const auto index = m_model->index(row, 0);
if ( isPinned(index) )
moveRow(row, row - rowCount);
}
connect( m_model.data(), &QAbstractItemModel::rowsMoved,
this, &ItemPinnedSaver::onRowsMoved );
}
void ItemPinnedSaver::onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
if ( bottomRight.row() < m_lastPinned )
return;
updateLastPinned( topLeft.row(), bottomRight.row() );
}
void ItemPinnedSaver::moveRow(int from, int to)
{
m_model->moveRow(QModelIndex(), from, QModelIndex(), to);
}
void ItemPinnedSaver::updateLastPinned(int from, int to)
{
for (int row = to; row >= from; --row) {
const auto index = m_model->index(row, 0);
if ( isPinned(index) ) {
m_lastPinned = row;
break;
}
}
}
ItemPinnedLoader::ItemPinnedLoader()
{
}
ItemPinnedLoader::~ItemPinnedLoader() = default;
QStringList ItemPinnedLoader::formatsToSave() const
{
return QStringList() << mimePinned;
}
ItemWidget *ItemPinnedLoader::transform(ItemWidget *itemWidget, const QVariantMap &data)
{
return data.contains(mimePinned) ? new ItemPinned(itemWidget) : nullptr;
}
ItemSaverPtr ItemPinnedLoader::transformSaver(const ItemSaverPtr &saver, QAbstractItemModel *model)
{
return std::make_shared<ItemPinnedSaver>(model, saver);
}
QObject *ItemPinnedLoader::tests(const TestInterfacePtr &test) const
{
#ifdef HAS_TESTS
QObject *tests = new ItemPinnedTests(test);
return tests;
#else
Q_UNUSED(test)
return nullptr;
#endif
}
ItemScriptable *ItemPinnedLoader::scriptableObject()
{
return new ItemPinnedScriptable();
}
QVector<Command> ItemPinnedLoader::commands() const
{
QVector<Command> commands;
Command c;
c = dummyPinCommand();
c.internalId = QStringLiteral("copyq_pinned_pin");
c.name = tr("Pin");
c.input = "!OUTPUT";
c.output = mimePinned;
c.cmd = "copyq: plugins.itempinned.pin()";
commands.append(c);
c = dummyPinCommand();
c.internalId = QStringLiteral("copyq_pinned_unpin");
c.name = tr("Unpin");
c.input = mimePinned;
c.cmd = "copyq: plugins.itempinned.unpin()";
commands.append(c);
return commands;
}
| 9,972
|
C++
|
.cpp
| 298
| 28.090604
| 115
| 0.66736
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,115
|
itempinnedtests.cpp
|
hluk_CopyQ/plugins/itempinned/tests/itempinnedtests.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itempinnedtests.h"
#include "tests/test_utils.h"
#include "common/commandstatus.h"
ItemPinnedTests::ItemPinnedTests(const TestInterfacePtr &test, QObject *parent)
: QObject(parent)
, m_test(test)
{
}
void ItemPinnedTests::initTestCase()
{
TEST(m_test->initTestCase());
}
void ItemPinnedTests::cleanupTestCase()
{
TEST(m_test->cleanupTestCase());
}
void ItemPinnedTests::init()
{
TEST(m_test->init());
}
void ItemPinnedTests::cleanup()
{
TEST( m_test->cleanup() );
}
void ItemPinnedTests::isPinned()
{
RUN("add" << "b" << "a", "");
RUN("-e" << "plugins.itempinned.isPinned(0)", "false\n");
RUN("-e" << "plugins.itempinned.isPinned(1)", "false\n");
}
void ItemPinnedTests::pin()
{
RUN("add" << "b" << "a", "");
RUN("-e" << "plugins.itempinned.pin(1)", "");
RUN("-e" << "plugins.itempinned.isPinned(1)", "true\n");
RUN("-e" << "plugins.itempinned.isPinned(0)", "false\n");
RUN("-e" << "plugins.itempinned.pin(0)", "");
RUN("-e" << "plugins.itempinned.isPinned(0)", "true\n");
RUN("-e" << "plugins.itempinned.isPinned(1)", "true\n");
}
void ItemPinnedTests::pinMultiple()
{
RUN("add" << "d" << "c" << "b" << "a", "");
RUN("-e" << "plugins.itempinned.pin(1, 2)", "");
RUN("-e" << "plugins.itempinned.isPinned(0)", "false\n");
RUN("-e" << "plugins.itempinned.isPinned(1)", "true\n");
RUN("-e" << "plugins.itempinned.isPinned(2)", "true\n");
RUN("-e" << "plugins.itempinned.isPinned(3)", "false\n");
RUN("-e" << "plugins.itempinned.pin(1, 2 ,3)", "");
RUN("-e" << "plugins.itempinned.isPinned(0)", "false\n");
RUN("-e" << "plugins.itempinned.isPinned(1)", "true\n");
RUN("-e" << "plugins.itempinned.isPinned(2)", "true\n");
RUN("-e" << "plugins.itempinned.isPinned(3)", "true\n");
}
void ItemPinnedTests::unpin()
{
RUN("add" << "b" << "a", "");
RUN("-e" << "plugins.itempinned.pin(0, 1)", "");
RUN("-e" << "plugins.itempinned.isPinned(0)", "true\n");
RUN("-e" << "plugins.itempinned.isPinned(1)", "true\n");
RUN("-e" << "plugins.itempinned.unpin(0)", "");
RUN("-e" << "plugins.itempinned.isPinned(0)", "false\n");
RUN("-e" << "plugins.itempinned.isPinned(1)", "true\n");
RUN("-e" << "plugins.itempinned.unpin(1)", "");
RUN("-e" << "plugins.itempinned.isPinned(0)", "false\n");
RUN("-e" << "plugins.itempinned.isPinned(1)", "false\n");
}
void ItemPinnedTests::unpinMultiple()
{
RUN("add" << "d" << "c" << "b" << "a", "");
RUN("-e" << "plugins.itempinned.pin(0, 1, 2, 3)", "");
RUN("-e" << "plugins.itempinned.isPinned(0)", "true\n");
RUN("-e" << "plugins.itempinned.isPinned(1)", "true\n");
RUN("-e" << "plugins.itempinned.isPinned(2)", "true\n");
RUN("-e" << "plugins.itempinned.isPinned(3)", "true\n");
RUN("-e" << "plugins.itempinned.unpin(1, 2)", "");
RUN("-e" << "plugins.itempinned.isPinned(0)", "true\n");
RUN("-e" << "plugins.itempinned.isPinned(1)", "false\n");
RUN("-e" << "plugins.itempinned.isPinned(2)", "false\n");
RUN("-e" << "plugins.itempinned.isPinned(3)", "true\n");
RUN("-e" << "plugins.itempinned.unpin(2, 3)", "");
RUN("-e" << "plugins.itempinned.isPinned(0)", "true\n");
RUN("-e" << "plugins.itempinned.isPinned(1)", "false\n");
RUN("-e" << "plugins.itempinned.isPinned(2)", "false\n");
RUN("-e" << "plugins.itempinned.isPinned(3)", "false\n");
}
void ItemPinnedTests::removePinnedThrows()
{
RUN("add" << "b" << "a", "");
RUN("-e" << "plugins.itempinned.pin(0, 1)", "");
RUN_EXPECT_ERROR("remove" << "0" << "1", CommandException);
RUN("separator" << " " << "read" << "0" << "1", "a b");
}
void ItemPinnedTests::pinToRow()
{
const auto read = Args() << "separator" << " " << "read";
RUN("add" << "a", "");
RUN("-e" << "plugins.itempinned.pin(0)", "");
RUN("add" << "b", "");
RUN(read << "0" << "1", "a b");
RUN("add" << "c", "");
RUN(read << "0" << "1" << "2", "a c b");
RUN("-e" << "plugins.itempinned.pin(1)", "");
RUN("add" << "d", "");
RUN(read << "0" << "1" << "2" << "3", "a c d b");
RUN("-e" << "plugins.itempinned.pin(2)", "");
RUN("-e" << "plugins.itempinned.unpin(1); remove(1)", "");
RUN(read << "0" << "1" << "2", "a b d");
}
void ItemPinnedTests::fullTab()
{
RUN("config" << "maxitems" << "3", "3\n");
RUN("add" << "c" << "b" << "a", "");
RUN("-e" << "plugins.itempinned.pin(0,1,2)", "");
// Tab is full and no items can be removed.
RUN_EXPECT_ERROR("add" << "X", CommandException);
RUN_EXPECT_ERROR("write" << "1" << "text/plain" << "X", CommandException);
RUN("separator" << " " << "read" << "0" << "1" << "2", "a b c");
RUN("size", "3\n");
}
| 4,767
|
C++
|
.cpp
| 121
| 35.586777
| 79
| 0.554786
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,116
|
itemtext.cpp
|
hluk_CopyQ/plugins/itemtext/itemtext.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemtext.h"
#include "ui_itemtextsettings.h"
#include "common/mimetypes.h"
#include "common/sanitize_text_document.h"
#include "common/textdata.h"
#include <QAbstractTextDocumentLayout>
#include <QCoreApplication>
#include <QContextMenuEvent>
#include <QCursor>
#include <QMimeData>
#include <QMouseEvent>
#include <QScrollBar>
#include <QSettings>
#include <QTextBlock>
#include <QTextCursor>
#include <QTextDocument>
#include <QtPlugin>
namespace {
// Limit number of characters for performance reasons.
const int maxCharacters = 100 * 1024;
// Limit line length for performance reasons.
const int maxLineLength = 1024;
const int maxLineLengthInPreview = 16 * maxLineLength;
// Limit line count for performance reasons.
const int maxLineCount = 4 * 1024;
const int maxLineCountInPreview = 16 * maxLineCount;
const QLatin1String optionUseRichText("use_rich_text");
const QLatin1String optionMaximumLines("max_lines");
const QLatin1String optionMaximumHeight("max_height");
const QLatin1String optionDefaultStyleSheet("default_style_sheet");
// Some applications insert \0 terminator at the end of text data.
// It needs to be removed because QTextBrowser can render the character.
void removeTrailingNull(QString *text)
{
if ( text->endsWith(QChar(0)) )
text->chop(1);
}
bool getRichText(const QVariantMap &dataMap, QString *text)
{
if ( dataMap.contains(mimeHtml) ) {
*text = getTextData(dataMap, mimeHtml);
return true;
}
return false;
}
QString normalizeText(QString text)
{
removeTrailingNull(&text);
return text.left(maxCharacters);
}
void insertEllipsis(QTextCursor *tc)
{
tc->insertHtml( " "
"<span style='background:rgba(0,0,0,30);border-radius:4px'>"
" … "
"</span>" );
}
} // namespace
ItemText::ItemText(
const QString &text,
const QString &richText,
const QString &defaultStyleSheet,
int maxLines,
int lineLength,
int maximumHeight,
QWidget *parent)
: QTextEdit(parent)
, ItemWidget(this)
, m_textDocument()
, m_maximumHeight(maximumHeight)
{
m_textDocument.setDefaultFont(font());
// Disable slow word wrapping initially.
setLineWrapMode(QTextEdit::NoWrap);
QTextOption option = m_textDocument.defaultTextOption();
option.setWrapMode(QTextOption::NoWrap);
m_textDocument.setDefaultTextOption(option);
m_textDocument.setDefaultStyleSheet(defaultStyleSheet);
setReadOnly(true);
setUndoRedoEnabled(false);
setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setFrameStyle(QFrame::NoFrame);
if ( !richText.isEmpty() ) {
m_textDocument.setHtml(richText);
// Use plain text instead if rendering HTML fails or result is empty.
m_isRichText = !m_textDocument.isEmpty();
}
if (!m_isRichText)
m_textDocument.setPlainText(text);
if (maxLines > 0) {
QTextBlock block = m_textDocument.findBlockByLineNumber(maxLines);
if (block.isValid()) {
QTextCursor tc(&m_textDocument);
tc.setPosition(block.position() - 1);
tc.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
m_elidedFragment = tc.selection();
tc.removeSelectedText();
m_ellipsisPosition = tc.position();
insertEllipsis(&tc);
}
}
if (lineLength > 0) {
for ( auto block = m_textDocument.begin(); block.isValid(); block = block.next() ) {
if ( block.length() > lineLength ) {
QTextCursor tc(&m_textDocument);
tc.setPosition(block.position() + lineLength);
tc.setPosition(block.position() + block.length() - 1, QTextCursor::KeepAnchor);
insertEllipsis(&tc);
}
}
}
if (m_isRichText)
sanitizeTextDocument(&m_textDocument);
connect( this, &QTextEdit::selectionChanged,
this, &ItemText::onSelectionChanged );
}
void ItemText::updateSize(QSize maximumSize, int idealWidth)
{
if ( m_textDocument.isEmpty() ) {
setFixedSize(0, 0);
return;
}
const int scrollBarWidth = verticalScrollBar()->width();
setMaximumHeight( maximumSize.height() );
setFixedWidth(idealWidth);
m_textDocument.setTextWidth(idealWidth - scrollBarWidth);
const bool noWrap = maximumSize.width() > idealWidth;
QTextOption option = m_textDocument.defaultTextOption();
const auto wrapMode = noWrap
? QTextOption::NoWrap : QTextOption::WrapAtWordBoundaryOrAnywhere;
if (wrapMode != option.wrapMode()) {
option.setWrapMode(wrapMode);
m_textDocument.setDefaultTextOption(option);
}
setLineWrapMode(noWrap ? QTextEdit::NoWrap : QTextEdit::WidgetWidth);
// setDocument() is slow, so postpone this after resized properly
if (document() != &m_textDocument)
setDocument(&m_textDocument);
if (m_maximumHeight != -1) {
const QSizeF size = m_textDocument.size();
const int h = size.height() + 1;
if (0 < m_maximumHeight && m_maximumHeight < h - 8)
setFixedHeight(m_maximumHeight);
else
setFixedHeight(h);
}
}
bool ItemText::eventFilter(QObject *, QEvent *event)
{
return ItemWidget::filterMouseEvents(this, event);
}
QMimeData *ItemText::createMimeDataFromSelection() const
{
const auto data = QTextEdit::createMimeDataFromSelection();
if (!data)
return nullptr;
// Copy only plain text if rich text is not available.
if (!m_isRichText) {
const auto text = data->text();
data->clear();
data->setText(text);
}
const auto owner = qApp->property("CopyQ_session_name").toString();
data->setData( mimeOwner, owner.toUtf8() );
return data;
}
void ItemText::onSelectionChanged()
{
// Expand the ellipsis if selected.
if ( m_ellipsisPosition == -1 || textCursor().selectionEnd() <= m_ellipsisPosition )
return;
QTextCursor tc(&m_textDocument);
tc.setPosition(m_ellipsisPosition);
m_ellipsisPosition = -1;
tc.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
tc.insertFragment(m_elidedFragment);
m_elidedFragment = QTextDocumentFragment();
}
ItemTextLoader::ItemTextLoader()
{
}
ItemTextLoader::~ItemTextLoader() = default;
ItemWidget *ItemTextLoader::create(const QVariantMap &data, QWidget *parent, bool preview) const
{
if ( data.value(mimeHidden).toBool() )
return nullptr;
QString richText;
const bool isRichText = m_useRichText && getRichText(data, &richText);
QString text = getTextData(data);
const bool isPlainText = !text.isEmpty();
if (!isRichText && !isPlainText)
return nullptr;
richText = normalizeText(richText);
text = normalizeText(text);
ItemText *item = nullptr;
Qt::TextInteractionFlags interactionFlags(Qt::LinksAccessibleByMouse);
// Always limit text size for performance reasons.
if (preview) {
item = new ItemText(text, richText, m_defaultStyleSheet, maxLineCountInPreview, maxLineLengthInPreview, -1, parent);
item->setFocusPolicy(Qt::StrongFocus);
interactionFlags = interactionFlags
| Qt::TextSelectableByKeyboard
| Qt::LinksAccessibleByKeyboard;
} else {
int maxLines = m_maxLines;
if (maxLines <= 0 || maxLines > maxLineCount)
maxLines = maxLineCount;
item = new ItemText(text, richText, m_defaultStyleSheet, maxLines, maxLineLength, m_maxHeight, parent);
item->viewport()->installEventFilter(item);
item->setContextMenuPolicy(Qt::NoContextMenu);
}
item->setTextInteractionFlags(item->textInteractionFlags() | interactionFlags);
return item;
}
QStringList ItemTextLoader::formatsToSave() const
{
return m_useRichText
? QStringList{mimeText, mimeTextUtf8, mimeHtml}
: QStringList{mimeText, mimeTextUtf8};
}
void ItemTextLoader::applySettings(QSettings &settings)
{
settings.setValue(optionUseRichText, ui->checkBoxUseRichText->isChecked());
settings.setValue(optionMaximumLines, ui->spinBoxMaxLines->value());
settings.setValue(optionMaximumHeight, ui->spinBoxMaxHeight->value());
settings.setValue(optionDefaultStyleSheet, ui->textEditDefaultStyleSheet->toPlainText());
}
void ItemTextLoader::loadSettings(const QSettings &settings)
{
m_useRichText = settings.value(optionUseRichText, true).toBool();
m_maxLines = settings.value(optionMaximumLines, maxLineCount).toInt();
m_maxHeight = settings.value(optionMaximumHeight).toInt();
m_defaultStyleSheet = settings.value(optionDefaultStyleSheet).toString();
}
QWidget *ItemTextLoader::createSettingsWidget(QWidget *parent)
{
ui.reset(new Ui::ItemTextSettings);
QWidget *w = new QWidget(parent);
ui->setupUi(w);
ui->checkBoxUseRichText->setChecked(m_useRichText);
ui->spinBoxMaxLines->setValue(m_maxLines);
ui->spinBoxMaxHeight->setValue(m_maxHeight);
ui->textEditDefaultStyleSheet->setPlainText(m_defaultStyleSheet);
return w;
}
| 9,291
|
C++
|
.cpp
| 247
| 31.975709
| 124
| 0.702035
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,117
|
itemimage.cpp
|
hluk_CopyQ/plugins/itemimage/itemimage.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemimage.h"
#include "ui_itemimagesettings.h"
#include "common/contenttype.h"
#include "common/mimetypes.h"
#include "item/itemeditor.h"
#include "gui/pixelratio.h"
#ifdef HAS_TESTS
# include "tests/itemimagetests.h"
#endif
#include <QBuffer>
#include <QHBoxLayout>
#include <QModelIndex>
#include <QMovie>
#include <QPainter>
#include <QPixmap>
#include <QSettings>
#include <QtPlugin>
#include <QVariant>
#include <QVariantMap>
namespace {
const QLatin1String configMaxImageWidth("max_image_width");
const QLatin1String configMaxImageHeight("max_image_height");
const QLatin1String configImageEditor("image_editor");
const QLatin1String configSvgEditor("svg_editor");
QString findImageFormat(const QList<QString> &formats)
{
// Check formats in this order.
static const auto imageFormats = QList<QLatin1String>()
<< QLatin1String("image/png")
<< QLatin1String("image/bmp")
<< QLatin1String("image/jpeg")
<< QLatin1String("image/gif");
for (const auto &format : imageFormats) {
if ( formats.contains(format) )
return format;
}
return QString();
}
bool getImageData(const QVariantMap &dataMap, QByteArray *data, QString *mime)
{
*mime = findImageFormat(dataMap.keys());
if ( mime->isEmpty() )
return false;
*data = dataMap[*mime].toByteArray();
return true;
}
bool getSvgData(const QVariantMap &dataMap, QByteArray *data, QString *mime)
{
const QString svgMime("image/svg+xml");
if ( !dataMap.contains(svgMime) )
return false;
*mime = svgMime;
*data = dataMap[*mime].toByteArray();
return true;
}
bool getAnimatedImageData(const QVariantMap &dataMap, QByteArray *data, QByteArray *format)
{
for (const auto &movieFormat : QMovie::supportedFormats()) {
const QByteArray mime = "image/" + movieFormat;
if (dataMap.contains(mime)) {
*format = movieFormat;
*data = dataMap[mime].toByteArray();
return true;
}
}
return false;
}
bool getPixmapFromData(const QVariantMap &dataMap, QPixmap *pix)
{
QString mime;
QByteArray data;
if ( !getImageData(dataMap, &data, &mime) && !getSvgData(dataMap, &data, &mime) )
return false;
pix->loadFromData( data, mime.toLatin1() );
return true;
}
} // namespace
ItemImage::ItemImage(
const QPixmap &pix,
const QByteArray &animationData, const QByteArray &animationFormat,
QWidget *parent)
: QLabel(parent)
, ItemWidget(this)
, m_pixmap(pix)
, m_animationData(animationData)
, m_animationFormat(animationFormat)
, m_animation(nullptr)
{
setMargin(4);
setPixmap(pix);
}
void ItemImage::updateSize(QSize, int)
{
const auto m2 = 2 * margin();
const auto ratio = pixelRatio(this);
const int w = (m_pixmap.width() + 1) / ratio + m2;
const int h = (m_pixmap.height() + 1) / ratio + m2;
setFixedSize( QSize(w, h) );
}
void ItemImage::setCurrent(bool current)
{
if (current) {
if ( !m_animationData.isEmpty() ) {
if (!m_animation) {
QBuffer *stream = new QBuffer(&m_animationData, this);
m_animation = new QMovie(stream, m_animationFormat, this);
m_animation->setScaledSize( m_pixmap.size() );
}
if (m_animation) {
setMovie(m_animation);
startAnimation();
m_animation->start();
}
}
} else {
stopAnimation();
setPixmap(m_pixmap);
}
}
void ItemImage::showEvent(QShowEvent *event)
{
startAnimation();
QLabel::showEvent(event);
}
void ItemImage::hideEvent(QHideEvent *event)
{
QLabel::hideEvent(event);
stopAnimation();
}
void ItemImage::paintEvent(QPaintEvent *event)
{
// WORKAROUND: Draw current animation frame with correct DPI.
if (movie()) {
QPainter painter(this);
auto pix = m_animation->currentPixmap();
pix.setDevicePixelRatio( pixelRatio(this) );
const auto m = margin();
painter.drawPixmap(m, m, pix);
} else {
QLabel::paintEvent(event);
}
}
void ItemImage::startAnimation()
{
if (movie())
movie()->start();
}
void ItemImage::stopAnimation()
{
if (movie())
movie()->stop();
}
ItemImageLoader::ItemImageLoader()
{
}
ItemImageLoader::~ItemImageLoader() = default;
ItemWidget *ItemImageLoader::create(const QVariantMap &data, QWidget *parent, bool preview) const
{
if ( data.value(mimeHidden).toBool() )
return nullptr;
// TODO: Just check if image provided and load it in different thread.
QPixmap pix;
if ( !getPixmapFromData(data, &pix) )
return nullptr;
pix.setDevicePixelRatio( pixelRatio(parent) );
// scale pixmap
const int w = preview ? 0 : m_maxImageWidth;
const int h = preview ? 0 : m_maxImageHeight;
if ( w > 0 && pix.width() > w && (h <= 0 || 1.0 * pix.width()/w > 1.0 * pix.height()/h) ) {
pix = pix.scaledToWidth(w, Qt::SmoothTransformation);
} else if (h > 0 && pix.height() > h) {
pix = pix.scaledToHeight(h, Qt::SmoothTransformation);
}
QByteArray animationData;
QByteArray animationFormat;
getAnimatedImageData(data, &animationData, &animationFormat);
return new ItemImage(pix, animationData, animationFormat, parent);
}
QStringList ItemImageLoader::formatsToSave() const
{
return {
QLatin1String("image/svg+xml"),
QLatin1String("image/png"),
QLatin1String("image/gif")
};
}
QObject *ItemImageLoader::tests(const TestInterfacePtr &test) const
{
#ifdef HAS_TESTS
QObject *tests = new ItemImageTests(test);
return tests;
#else
Q_UNUSED(test)
return nullptr;
#endif
}
void ItemImageLoader::applySettings(QSettings &settings)
{
settings.setValue(configMaxImageWidth, ui->spinBoxImageWidth->value());
settings.setValue(configMaxImageHeight, ui->spinBoxImageHeight->value());
settings.setValue(configImageEditor, ui->lineEditImageEditor->text());
settings.setValue(configSvgEditor, ui->lineEditSvgEditor->text());
}
void ItemImageLoader::loadSettings(const QSettings &settings)
{
m_maxImageWidth = settings.value(configMaxImageWidth, 320).toInt();
m_maxImageHeight = settings.value(configMaxImageHeight, 240).toInt();
m_imageEditor = settings.value(configImageEditor).toString();
m_svgEditor = settings.value(configSvgEditor).toString();
}
QWidget *ItemImageLoader::createSettingsWidget(QWidget *parent)
{
ui.reset(new Ui::ItemImageSettings);
QWidget *w = new QWidget(parent);
ui->setupUi(w);
ui->spinBoxImageWidth->setValue(m_maxImageWidth);
ui->spinBoxImageHeight->setValue(m_maxImageHeight);
ui->lineEditImageEditor->setText(m_imageEditor);
ui->lineEditSvgEditor->setText(m_svgEditor);
return w;
}
QObject *ItemImageLoader::createExternalEditor(const QModelIndex &, const QVariantMap &data, QWidget *parent) const
{
QString mime;
QByteArray imageData;
if ( !m_imageEditor.isEmpty() && getImageData(data, &imageData, &mime) )
return new ItemEditor(imageData, mime, m_imageEditor, parent);
if ( !m_svgEditor.isEmpty() && getSvgData(data, &imageData, &mime) )
return new ItemEditor(imageData, mime, m_svgEditor, parent);
return nullptr;
}
| 7,428
|
C++
|
.cpp
| 232
| 27.168103
| 115
| 0.682422
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,118
|
itemimagetests.cpp
|
hluk_CopyQ/plugins/itemimage/tests/itemimagetests.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemimagetests.h"
#include "tests/test_utils.h"
#include <QBuffer>
#include <QImageReader>
#include <QImageWriter>
#include <QImage>
ItemImageTests::ItemImageTests(const TestInterfacePtr &test, QObject *parent)
: QObject(parent)
, m_test(test)
{
}
void ItemImageTests::initTestCase()
{
TEST(m_test->initTestCase());
}
void ItemImageTests::cleanupTestCase()
{
TEST(m_test->cleanupTestCase());
}
void ItemImageTests::init()
{
TEST(m_test->init());
}
void ItemImageTests::cleanup()
{
TEST( m_test->cleanup() );
}
void ItemImageTests::supportedFormats()
{
const auto supportedRead = QImageReader::supportedImageFormats();
QVERIFY(supportedRead.contains("png"));
QVERIFY(supportedRead.contains("bmp"));
#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
QVERIFY(supportedRead.contains("gif"));
QVERIFY(supportedRead.contains("webp"));
#endif
const auto supportedWrite = QImageWriter::supportedImageFormats();
QVERIFY(supportedWrite.contains("png"));
QVERIFY(supportedWrite.contains("bmp"));
}
void ItemImageTests::savePng()
{
QImage image(":images/icon");
QVERIFY(!image.isNull());
image = image.scaled(QSize(16, 16));
QByteArray data;
QBuffer buffer(&data);
buffer.open(QBuffer::ReadWrite);
QVERIFY(image.save(&buffer, "PNG"));
TEST( m_test->setClipboard("TEST") );
WAIT_ON_OUTPUT("read(0)", "TEST");
TEST( m_test->setClipboard(data, "image/png") );
WAIT_ON_OUTPUT("read('image/png', 0).length > 0", "true\n");
}
void ItemImageTests::saveBmp()
{
QImage image(":images/icon");
QVERIFY(!image.isNull());
image = image.scaled(QSize(16, 16));
QByteArray data;
QBuffer buffer(&data);
buffer.open(QBuffer::ReadWrite);
QVERIFY(image.save(&buffer, "BMP"));
TEST( m_test->setClipboard("TEST") );
WAIT_ON_OUTPUT("read(0)", "TEST");
TEST( m_test->setClipboard(data, "image/bmp") );
WAIT_ON_OUTPUT("read('image/png', 0).length > 0", "true\n");
}
void ItemImageTests::saveGif()
{
if ( !QImageReader::supportedImageFormats().contains("gif") )
SKIP("GIF image format is unsopported on this platform");
const auto data = QByteArray::fromBase64(
"R0lGODlhCAAIAPQAAAAAAE5WUURsU0ZuVVxkX3Jycnx8fFKCZFyRcFyScF6Ucl+Wc1+WdGmLdmuMeGGadmqqgmurg5OUlJubm56dnaGhobW1tb2+vgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAAAIf8LSW1hZ2VNYWdpY2sNZ2FtbWE9MC40NTQ1NQAsAAAAAAgACAAABSYgAAwiKSZLkjCJ+AhRJDzikTTOcohAIF0EHmBSsVCEhkLBIGwCQgA7");
TEST( m_test->setClipboard("TEST") );
WAIT_ON_OUTPUT("read(0)", "TEST");
TEST( m_test->setClipboard(data, "image/gif") );
WAIT_ON_OUTPUT("read('image/png', 0).length > 0", "true\n");
}
void ItemImageTests::saveWebp()
{
if ( !QImageReader::supportedImageFormats().contains("webp") )
SKIP("WEBP image format is unsopported on this platform");
const auto data = QByteArray::fromBase64(
"UklGRrgAAABXRUJQVlA4WAoAAAAQAAAABwAABwAAQUxQSEEAAAAACFmTUFCTWQhN3url5ereTXLuwPn5wO5yLrvx/v7xuy4AIbD//7AhAAARw/z8wxEAAA2vqKivDAAAAEc2NkcAAABWUDggUAAAAPABAJ0BKggACAACADQljAJ0AQ8M/qJ2gAD+3i3bP+bdQx6F+ZyiDZNsPKvgXJjteWOHwsl4XY+Utm/aW5R74XTu3MMrnj1KVx5aDzswFkAA");
TEST( m_test->setClipboard("TEST") );
WAIT_ON_OUTPUT("read(0)", "TEST");
TEST( m_test->setClipboard(data, "image/webp") );
WAIT_ON_OUTPUT("read('image/png', 0).length > 0", "true\n");
}
| 3,416
|
C++
|
.cpp
| 91
| 33.846154
| 276
| 0.724879
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,119
|
itemnotes.cpp
|
hluk_CopyQ/plugins/itemnotes/itemnotes.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemnotes.h"
#include "ui_itemnotessettings.h"
#include "common/contenttype.h"
#include "common/mimetypes.h"
#include "common/textdata.h"
#include "gui/iconfont.h"
#include "gui/iconwidget.h"
#include "gui/pixelratio.h"
#include "item/itemfilter.h"
#include <QBoxLayout>
#include <QLabel>
#include <QModelIndex>
#include <QMouseEvent>
#include <QPainter>
#include <QSettings>
#include <QTextCursor>
#include <QTextDocument>
#include <QTextEdit>
#include <QTimer>
#include <QToolTip>
#include <QVariantMap>
#include <QtPlugin>
#include <cmath>
namespace {
// Limit number of characters for performance reasons.
const int defaultMaxBytes = 10*1024;
const int notesIndent = 16;
const QLatin1String configNotesAtBottom("notes_at_bottom");
const QLatin1String configNotesBeside("notes_beside");
const QLatin1String configShowTooltip("show_tooltip");
QWidget *createIconWidget(const QByteArray &icon, QWidget *parent)
{
if (!icon.isEmpty()) {
QPixmap p;
if (p.loadFromData(icon)) {
const auto ratio = pixelRatio(parent);
p.setDevicePixelRatio(ratio);
const int side = ratio * (iconFontSizePixels() + 2);
p = p.scaled(side, side, Qt::KeepAspectRatio, Qt::SmoothTransformation);
QLabel *label = new QLabel(parent);
const auto m = side / 4;
label->setFixedSize( p.size() / ratio + QSize(m, m) );
label->setAlignment(Qt::AlignCenter);
label->setPixmap(p);
return label;
}
}
return new IconWidget(IconPenToSquare, parent);
}
} // namespace
ItemNotes::ItemNotes(ItemWidget *childItem, const QString &text, const QByteArray &icon,
NotesPosition notesPosition, bool showToolTip)
: QWidget( childItem->widget()->parentWidget() )
, ItemWidgetWrapper(childItem, this)
, m_notes(new QTextEdit(this))
, m_icon(nullptr)
, m_timerShowToolTip(nullptr)
, m_toolTipText()
{
childItem->widget()->setObjectName("item_child");
childItem->widget()->setParent(this);
if (!icon.isEmpty())
m_icon = createIconWidget(icon, this);
QBoxLayout *layout;
m_notes->setObjectName("item_child");
m_notes->setProperty("CopyQ_item_type", "notes");
m_notes->setReadOnly(true);
m_notes->setUndoRedoEnabled(false);
m_notes->setFocusPolicy(Qt::NoFocus);
m_notes->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_notes->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_notes->setFrameStyle(QFrame::NoFrame);
m_notes->setContextMenuPolicy(Qt::NoContextMenu);
m_notes->viewport()->installEventFilter(this);
m_notes->setPlainText( text.left(defaultMaxBytes) );
if (notesPosition == NotesBeside)
layout = new QHBoxLayout(this);
else
layout = new QVBoxLayout(this);
auto labelLayout = new QHBoxLayout;
labelLayout->setContentsMargins(notesIndent, 0, 0, 0);
if (m_icon)
labelLayout->addWidget(m_icon, 0, Qt::AlignLeft | Qt::AlignTop);
labelLayout->addWidget(m_notes, 1, Qt::AlignLeft | Qt::AlignTop);
if (notesPosition == NotesBelow) {
layout->addWidget( childItem->widget() );
layout->addLayout(labelLayout);
} else {
layout->addLayout(labelLayout);
layout->addWidget( childItem->widget() );
}
if (showToolTip) {
m_timerShowToolTip = new QTimer(this);
m_timerShowToolTip->setInterval(250);
m_timerShowToolTip->setSingleShot(true);
connect( m_timerShowToolTip, &QTimer::timeout,
this, &ItemNotes::showToolTip );
m_toolTipText = text;
}
layout->setContentsMargins({});
layout->setSpacing(0);
}
void ItemNotes::setCurrent(bool current)
{
ItemWidgetWrapper::setCurrent(current);
m_isCurrent = current;
if (m_timerShowToolTip == nullptr)
return;
QToolTip::hideText();
if (current)
m_timerShowToolTip->start();
else
m_timerShowToolTip->stop();
}
void ItemNotes::updateSize(QSize maximumSize, int idealWidth)
{
setMaximumSize(maximumSize);
if (m_notes) {
const int w = maximumSize.width() - 2 * notesIndent - 8;
QTextDocument *doc = m_notes->document();
doc->setTextWidth(w);
m_notes->setFixedSize(
static_cast<int>(doc->idealWidth()) + 16,
static_cast<int>(doc->size().height()) );
}
ItemWidgetWrapper::updateSize(maximumSize, idealWidth);
adjustSize();
setFixedSize(sizeHint());
}
void ItemNotes::paintEvent(QPaintEvent *event)
{
QWidget::paintEvent(event);
// Decorate notes.
if (m_notes != nullptr) {
QPainter p(this);
QColor c = p.pen().color();
c.setAlpha(80);
p.setBrush(c);
p.setPen(Qt::NoPen);
QWidget *w = m_icon ? m_icon : m_notes;
const auto height = std::max(w->height(), m_notes->height()) - 8;
p.drawRect(w->x() - notesIndent + 4, w->y() + 4,
notesIndent - 4, height);
}
}
bool ItemNotes::eventFilter(QObject *, QEvent *event)
{
if ( event->type() == QEvent::Show && m_timerShowToolTip && m_isCurrent )
m_timerShowToolTip->start();
return ItemWidget::filterMouseEvents(m_notes, event);
}
void ItemNotes::showToolTip()
{
QToolTip::hideText();
if ( !isVisible() )
return;
QPoint toolTipPosition = QPoint(parentWidget()->contentsRect().width() - 16, height() - 16);
toolTipPosition = mapToGlobal(toolTipPosition);
QToolTip::showText(toolTipPosition, m_toolTipText, this);
}
ItemNotesLoader::ItemNotesLoader()
{
}
ItemNotesLoader::~ItemNotesLoader() = default;
QStringList ItemNotesLoader::formatsToSave() const
{
return QStringList() << mimeItemNotes << mimeIcon;
}
void ItemNotesLoader::applySettings(QSettings &settings)
{
settings.setValue(configNotesAtBottom, ui->radioButtonBottom->isChecked());
settings.setValue(configNotesBeside, ui->radioButtonBeside->isChecked());
settings.setValue(configShowTooltip, ui->checkBoxShowToolTip->isChecked());
}
void ItemNotesLoader::loadSettings(const QSettings &settings)
{
m_notesAtBottom = settings.value(configNotesAtBottom, false).toBool();
m_notesBeside = settings.value(configNotesBeside, false).toBool();
m_showTooltip = settings.value(configShowTooltip, false).toBool();
}
QWidget *ItemNotesLoader::createSettingsWidget(QWidget *parent)
{
ui.reset(new Ui::ItemNotesSettings);
QWidget *w = new QWidget(parent);
ui->setupUi(w);
if (m_notesAtBottom)
ui->radioButtonBottom->setChecked(true);
else if (m_notesBeside)
ui->radioButtonBeside->setChecked(true);
else
ui->radioButtonTop->setChecked(true);
ui->checkBoxShowToolTip->setChecked(m_showTooltip);
return w;
}
ItemWidget *ItemNotesLoader::transform(ItemWidget *itemWidget, const QVariantMap &data)
{
const auto text = getTextData(data, mimeItemNotes);
const QByteArray icon = data.value(mimeIcon).toByteArray();
if ( text.isEmpty() && icon.isEmpty() )
return nullptr;
const NotesPosition notesPosition =
m_notesAtBottom ? NotesBelow
: m_notesBeside ? NotesBeside
: NotesAbove;
itemWidget->setTagged(true);
return new ItemNotes(
itemWidget, text, icon, notesPosition, m_showTooltip );
}
bool ItemNotesLoader::matches(const QModelIndex &index, const ItemFilter &filter) const
{
const QString text = index.data(contentType::notes).toString();
return filter.matches(text) || filter.matches(accentsRemoved(text));
}
| 7,676
|
C++
|
.cpp
| 214
| 30.462617
| 96
| 0.688006
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,122
|
qxtglobalshortcut_x11.cpp
|
hluk_CopyQ/qxt/qxtglobalshortcut_x11.cpp
|
#include "qxtglobalshortcut_p.h"
/****************************************************************************
** Copyright (c) 2006 - 2011, the LibQxt project.
** See the Qxt AUTHORS file for a list of authors and copyright holders.
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the LibQxt project nor the
** names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
** <http://libqxt.org> <foundation@libqxt.org>
*****************************************************************************/
#include "platform/x11/x11info.h"
#include <QVector>
#include <QWidget>
#include <X11/keysym.h>
#include <X11/Xlib.h>
#include <xcb/xcb.h>
#include "xcbkeyboard.h"
namespace {
/**
* Creates first invisible application window
* so X11 key press events can be received.
*
* This is used for Cinnamon and KDE.
*/
void createFirstWindow()
{
static QWidget *w = nullptr;
if (!w) {
// Try hard so the window is not visible.
// Tool tips won't show in taskbar.
w = new QWidget(nullptr, Qt::ToolTip);
w->setWindowTitle(QStringLiteral("Dummy"));
w->setWindowRole(QStringLiteral("dummy"));
// Move out of screen (if it's not possible to show the window minimized).
w->resize(1, 1);
w->move(-100000, -100000);
// Show and hide quickly.
w->showMinimized();
w->hide();
}
}
QVector<quint32> maskModifiers()
{
return QVector<quint32>() << 0 << Mod2Mask << LockMask << (Mod2Mask | LockMask);
}
using X11ErrorHandler = int (*)(Display* display, XErrorEvent* event);
class QxtX11ErrorHandler final {
public:
static bool error;
static int qxtX11ErrorHandler(Display* display, XErrorEvent *event)
{
Q_UNUSED(display)
switch (event->error_code)
{
case BadAccess:
case BadValue:
case BadWindow:
if (event->request_code == 33 /* X_GrabKey */ ||
event->request_code == 34 /* X_UngrabKey */)
{
error = true;
//TODO:
//char errstr[256];
//XGetErrorText(dpy, err->error_code, errstr, 256);
}
}
return 0;
}
QxtX11ErrorHandler()
: m_previousErrorHandler(nullptr)
{
error = false;
m_previousErrorHandler = XSetErrorHandler(qxtX11ErrorHandler);
}
~QxtX11ErrorHandler()
{
XSetErrorHandler(m_previousErrorHandler);
}
private:
X11ErrorHandler m_previousErrorHandler;
};
bool QxtX11ErrorHandler::error = false;
class QxtX11Data final {
public:
QxtX11Data()
: m_display(nullptr)
{
if ( X11Info::isPlatformX11() ) {
createFirstWindow();
m_display = X11Info::display();
}
}
bool isValid()
{
return X11Info::isPlatformX11() && m_display != nullptr;
}
Display *display()
{
Q_ASSERT(isValid());
return m_display;
}
Window rootWindow()
{
return DefaultRootWindow(display());
}
bool grabKey(quint32 keycode, quint32 modifiers, Window window)
{
QxtX11ErrorHandler errorHandler;
for (const auto maskMods : maskModifiers()) {
XGrabKey(display(), static_cast<int>(keycode), modifiers | maskMods, window, True,
GrabModeAsync, GrabModeAsync);
if (errorHandler.error)
break;
}
if (errorHandler.error) {
ungrabKey(keycode, modifiers, window);
return false;
}
return true;
}
bool ungrabKey(quint32 keycode, quint32 modifiers, Window window)
{
QxtX11ErrorHandler errorHandler;
for (const auto maskMods : maskModifiers()) {
XUngrabKey(display(), static_cast<int>(keycode), modifiers | maskMods, window);
}
return !errorHandler.error;
}
private:
Display *m_display;
};
KeySym qtKeyToXKeySym(Qt::Key key, Qt::KeyboardModifiers mods)
{
int i = 0;
if ( mods.testFlag(Qt::KeypadModifier) ) {
switch (key) {
case Qt::Key_0: return XK_KP_Insert;
case Qt::Key_1: return XK_KP_End;
case Qt::Key_2: return XK_KP_Down;
case Qt::Key_3: return XK_KP_Page_Down;
case Qt::Key_4: return XK_KP_Left;
case Qt::Key_5: return XK_KP_Begin;
case Qt::Key_6: return XK_KP_Right;
case Qt::Key_7: return XK_KP_Home;
case Qt::Key_8: return XK_KP_Up;
case Qt::Key_9: return XK_KP_Page_Up;
default: break;
}
for (; KeyTbl[i] != 0; i += 2) {
if (KeyTbl[i] == XK_Num_Lock)
break;
}
} else {
const auto keySym = XStringToKeysym(QKeySequence(key).toString().toLatin1().data());
if (keySym != NoSymbol)
return keySym;
}
for (; KeyTbl[i] != 0; i += 2) {
if (KeyTbl[i + 1] == key)
return KeyTbl[i];
}
return static_cast<ushort>(key);
}
} // namespace
bool QxtGlobalShortcutPrivate::nativeEventFilter(
const QByteArray &eventType, void *message, NativeEventResult *result)
{
Q_UNUSED(result)
xcb_key_press_event_t *kev = nullptr;
if (eventType == "xcb_generic_event_t") {
xcb_generic_event_t* ev = static_cast<xcb_generic_event_t *>(message);
if ((ev->response_type & 127) == XCB_KEY_PRESS)
kev = static_cast<xcb_key_press_event_t *>(message);
}
if (kev != nullptr) {
unsigned int keycode = kev->detail;
unsigned int keystate = 0;
if(kev->state & XCB_MOD_MASK_1)
keystate |= Mod1Mask;
if(kev->state & XCB_MOD_MASK_CONTROL)
keystate |= ControlMask;
if(kev->state & XCB_MOD_MASK_4)
keystate |= Mod4Mask;
if(kev->state & XCB_MOD_MASK_SHIFT)
keystate |= ShiftMask;
activateShortcut(keycode,
// Mod1Mask == Alt, Mod4Mask == Meta
keystate & (ShiftMask | ControlMask | Mod1Mask | Mod4Mask));
}
return false;
}
quint32 QxtGlobalShortcutPrivate::nativeModifiers(Qt::KeyboardModifiers modifiers)
{
// ShiftMask, LockMask, ControlMask, Mod1Mask, Mod2Mask, Mod3Mask, Mod4Mask, and Mod5Mask
quint32 native = 0;
if (modifiers & Qt::ShiftModifier)
native |= ShiftMask;
if (modifiers & Qt::ControlModifier)
native |= ControlMask;
if (modifiers & Qt::AltModifier)
native |= Mod1Mask;
if (modifiers & Qt::MetaModifier)
native |= Mod4Mask;
// TODO: resolve these?
//if (modifiers & Qt::MetaModifier)
//if (modifiers & Qt::KeypadModifier)
//if (modifiers & Qt::GroupSwitchModifier)
return native;
}
quint32 QxtGlobalShortcutPrivate::nativeKeycode(Qt::Key key, Qt::KeyboardModifiers mods)
{
QxtX11Data x11;
if (!x11.isValid())
return 0;
const KeySym keysym = qtKeyToXKeySym(key, mods);
return XKeysymToKeycode(x11.display(), keysym);
}
bool QxtGlobalShortcutPrivate::registerShortcut(quint32 nativeKey, quint32 nativeMods)
{
QxtX11Data x11;
return x11.isValid() && x11.grabKey(nativeKey, nativeMods, x11.rootWindow());
}
bool QxtGlobalShortcutPrivate::unregisterShortcut(quint32 nativeKey, quint32 nativeMods)
{
QxtX11Data x11;
return x11.isValid() && x11.ungrabKey(nativeKey, nativeMods, x11.rootWindow());
}
| 8,813
|
C++
|
.cpp
| 247
| 29.34413
| 94
| 0.632363
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
18,124
|
main.cpp
|
hluk_CopyQ/src/main.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "app/app.h"
#include "app/applicationexceptionhandler.h"
#include "app/clipboardclient.h"
#include "app/clipboardserver.h"
#include "common/commandstatus.h"
#include "common/log.h"
#include "common/messagehandlerforqt.h"
#include "common/textdata.h"
#include "platform/platformnativeinterface.h"
#ifdef Q_OS_UNIX
# include "platform/unix/unixsignalhandler.h"
#endif
#include "scriptable/scriptable.h"
#include <QApplication>
#include <QFile>
#include <QJSEngine>
#include <QProcess>
#include <QSettings>
#ifdef HAS_TESTS
# include "tests/tests.h"
#endif // HAS_TESTS
#include <exception>
Q_DECLARE_METATYPE(QByteArray*)
namespace {
int evaluate(
const QString &functionName,
const QStringList &arguments, int argc, char **argv,
const QString &sessionName)
{
App app( platformNativeInterface()->createConsoleApplication(argc, argv), sessionName );
setLogLabel("Prompt");
QJSEngine engine;
Scriptable scriptable(&engine, nullptr, nullptr);
QJSValue function = engine.globalObject().property(functionName);
QJSValueList functionArguments;
functionArguments.reserve( arguments.size() );
for (const auto &argument : arguments)
functionArguments.append(argument);
const auto result = function.call(functionArguments);
const bool hasUncaughtException = result.isError() || scriptable.hasUncaughtException();
const auto output = scriptable.fromString(result.toString());
if ( !output.isEmpty() && canUseStandardOutput() ) {
QFile f;
if (hasUncaughtException)
f.open(stderr, QIODevice::WriteOnly);
else
f.open(stdout, QIODevice::WriteOnly);
f.write(output);
if ( !output.endsWith("\n") )
f.write("\n");
f.close();
}
const int exitCode = hasUncaughtException ? CommandException : 0;
app.exit(exitCode);
return exitCode;
}
bool containsOnlyValidCharacters(const QString &sessionName)
{
for (const auto &c : sessionName) {
if ( !c.isLetterOrNumber() && c != '-' && c != '_' )
return false;
}
return true;
}
bool isValidSessionName(const QString &sessionName)
{
return !sessionName.isNull() &&
sessionName.length() < 16 &&
containsOnlyValidCharacters(sessionName);
}
QString restoreSessionName(const QString &sessionId)
{
const QSettings settings(
QSettings::IniFormat,
QSettings::UserScope,
QStringLiteral("copyq"),
QStringLiteral("copyq_no_session"));
const auto sessionNameKey = QLatin1String("session_") + sessionId;
const auto sessionName = settings.value(sessionNameKey).toString();
return sessionName;
}
int startServer(int argc, char *argv[], QString sessionName)
{
// By default, enable automatic screen scaling in Qt for high-DPI displays
// (this works better at least in Windows).
if ( qEnvironmentVariableIsEmpty("QT_AUTO_SCREEN_SCALE_FACTOR") )
qputenv("QT_AUTO_SCREEN_SCALE_FACTOR", QByteArrayLiteral("1"));
auto qapp = platformNativeInterface()->createServerApplication(argc, argv);
if ( qapp->isSessionRestored() ) {
const auto sessionId = qapp->sessionId();
sessionName = restoreSessionName(sessionId);
COPYQ_LOG( QStringLiteral("Restoring session ID \"%1\", session name \"%2\"")
.arg(sessionId, sessionName) );
if ( !sessionName.isEmpty() && !isValidSessionName(sessionName) ) {
log("Failed to restore session name", LogError);
return 2;
}
}
ClipboardServer app(qapp, sessionName);
return app.exec();
}
void startServerInBackground(const QString &applicationPath, QString sessionName)
{
const bool couldUseStandardOutput = canUseStandardOutput();
if (couldUseStandardOutput)
qputenv("COPYQ_NO_OUTPUT", QByteArrayLiteral("1"));
const QStringList arguments{QStringLiteral("-s"), sessionName};
const bool started = QProcess::startDetached(applicationPath, arguments);
if (!couldUseStandardOutput)
qunsetenv("COPYQ_NO_OUTPUT");
if (!started)
log("Failed to start the server", LogError);
}
int startClient(int argc, char *argv[], const QStringList &arguments, const QString &sessionName)
{
ClipboardClient app(argc, argv, arguments, sessionName);
return app.exec();
}
bool needsHelp(const QString &arg)
{
return arg == QLatin1String("-h") ||
arg == QLatin1String("--help") ||
arg == QLatin1String("help");
}
bool needsVersion(const QString &arg)
{
return arg == QLatin1String("-v") ||
arg == QLatin1String("--version") ||
arg == QLatin1String("version");
}
bool needsInfo(const QString &arg)
{
return arg == QLatin1String("--info") ||
arg == QLatin1String("info");
}
bool needsLogs(const QString &arg)
{
return arg == QLatin1String("--logs") ||
arg == QLatin1String("logs");
}
bool needsStartServer(const QString &arg)
{
return arg == QLatin1String("--start-server");
}
#ifdef HAS_TESTS
bool needsTests(const QString &arg)
{
return arg == QLatin1String("--tests") ||
arg == QLatin1String("tests");
}
#endif
QString getSessionName(const QStringList &arguments, int *skipArguments)
{
if (arguments.size() > 0) {
if ( arguments[0] == QLatin1String("-s")
|| arguments[0] == QLatin1String("--session")
|| arguments[0] == QLatin1String("session") )
{
*skipArguments = 2;
return arguments.value(1);
}
if ( arguments[0].startsWith(QLatin1String("--session=")) ) {
*skipArguments = 1;
return arguments[0].mid( arguments[0].indexOf('=') + 1 );
}
// Skip session arguments passed from session manager.
if (arguments.size() == 2 && arguments[0] == QLatin1String("-session"))
*skipArguments = 2;
}
return getTextData( qgetenv("COPYQ_SESSION_NAME") );
}
int startApplication(int argc, char **argv)
{
installMessageHandlerForQt();
#ifdef Q_OS_UNIX
if ( !initUnixSignalHandler() )
log("Failed to create handler for Unix signals!", LogError);
#endif
const QStringList arguments =
platformNativeInterface()->getCommandLineArguments(argc, argv);
// Get session name (default is empty).
int skipArguments = 0;
const QString sessionName = getSessionName(arguments, &skipArguments);
if ( !isValidSessionName(sessionName) ) {
log( QObject::tr("Session name must contain at most 16 characters\n"
"which can be letters, digits, '-' or '_'!"), LogError );
return 2;
}
// Print version, help or run tests.
if ( arguments.size() > skipArguments ) {
const auto arg = arguments[skipArguments];
if ( needsStartServer(arg) ) {
startServerInBackground( QString::fromUtf8(argv[0]), sessionName );
return skipArguments + 1 == arguments.size() ? 0
: startClient(argc, argv, arguments.mid(skipArguments + 1), sessionName);
}
if ( needsVersion(arg) )
return evaluate( QStringLiteral("version"), QStringList(), argc, argv, sessionName );
if ( needsHelp(arg) )
return evaluate( QStringLiteral("help"), arguments.mid(skipArguments + 1), argc, argv, sessionName );
if ( needsInfo(arg) )
return evaluate( QStringLiteral("info"), arguments.mid(skipArguments + 1), argc, argv, sessionName );
if ( needsLogs(arg) )
return evaluate( QStringLiteral("logs"), arguments.mid(skipArguments + 1), argc, argv, sessionName );
#ifdef HAS_TESTS
if ( needsTests(arg) ) {
// Skip the "tests" argument and pass the rest to tests.
return runTests(argc - skipArguments - 1, argv + skipArguments + 1);
}
#endif
}
// If server hasn't been run yet and no argument were specified
// then run this process as server.
if ( skipArguments == arguments.size() )
return startServer(argc, argv, sessionName);
// If argument was specified and server is running
// then run this process as client.
return startClient(argc, argv, arguments.mid(skipArguments), sessionName);
}
} // namespace
int main(int argc, char **argv)
{
try {
return startApplication(argc, argv);
} catch (const std::exception &e) {
logException(e.what());
throw;
} catch (...) {
logException();
throw;
}
}
| 8,604
|
C++
|
.cpp
| 233
| 31.021459
| 113
| 0.665104
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,125
|
tests_commands.cpp
|
hluk_CopyQ/src/tests/tests_commands.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "test_utils.h"
#include "tests.h"
#include "tests_common.h"
#include "common/sleeptimer.h"
void Tests::shortcutCommand()
{
RUN("setCommands([{name: 'test', inMenu: true, shortcuts: ['Ctrl+F1'], cmd: 'copyq add OK'}])", "");
RUN("keys" << "CTRL+F1", "");
WAIT_ON_OUTPUT("read" << "0", "OK");
}
void Tests::shortcutCommandOverrideEnter()
{
RUN("setCommands([{name: 'test', inMenu: true, shortcuts: ['Enter'], cmd: 'copyq add OK'}])", "");
RUN("keys" << "ENTER" << "ENTER", "");
WAIT_ON_OUTPUT("read" << "0" << "1", "OK\nOK");
}
void Tests::shortcutCommandMatchInput()
{
// Activate only one of the two actions depending on input MIME format.
const auto script = R"(
function cmd(name) {
var format = 'application/x-copyq-' + name
return {
name: name,
inMenu: true,
shortcuts: ['Ctrl+F1'],
input: format,
cmd: 'copyq add ' + name
}
}
setCommands([ cmd('test1'), cmd('test2') ])
)";
RUN(script, "");
RUN("write" << "application/x-copyq-test1" << "", "");
RUN("keys" << "CTRL+F1", "");
WAIT_ON_OUTPUT("read" << "0", "test1");
RUN("tab" << QString(clipboardTabName) << "size", "2\n");
RUN("write" << "application/x-copyq-test2" << "", "");
RUN("keys" << "CTRL+F1", "");
WAIT_ON_OUTPUT("read" << "0", "test2");
RUN("tab" << QString(clipboardTabName) << "size", "4\n");
}
void Tests::shortcutCommandMatchCmd()
{
const auto tab = testTab(1);
const Args args = Args("tab") << tab;
// Activate only one of the three actions depending on exit code of command which matches input MIME format.
const auto script = R"(
function cmd(name) {
var format = 'application/x-copyq-' + name
return {
name: name,
inMenu: true,
shortcuts: ['Ctrl+F1'],
matchCmd: 'copyq: str(data("' + format + '")) || fail()',
cmd: 'copyq tab )" + tab + R"( add ' + name
}
}
setCommands([ cmd('test1'), cmd('test2') ])
)";
RUN(script, "");
RUN("show" << tab, "");
RUN(args << "write" << "application/x-copyq-test1" << "1", "");
WAIT_ON_OUTPUT(args << "keys('Ctrl+F1'); read(0)", "test1");
RUN(args << "write" << "application/x-copyq-test2" << "2", "");
WAIT_ON_OUTPUT(args << "keys('Ctrl+F1'); read(0)", "test2");
}
void Tests::shortcutCommandSelectedItemData()
{
const auto tab1 = testTab(1);
const auto script = R"(
setCommands([{
name: 'Move Second Selected Item to Other Tab',
inMenu: true,
shortcuts: ['Ctrl+F1'],
output: 'text/plain',
outputTab: ')" + tab1 + R"(',
cmd: 'copyq: selectedItemData(1)["text/plain"]'
}])
)";
RUN(script, "");
RUN("add" << "C" << "B" << "A", "");
RUN("selectItems" << "1" << "2", "true\n");
RUN("keys" << "CTRL+F1", "");
WAIT_ON_OUTPUT("tab" << tab1 << "read" << "0", "C");
}
void Tests::shortcutCommandSetSelectedItemData()
{
const auto script = R"(
setCommands([{
name: 'Set Data for Second Selected Item',
inMenu: true,
shortcuts: ['Ctrl+F1'],
cmd: 'copyq: setSelectedItemData(1, {"text/plain": "X", "DATA": "TEST"})'
}])
)";
RUN(script, "");
RUN("add" << "C" << "B" << "A", "");
RUN("selectItems" << "1" << "2", "true\n");
RUN("keys" << "CTRL+F1", "");
WAIT_ON_OUTPUT("read" << "2", "X");
RUN("read" << "DATA" << "2", "TEST");
}
void Tests::shortcutCommandSelectedItemsData()
{
const auto tab1 = testTab(1);
const auto script = R"(
setCommands([{
name: 'Concatenate Selected Items to Other Tab',
inMenu: true,
shortcuts: ['Ctrl+F1'],
output: 'text/plain',
outputTab: ')" + tab1 + R"(',
cmd: 'copyq: d = selectedItemsData();'
+ 'for (i in d) { print(d[i][mimeText]); print(",") }'
}])
)";
RUN(script, "");
RUN("add" << "C" << "B" << "A", "");
RUN("selectItems" << "1" << "2", "true\n");
RUN("keys" << "CTRL+F1", "");
WAIT_ON_OUTPUT("tab" << tab1 << "read" << "0", "B,C,");
}
void Tests::shortcutCommandSetSelectedItemsData()
{
const auto script = R"(
setCommands([{
name: 'Set Data for Second Selected Item',
inMenu: true,
shortcuts: ['Ctrl+F1'],
cmd: 'copyq: setSelectedItemsData([{"text/plain": "X"}, {"text/plain": "Y"}])'
}])
)";
RUN(script, "");
RUN("add" << "C" << "B" << "A", "");
RUN("selectItems" << "1" << "2", "true\n");
RUN("keys" << "CTRL+F1", "");
WAIT_ON_OUTPUT("read" << "0" << "1" << "2", "A\nX\nY");
}
void Tests::shortcutCommandSelectedAndCurrent()
{
const auto script = R"(
setCommands([{
name: 'Set Data for Second Selected Item',
inMenu: true,
shortcuts: ['Ctrl+F1'],
output: 'text/plain',
cmd: 'copyq: print(selectedItems() + "|" + currentItem() + "|" + selectedTab())'
}])
)";
RUN(script, "");
const auto tab1 = testTab(1);
RUN("tab" << tab1 << "add" << "C" << "B" << "A", "");
RUN("tab" << tab1 << "setCurrentTab" << tab1 << "selectItems" << "1" << "2", "true\n");
RUN("keys" << "CTRL+F1", "");
WAIT_ON_OUTPUT("tab" << tab1 << "read(0)", "1,2|2|" + tab1.toUtf8());
}
void Tests::shortcutCommandMoveSelected()
{
const QString script = R"(
setCommands([{
name: 'Move Selected',
inMenu: true,
shortcuts: ['Ctrl+F1'],
output: 'text/plain',
cmd: 'copyq: move(%1); settings("done", 1)'
}])
)";
RUN(script.arg(1), "");
const Args args = Args("tab") << testTab(1) << "separator" << ",";
RUN("setCurrentTab" << testTab(1), "");
RUN(args << "add" << "4" << "3" << "2" << "1", "");
#define MOVE_SELECTED(EXPECTED_ITEMS) \
RUN("settings" << "done" << "0" << "keys" << "CTRL+F1", ""); \
WAIT_ON_OUTPUT("settings" << "done", "1\n"); \
RUN(args << "read(0,1,2,3,4)", EXPECTED_ITEMS)
RUN(args << "selectItems" << "1" << "2", "true\n");
MOVE_SELECTED("1,2,3,4,");
RUN(args << "selectItems" << "2" << "3", "true\n");
MOVE_SELECTED("1,3,4,2,");
RUN(script.arg(5), "");
MOVE_SELECTED("1,3,4,2,");
RUN(script.arg(-1), "");
MOVE_SELECTED("1,3,4,2,");
RUN(script.arg(4), "");
MOVE_SELECTED("1,2,3,4,");
RUN(script.arg(0), "");
MOVE_SELECTED("3,4,1,2,");
#undef MOVE_SELECTED
}
void Tests::automaticCommandIgnore()
{
const auto script = R"(
setCommands([
{ automatic: true, cmd: 'copyq ignore; copyq add OK' },
{ automatic: true, cmd: 'copyq add "SHOULD NOT BE EXECUTED"' }
])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "2\n");
TEST( m_test->setClipboard("SHOULD BE IGNORED 1") );
WAIT_ON_OUTPUT("read" << "0", "OK");
RUN("separator" << "," << "read" << "0" << "1" << "2", "OK,,");
RUN("size", "1\n");
TEST( m_test->setClipboard("SHOULD BE IGNORED 2") );
WAIT_ON_OUTPUT("size", "2\n");
RUN("separator" << "," << "read" << "0" << "1" << "2", "OK,OK,");
}
void Tests::automaticCommandRemove()
{
const auto script = R"(
setCommands([
{ automatic: true, remove: true, cmd: 'copyq add OK' },
{ automatic: true, cmd: 'copyq add "SHOULD NOT BE EXECUTED"' }
])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "2\n");
TEST( m_test->setClipboard("SHOULD BE IGNORED 1") );
WAIT_ON_OUTPUT("read" << "0", "OK");
TEST( m_test->setClipboard("SHOULD BE IGNORED 2") );
WAIT_ON_OUTPUT("size", "2\n");
RUN("separator" << "," << "read" << "0" << "1" << "2", "OK,OK,");
}
void Tests::automaticCommandInput()
{
const auto script = R"(
setCommands([
{ automatic: true, input: 'DATA', cmd: 'copyq: setData("DATA", "???")' },
{ automatic: true, input: 'text/plain', cmd: 'copyq: setData("text/plain", "OK")' },
])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "2\n");
TEST( m_test->setClipboard("SHOULD BE CHANGED") );
WAIT_ON_OUTPUT("read" << "0", "OK");
RUN("read" << "DATA" << "0", "");
}
void Tests::automaticCommandRegExp()
{
const auto script = R"(
setCommands([
{ automatic: true, re: 'SHOULD BE (CHANGED)$', cmd: 'copyq: setData(mimeText, arguments[1])' },
{ automatic: true, cmd: 'copyq: setData("DATA", "DONE")' },
])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "2\n");
TEST( m_test->setClipboard("SHOULD BE CHANGED") );
WAIT_ON_OUTPUT("read" << "DATA" << "0", "DONE");
RUN("read" << "0", "CHANGED");
RUN("remove" << "0", "");
TEST( m_test->setClipboard("SHOULD NOT BE CHANGED") );
WAIT_ON_OUTPUT("read" << "DATA" << "0", "DONE");
RUN("read" << "0", "SHOULD NOT BE CHANGED");
}
void Tests::automaticCommandSetData()
{
const auto script = R"(
setCommands([{automatic: true, cmd: 'copyq: setData("text/plain", "OK")'}])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "1\n");
TEST( m_test->setClipboard("SHOULD BE CHANGED") );
WAIT_ON_OUTPUT("read" << "0", "OK");
}
void Tests::automaticCommandOutputTab()
{
const auto tab1 = testTab(1);
const auto script = R"(
var tab1 = ')" + tab1 + R"('
setCommands([{automatic: true, cmd: 'copyq: setData(mimeOutputTab, "' + tab1 + '")'}])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "1\n");
TEST( m_test->setClipboard("TEST") );
WAIT_ON_OUTPUT("tab" << tab1 << "read" << "0", "TEST");
RUN("tab" << QString(clipboardTabName) << "size", "0\n");
}
void Tests::automaticCommandNoOutputTab()
{
const auto script = R"(
setCommands([{automatic: true, cmd: 'copyq: removeData(mimeOutputTab)'}])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "1\n");
TEST( m_test->setClipboard("TEST") );
waitFor(1000);
RUN("tab" << QString(clipboardTabName) << "size", "0\n");
}
void Tests::automaticCommandChaining()
{
const auto script = R"(
setCommands([
{automatic: true, cmd: 'copyq: setData(mimeText, 1)'},
{automatic: true, cmd: 'copyq: setData(mimeText, str(data(mimeText)) + 2)'},
{automatic: true, cmd: 'copyq: setData(mimeText, str(data(mimeText)) + 3)'}
])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "3\n");
TEST( m_test->setClipboard("TEST") );
WAIT_ON_OUTPUT("read" << "0", "123");
}
void Tests::automaticCommandCopyToTab()
{
const auto tab1 = testTab(1);
const auto script = R"(
setCommands([{automatic: true, tab: ')" + tab1 + R"('}])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "1\n");
TEST( m_test->setClipboard("TEST") );
WAIT_ON_OUTPUT("tab" << QString(clipboardTabName) << "read" << "0", "TEST");
RUN("tab" << tab1 << "read" << "0", "TEST");
}
void Tests::automaticCommandStoreSpecialFormat()
{
const auto script = R"(
setCommands([
{ automatic: true, name: 'CMD1', input: 'test-format' }
])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "1\n");
TEST( m_test->setClipboard("DATA", "test-format") );
WAIT_ON_OUTPUT("separator" << "," << "read" << "test-format" << "0" << "1", "DATA,");
}
void Tests::automaticCommandIgnoreSpecialFormat()
{
const auto script = R"(
setCommands([
{ automatic: true, name: 'CMD1', cmd: 'copyq add CMD1', input: 'test-format', remove: true },
{ automatic: true, name: 'CMD2', cmd: 'copyq add CMD2' },
{ automatic: true, name: 'CMD3', cmd: 'copyq add CMD3', input: 'test-format' }
])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "3\n");
TEST( m_test->setClipboard("SHOULD BE IGNORED", "test-format") );
WAIT_ON_OUTPUT("separator" << "," << "read" << "0" << "1", "CMD1,");
TEST( m_test->setClipboard("SHOULD NOT BE IGNORED") );
WAIT_ON_OUTPUT("separator" << "," << "read" << "0" << "1" << "2" << "3", "SHOULD NOT BE IGNORED,CMD2,CMD1,");
}
void Tests::globalCommandInMenu()
{
const auto script = R"(
setCommands([
{ isGlobalShortcut: true, name: 'test', cmd: 'copyq add test' },
])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "1\n");
RUN("menu", "");
RUN("keys" << trayMenuId << "DOWN" << "ENTER", "");
RUN("keys" << clipboardBrowserId, "");
WAIT_ON_OUTPUT("read(0)", "test");
RUN("setCommands([])", "");
WAIT_ON_OUTPUT("commands().length", "0\n");
// Test sub-menus
const auto script2 = R"(
setCommands([
{ isGlobalShortcut: true, name: 'test|test1|test2', cmd: 'copyq add test2' },
])
)";
RUN(script2, "");
WAIT_ON_OUTPUT("commands().length", "1\n");
RUN("menu", "");
RUN("keys" << trayMenuId << "DOWN" << "DOWN" << "ENTER", "");
waitFor(100);
RUN("keys" << trayMenuId << "ENTER", "");
waitFor(100);
RUN("keys" << trayMenuId << "ENTER", "");
RUN("keys" << clipboardBrowserId, "");
WAIT_ON_OUTPUT("read(0)", "test2");
}
| 13,589
|
C++
|
.cpp
| 377
| 29.657825
| 113
| 0.528902
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,126
|
tests_cli.cpp
|
hluk_CopyQ/src/tests/tests_cli.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "test_utils.h"
#include "tests.h"
#include "tests_common.h"
#include "common/commandstatus.h"
#include "common/log.h"
#include "common/version.h"
#include <QRegularExpression>
void Tests::readLog()
{
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("info") << "log", &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QCOMPARE( logFileName() + "\n", QString::fromUtf8(stdoutActual) );
QTRY_VERIFY( !readLogFile(maxReadLogSize).isEmpty() );
#define LOGGED_ONCE(PATTERN) \
QTRY_COMPARE( count(splitLines(readLogFile(maxReadLogSize)), PATTERN), 1 )
LOGGED_ONCE(
R"(^CopyQ DEBUG \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}\] <Server-\d+>: Loading configuration$)");
LOGGED_ONCE(
R"(^CopyQ DEBUG \[.*\] <Server-\d+>: Starting monitor$)");
LOGGED_ONCE(
R"(^.*<monitorClipboard-\d+>: Clipboard formats to save: .*$)");
}
void Tests::commandHelp()
{
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("help"), &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY(!stdoutActual.isEmpty());
const QStringList commands = QStringList()
<< "show"
<< "hide"
<< "toggle"
<< "menu"
<< "exit"
<< "help"
<< "version"
<< "clipboard"
<< "copy"
<< "paste"
<< "action"
<< "add"
<< "remove";
for (const auto &command : commands) {
QCOMPARE( run(Args("help") << command, &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY( !stdoutActual.isEmpty() );
const QString help = QString::fromUtf8(stdoutActual);
QVERIFY( help.contains(QRegularExpression("\\b" + QRegularExpression::escape(command) + "\\b")) );
}
// Print error on unknown function name.
RUN_EXPECT_ERROR("help" << "xxx", CommandException);
}
void Tests::commandVersion()
{
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("version"), &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY( !stdoutActual.isEmpty() );
const QString version = QString::fromUtf8(stdoutActual);
// Version contains application name and version.
QVERIFY( version.contains(QRegularExpression("\\bCopyQ\\b.*" + QRegularExpression::escape(versionString))) );
// Version contains Qt version.
QVERIFY( version.contains(QRegularExpression("\\bQt:\\s+\\d")) );
}
void Tests::badCommand()
{
RUN_EXPECT_ERROR_WITH_STDERR("xxx", CommandException, "xxx");
RUN_EXPECT_ERROR_WITH_STDERR("tab" << testTab(1) << "yyy", CommandException, "yyy");
// Bad command shouldn't create new tab.
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("tab"), &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY( !QString::fromUtf8(stdoutActual)
.contains(QRegularExpression("^" + QRegularExpression::escape(testTab(1)) + "$")) );
}
void Tests::badSessionName()
{
RUN_EXPECT_ERROR("-s" << "max_16_characters_in_session_name_allowed" << "", CommandBadSyntax);
RUN_EXPECT_ERROR("-s" << "spaces disallowed" << "", CommandBadSyntax);
}
void Tests::commandCatchExceptions()
{
#if QT_VERSION < QT_VERSION_CHECK(5,12,0)
SKIP("Internal exceptions are not handled well before Qt 5.12.");
#endif
RUN("try { removeTab('MISSING') } catch(e) { print(e) }",
"Error: Tab with given name doesn't exist!");
}
| 3,744
|
C++
|
.cpp
| 94
| 34.276596
| 113
| 0.65051
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,127
|
tests_classes.cpp
|
hluk_CopyQ/src/tests/tests_classes.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "test_utils.h"
#include "tests.h"
#include "tests_common.h"
#include "common/appconfig.h"
void Tests::classByteArray()
{
RUN("ByteArray", "");
RUN("ByteArray('test')", "test");
RUN("ByteArray(ByteArray('test'))", "test");
RUN("typeof(ByteArray('test'))", "object\n");
RUN("ByteArray('test') instanceof ByteArray", "true\n");
RUN("b = ByteArray('0123'); b.chop(2); b", "01");
RUN("ByteArray('0123').equals(ByteArray('0123'))", "true\n");
RUN("ByteArray('0123').left(3)", "012");
RUN("ByteArray('0123').mid(1, 2)", "12");
RUN("ByteArray('0123').mid(1)", "123");
RUN("ByteArray('0123').right(3)", "123");
RUN("ByteArray('0123').remove(1, 2)", "03");
RUN("ByteArray(' 01 23 ').simplified()", "01 23");
RUN("ByteArray('0123').toBase64()", "MDEyMw==");
RUN("ByteArray('ABCd').toLower()", "abcd");
RUN("ByteArray('abcD').toUpper()", "ABCD");
RUN("ByteArray(' 01 23 ').trimmed()", "01 23");
RUN("b = ByteArray('0123'); b.truncate(2); b", "01");
RUN("ByteArray('0123').toLatin1String() == '0123'", "true\n");
RUN("ByteArray('0123').valueOf() == '0123'", "true\n");
RUN("ByteArray(8).size()", "8\n");
RUN("b = ByteArray(); b.length = 10; b.length", "10\n");
// ByteArray implicitly converts to str.
RUN("ByteArray('test') == 'test'", "true\n");
RUN("ByteArray('test1') == 'test2'", "false\n");
RUN("ByteArray('test') === 'test'", "false\n");
RUN("ByteArray('a') + 'b'", "ab\n");
}
void Tests::classFile()
{
RUN("var f = new File('/copyq_missing_file'); f.exists()", "false\n");
}
void Tests::classDir()
{
RUN("var d = new Dir('/missing_directory/')"
"; d.exists()"
, "false\n"
);
const auto home = QDir::homePath();
RUN("Dir().homePath()", home + "\n");
RUN("Dir().home().path()", home + "\n");
const auto root = QDir::rootPath();
RUN("Dir().rootPath()", root + "\n");
RUN("Dir().root().path()", root + "\n");
const auto temp = QDir::tempPath();
RUN("Dir().tempPath()", temp + "\n");
RUN("Dir().temp().path()", temp + "\n");
RUN("Dir().separator()", QString(QDir::separator()) + "\n");
QTemporaryDir tmpDir;
QVERIFY(tmpDir.isValid());
QDir dir(tmpDir.path());
const auto path = dir.path();
const auto args = QString::fromLatin1("var d = new Dir('%1')").arg(path);
RUN(args << "d.exists()", "true\n");
RUN(args << "d.isReadable()", "true\n");
RUN(args << "d.isAbsolute()", "true\n");
RUN(args << "d.isRelative()", "false\n");
RUN(args << "d.absolutePath()", path + "\n");
RUN(args << "d.path()", path + "\n");
RUN(args << "d.makeAbsolute()", "true\n");
RUN(args << "d.mkdir('test')", "true\n");
QVERIFY( QDir(dir.filePath("test")).exists() );
RUN(args << "d.exists('test')", "true\n");
RUN(args << "d.mkpath('a/b/c')", "true\n");
QVERIFY( QDir(dir.filePath("a/b/c")).exists() );
RUN(args << "d.exists('a/b/c')", "true\n");
RUN(args << "d.filePath('a/b/c')", dir.filePath("a/b/c") + "\n");
RUN(args << "d.relativeFilePath('" + path + "/a/b/c')", "a/b/c\n");
RUN("Dir('" + path + "/test/../a//b/c/..').canonicalPath()", dir.filePath("a/b") + "\n");
RUN(args << "d.setPath('" + path + "/a/b/c')" << "d.path()", dir.filePath("a/b/c") + "\n");
RUN(args << "d.cd('a')" << "d.cd('b')", "true\n");
RUN(args << "d.cd('x')", "false\n");
RUN(args << "d.cd('a')" << "d.cd('b')" << "d.path()", dir.filePath("a/b") + "\n");
RUN(args << "d.cd('a')" << "d.cd('..')" << "d.path()", path + "\n");
RUN(args << "d.cd('a')" << "d.cdUp()" << "d.path()", path + "\n");
RUN(args << "d.count()", QString::fromLatin1("%1\n").arg(dir.count()));
RUN(args << "d.dirName()", QString::fromLatin1("%1\n").arg(dir.dirName()));
RUN(args << "d.match(['a*'], 'test')", "false\n");
RUN(args << "d.match(['t*'], 'test')", "true\n");
RUN(args << "d.entryList()", ".\n..\na\ntest\n");
RUN(args << "d.entryList(['t*'])", "test\n");
RUN(args << "d.entryList(['t?st', 'a*'])", "a\ntest\n");
RUN(args << "d.setNameFilters(['t?st', 'a*'])" << "d.nameFilters()", "t?st\na*\n");
QFile f(dir.filePath("test.txt"));
QVERIFY( f.open(QIODevice::WriteOnly) );
f.close();
RUN(args << "d.exists('test.txt')", "true\n");
RUN(args << "d.absoluteFilePath('test.txt')", dir.filePath("test.txt") + "\n");
RUN(args << "d.rename('test.txt', 'test2.txt')", "true\n");
RUN(args << "d.exists('test2.txt')", "true\n");
RUN(args << "d.remove('test2.txt')", "true\n");
RUN(args << "d.exists('test2.txt')", "false\n");
RUN(args << "d.rmdir('test')", "true\n");
RUN(args << "d.exists('test')", "false\n");
RUN("Dir().cleanPath('/a//b/../c/')", QDir::cleanPath("/a//b/../c/") + "\n");
}
void Tests::classTemporaryFile()
{
RUN("var f = new TemporaryFile(); f.open()", "true\n");
QByteArray err;
for ( const auto autoRemove : {true, false} ) {
QByteArray fileName;
const auto script =
QString(R"(
var f = new TemporaryFile()
if (!f.open())
throw 'Failed to open temporary file'
f.setAutoRemove(%1)
print(f.fileName())
)").arg(autoRemove);
run(Args() << script, &fileName, &err);
QVERIFY2( testStderr(err), err );
QFile f( QString::fromUtf8(fileName) );
QVERIFY( f.exists() != autoRemove );
if (!autoRemove)
f.remove();
}
QByteArray fileName;
const auto scriptWrite = R"(
var f = new TemporaryFile()
if (!f.open())
throw 'Failed to open temporary file'
if (!f.write('LINE'))
throw 'Failed to write to temporary file'
f.setAutoRemove(false)
print(f.fileName())
)";
run(Args() << scriptWrite, &fileName);
QVERIFY2( testStderr(err), err );
QVERIFY( QFile::exists(QString::fromUtf8(fileName)) );
QByteArray out;
const auto scriptRead = R"(
var f = new File(str(input()))
if (!f.openReadOnly())
throw 'Failed to open file'
print(''
+ ' exists()=' + str(f.exists())
+ ' isOpen()=' + str(f.isOpen())
+ ' isReadable()=' + str(f.isReadable())
+ ' isWritable()=' + str(f.isWritable())
+ ' size()=' + str(f.size())
+ ' readAll()=' + str(f.readAll())
+ ' atEnd()=' + str(f.atEnd())
+ ' seek(0)=' + str(f.seek(0))
+ ' read(1)=' + str(f.read(1))
+ ' pos()=' + str(f.pos())
+ ' peek(1)=' + str(f.peek(1))
+ ' readLine()=' + str(f.readLine())
)
)";
const QByteArray expectedOut =
" exists()=true"
" isOpen()=true"
" isReadable()=true"
" isWritable()=false"
" size()=4"
" readAll()=LINE"
" atEnd()=true"
" seek(0)=true"
" read(1)=L"
" pos()=1"
" peek(1)=I"
" readLine()=INE";
run(Args() << scriptRead, &out, &err, fileName);
QVERIFY2( testStderr(err), err );
QCOMPARE(out, expectedOut);
const auto scriptRemove = R"(
var f = new File(str(input()))
if (!f.remove())
throw 'Failed to remove file'
)";
run(Args() << scriptRemove, &out, &err, fileName);
QVERIFY2( testStderr(err), err );
QCOMPARE(QByteArray(), out);
QVERIFY( !QFile::exists(QString::fromUtf8(fileName)) );
RUN("TemporaryFile().autoRemove()", "true\n");
RUN("TemporaryFile().fileTemplate()", QDir::temp().filePath("copyq.test.XXXXXX") + "\n");
}
void Tests::classItemSelection()
{
const auto tab1 = testTab(1);
const Args args = Args("tab") << tab1 << "separator" << ",";
const QString outRows("ItemSelection(tab=\"" + tab1 + "\", rows=[%1])\n");
RUN(args << "add" << "C" << "B" << "A", "");
RUN(args << "ItemSelection().length", "0\n");
RUN("ItemSelection('" + tab1 + "').length", "0\n");
RUN(args << "ItemSelection().selectAll().length", "3\n");
RUN("ItemSelection('" + tab1 + "').selectAll().length", "3\n");
RUN(args << "a = ItemSelection(); b = a; a === b", "true\n");
RUN(args << "a = ItemSelection(); b = a.selectAll(); a === b", "true\n");
RUN(args << "ItemSelection().selectAll().str()", outRows.arg("0..2"));
RUN(args << "ItemSelection().selectRemovable().str()", outRows.arg("0..2"));
RUN(args << "ItemSelection().selectRemovable().removeAll().str()", outRows.arg(""));
RUN(args << "read(0,1,2)", ",,");
RUN(args << "add" << "C" << "B" << "A", "");
RUN(args << "ItemSelection().select(/A|C/).str()", outRows.arg("0,2"));
RUN(args << "ItemSelection().select(/a|c/i).str()", outRows.arg("0,2"));
RUN(args << "ItemSelection().select(/A/).select(/C/).str()", outRows.arg("0,2"));
RUN(args << "ItemSelection().select(/C/).select(/A/).str()", outRows.arg("2,0"));
RUN(args << "ItemSelection().select(/A|C/).invert().str()", outRows.arg("1"));
RUN(args << "ItemSelection().select(/A|C/).deselectIndexes([0]).str()", outRows.arg("2"));
RUN(args << "ItemSelection().select(/A|C/).deselectIndexes([1]).str()", outRows.arg("0"));
RUN(args << "ItemSelection().select(/A|C/).deselectIndexes([0,1]).str()", outRows.arg(""));
RUN(args << "ItemSelection().select(/A|C/).deselectSelection(ItemSelection().select(/A/)).str()", outRows.arg("2"));
RUN(args << "ItemSelection().select(/A|C/).deselectSelection(ItemSelection().select(/C/)).str()", outRows.arg("0"));
RUN(args << "ItemSelection().select(/A|C/).deselectSelection(ItemSelection().selectAll()).str()", outRows.arg(""));
RUN(args << "a = ItemSelection().select(/a/i); b = a.copy(); a !== b", "true\n");
RUN(args << "a = ItemSelection().select(/a/i); b = a.copy(); a.str() == b.str()", "true\n");
RUN(args << "a = ItemSelection().select(/a|b/i); b = a.copy(); b.select(/C/); [a.rows(), '', b.rows()]", "0\n1\n\n0\n1\n2\n");
RUN(args << "s = ItemSelection().selectAll(); insert(1, 'X'); insert(3, 'Y'); s.invert().str()", outRows.arg("1,3"));
RUN(args << "ItemSelection().select(/a/i).invert().removeAll().str()", outRows.arg(""));
RUN(args << "read(0,1,2)", "A,,");
RUN(args << "ItemSelection().selectAll().removeAll().str()", outRows.arg(""));
RUN(args << "read(0,1,2)", ",,");
RUN(args << "write('application/x-tst', 'ghi')", "");
RUN(args << "write('application/x-tst', 'def')", "");
RUN(args << "write('application/x-tst', 'abc')", "");
RUN(args << "read('application/x-tst',0,1,2)", "abc,def,ghi");
RUN(args << "ItemSelection().select(/e/, 'application/x-tst').str()", outRows.arg("1"));
RUN(args << "ItemSelection().select(/e/, 'application/x-tst').removeAll().str()", outRows.arg(""));
RUN(args << "read('application/x-tst',0,1,2)", "abc,ghi,");
RUN(args << "ItemSelection().selectAll().itemAtIndex(0)['application/x-tst']", "abc");
RUN(args << "ItemSelection().selectAll().itemAtIndex(1)['application/x-tst']", "ghi");
RUN(args << "ItemSelection().select(/h/, 'application/x-tst').itemAtIndex(0)['application/x-tst']", "ghi");
RUN(args << "ItemSelection().select(/h/, 'application/x-tst').itemAtIndex(1)['application/x-tst'] == undefined", "true\n");
RUN(args << "ItemSelection().select(/ghi/, 'application/x-tst').setItemAtIndex(0, {'application/x-tst': 'def'}).str()",
outRows.arg("1"));
RUN(args << "read('application/x-tst',0,1,2)", "abc,def,");
RUN(args << "d = ItemSelection().selectAll().items(); [d.length, str(d[0]['application/x-tst']), str(d[1]['application/x-tst'])]", "2\nabc\ndef\n");
RUN(args << "ItemSelection().selectAll().setItems([{'application/x-tst': 'xyz'}]).str()", outRows.arg("0,1"));
RUN(args << "read('application/x-tst',0,1,2)", "xyz,def,");
RUN(args << "ItemSelection().selectAll().setItemsFormat(mimeItemNotes, 'test1').str()", outRows.arg("0,1"));
RUN(args << "read(mimeItemNotes,0,1,2)", "test1,test1,");
RUN(args << "read('application/x-tst',0,1,2)", "xyz,def,");
RUN(args << "ItemSelection().selectAll().setItems([{'application/x-tst': ByteArray('abc')}]).str()", outRows.arg("0,1"));
RUN(args << "read('application/x-tst',0,1,2)", "abc,def,");
RUN(args << "ItemSelection().selectAll().setItemsFormat(mimeItemNotes, ByteArray('test2')).str()", outRows.arg("0,1"));
RUN(args << "read(mimeItemNotes,0,1,2)", "test2,test2,");
RUN(args << "read('application/x-tst',0,1,2)", "abc,def,");
RUN(args << "ItemSelection().selectAll().itemsFormat(mimeItemNotes).map(str)", "test2\ntest2\n");
RUN(args << "ItemSelection().selectAll().itemsFormat('application/x-tst').map(str)", "abc\ndef\n");
RUN(args << "ItemSelection().selectAll().itemsFormat(ByteArray('application/x-tst')).map(str)", "abc\ndef\n");
RUN(args << "ItemSelection().selectAll().setItemsFormat(mimeItemNotes, undefined).str()", outRows.arg("0,1"));
RUN(args << "read(mimeItemNotes,0,1,2)", ",,");
RUN(args << "read('application/x-tst',0,1,2)", "abc,def,");
RUN(args << "ItemSelection().selectAll().removeAll().str()", outRows.arg(""));
RUN(args << "add" << "C" << "B" << "A", "");
RUN(args << "ItemSelection().select(/C/).move(1).str()", outRows.arg("1"));
RUN(args << "read(0,1,2)", "A,C,B");
RUN(args << "ItemSelection().select(/B/).select(/C/).move(1).str()", outRows.arg("2,1"));
RUN(args << "read(0,1,2)", "A,C,B");
RUN(args << "ItemSelection().select(/A/).move(2).str()", outRows.arg("1"));
RUN(args << "read(0,1,2)", "C,A,B");
RUN(args << "ItemSelection().select(/C/).select(/B/).move(2).str()", outRows.arg("1,2"));
RUN(args << "read(0,1,2)", "A,C,B");
RUN(args << "change(1, mimeItemNotes, 'NOTE'); read(mimeItemNotes,0,1,2)", ",NOTE,");
RUN(args << "ItemSelection().select(/.*/, mimeItemNotes).str()", outRows.arg("1"));
RUN(args << "ItemSelection().select(undefined, mimeItemNotes).str()", outRows.arg("0,2"));
// Match nothing if select() argument is not a regular expression.
RUN(args << "add" << "", "");
RUN(args << "ItemSelection().select('A').str()", outRows.arg(""));
}
void Tests::classItemSelectionGetCurrent()
{
const auto tab1 = testTab(1);
const Args args = Args("tab") << tab1 << "separator" << ",";
RUN("ItemSelection().tab", "CLIPBOARD\n");
RUN(args << "ItemSelection().tab", tab1 + "\n");
RUN(args << "ItemSelection().current().tab", "CLIPBOARD\n");
RUN(args << "ItemSelection().current().str()", "ItemSelection(tab=\"CLIPBOARD\", rows=[])\n");
RUN("setCurrentTab" << tab1, "");
RUN(args << "ItemSelection().current().tab", tab1 + "\n");
RUN(args << "ItemSelection().current().str()", "ItemSelection(tab=\"" + tab1 + "\", rows=[])\n");
RUN(args << "add" << "C" << "B" << "A", "");
RUN(args << "ItemSelection().current().str()", "ItemSelection(tab=\"" + tab1 + "\", rows=[0])\n");
RUN("setCommands([{name: 'test', inMenu: true, shortcuts: ['Ctrl+F1'], cmd: 'copyq: add(ItemSelection().current().str())'}])", "");
RUN("keys" << "CTRL+F1", "");
WAIT_ON_OUTPUT(args << "read(0)", "ItemSelection(tab=\"" + tab1 + "\", rows=[0])");
RUN("keys" << "END" << "SHIFT+UP" << "CTRL+F1", "");
WAIT_ON_OUTPUT(args << "read(0)", "ItemSelection(tab=\"" + tab1 + "\", rows=[2,3])");
}
void Tests::classItemSelectionByteArray()
{
const auto tab1 = testTab(1);
const Args args = Args("tab") << tab1 << "separator" << ",";
RUN("setCurrentTab" << tab1, "");
RUN(args << "add" << "C" << "B" << "A", "");
RUN(args << "ByteArray(ItemSelection().selectAll().itemAtIndex(0)[mimeText])", "A");
RUN(args << "str(ItemSelection().selectAll().itemAtIndex(0)[mimeText])", "A\n");
RUN(args << "write(0, [ItemSelection().selectAll().itemAtIndex(2)])"
<< "read(mimeText, 0)", "C");
}
void Tests::classItemSelectionSort()
{
const auto tab1 = testTab(1);
const Args args = Args("tab") << tab1 << "separator" << ",";
const QString outRows("ItemSelection(tab=\"" + tab1 + "\", rows=[%1])\n");
RUN("setCurrentTab" << tab1, "");
RUN(args << "add(2,5,1,3,4)", "");
RUN(args << "read(0,1,2,3,4)", "4,3,1,5,2");
const auto script = R"(
var sel = ItemSelection().selectAll();
const texts = sel.itemsFormat(mimeText);
sel.sort(function(i,j){
return texts[i] < texts[j];
});
sel.str();
)";
RUN(args << script, outRows.arg("3,2,0,4,1"));
RUN(args << "read(0,1,2,3,4)", "1,2,3,4,5");
RUN(args << "size", "5\n");
}
void Tests::classSettings()
{
TemporaryFile configFile;
const QString fileName = configFile.fileName();
RUN("eval" << "s=Settings(str(arguments[1])); print(s.fileName())" << fileName, fileName);
RUN("eval" << "s=Settings(str(arguments[1])); s.isWritable() === true" << fileName, "true\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.contains('o1')" << fileName, "false\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.setValue('o1', 1); s.sync(); s.contains('o1')" << fileName, "true\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.value('o1')" << fileName, "1\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.setValue('o2', 2)" << fileName, "");
RUN("eval" << "s=Settings(str(arguments[1])); s.value('o2')" << fileName, "2\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.setValue('o2', [1,2,3])" << fileName, "");
RUN("eval" << "s=Settings(str(arguments[1])); s.value('o2')[0]" << fileName, "1\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.value('o2')[1]" << fileName, "2\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.value('o2')[2]" << fileName, "3\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.setValue('g1/o3', true)" << fileName, "");
RUN("eval" << "s=Settings(str(arguments[1])); s.value('g1/o3')" << fileName, "true\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.childKeys()" << fileName, "o1\no2\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.allKeys()" << fileName, "g1/o3\no1\no2\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.beginGroup('g1'); s.group()" << fileName, "g1\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.beginGroup('g1'); s.setValue('g1.2/o4', 'test')" << fileName, "");
RUN("eval" << "s=Settings(str(arguments[1])); s.beginGroup('g1'); s.childGroups()" << fileName, "g1.2\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.beginGroup('g1'); s.endGroup(); s.childGroups()" << fileName, "g1\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.value('g1/g1.2/o4')" << fileName, "test\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.allKeys()" << fileName, "g1/g1.2/o4\ng1/o3\no1\no2\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.remove('g1/g1.2/o4'); s.allKeys()" << fileName, "g1/o3\no1\no2\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.beginWriteArray('a1', 3); s.setArrayIndex(1); s.setValue('o1', 'v1'); s.endArray()" << fileName, "");
RUN("eval" << "s=Settings(str(arguments[1])); s.beginReadArray('a1')" << fileName, "3\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.beginReadArray('a1'); s.setArrayIndex(1); s.value('o1');" << fileName, "v1\n");
RUN("eval" << "s=Settings(str(arguments[1])); s.clear(); s.allKeys()" << fileName, "");
QVERIFY(QFile::remove(fileName));
QVERIFY(!QFile::exists(fileName));
RUN("eval" << "s=Settings(str(arguments[1])); s.setValue('o1', 1); s.sync(); File(str(arguments[1])).exists()" << fileName, "true\n");
QVERIFY(QFile::exists(fileName));
QVERIFY(QFile::remove(fileName));
QVERIFY(!QFile::exists(fileName));
RUN("eval" << "s=Settings(str(arguments[1])); s.setValue('o1', 1)" << fileName, "");
QVERIFY(QFile::exists(fileName));
const QString appConfigFileName = AppConfig().settings().fileName();
RUN("Settings().fileName()", QStringLiteral("%1\n").arg(appConfigFileName));
RUN("Settings().value('Options/tabs')", QStringLiteral("%1\n").arg(clipboardTabName));
}
void Tests::calledWithInstance()
{
// These would fail with the old deprecated Qt Script module.
RUN("f=ByteArray().size; f()", "0\n");
RUN("f=Dir().path; f()", ".\n");
RUN("f=File('test').fileName; f()", "test\n");
RUN("f=TemporaryFile().autoRemove; f()", "true\n");
}
| 20,520
|
C++
|
.cpp
| 369
| 49.533875
| 153
| 0.560112
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,128
|
tests.cpp
|
hluk_CopyQ/src/tests/tests.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "tests.h"
#include "test_utils.h"
#include "tests_common.h"
#include "common/action.h"
#include "common/appconfig.h"
#include "common/client_server.h"
#include "common/common.h"
#include "common/config.h"
#include "common/log.h"
#include "common/settings.h"
#include "common/shortcuts.h"
#include "common/sleeptimer.h"
#include "common/textdata.h"
#include "item/itemfactory.h"
#include "item/itemwidget.h"
#include "item/serialize.h"
#include "gui/tabicons.h"
#include "platform/platformclipboard.h"
#include "platform/platformnativeinterface.h"
#include <QClipboard>
#include <QDebug>
#include <QDir>
#include <QElapsedTimer>
#include <QFile>
#include <QFileInfo>
#include <QGuiApplication>
#include <QMap>
#include <QProcess>
#include <QRegularExpression>
#include <QTest>
#include <QTimer>
#include <memory>
namespace {
class PerformanceTimer final {
public:
PerformanceTimer() {
m_timer.start();
}
void printPerformance(const char *label, const QStringList &arguments = QStringList()) {
const auto elapsedMs = m_timer.elapsed();
if (elapsedMs > 500)
qWarning() << "--- PERFORMANCE ---" << elapsedMs << "ms:" << label << arguments;
m_timer.start();
}
private:
QElapsedTimer m_timer;
};
QByteArray decorateOutput(const QByteArray &label, const QByteArray &stderrOutput)
{
QByteArray output = "\n" + stderrOutput;
output.replace('\n', "\n ");
output.prepend("\n " + label + ":");
return output;
}
class TestInterfaceImpl final : public TestInterface {
public:
TestInterfaceImpl()
: m_server(nullptr)
, m_env(QProcessEnvironment::systemEnvironment())
{
m_env.insert("COPYQ_LOG_LEVEL", "DEBUG");
m_env.insert("COPYQ_SESSION_COLOR", defaultSessionColor);
m_env.insert("COPYQ_SESSION_NAME", "TEST");
m_env.insert("COPYQ_CLIPBOARD_COPY_TIMEOUT_MS", "2000");
}
~TestInterfaceImpl()
{
stopServer();
}
QByteArray startServer() override
{
if ( isServerRunning() )
return "Server is already running.";
if ( !removeLogFiles() )
return "Failed to remove log files";
m_server.reset(new QProcess);
if ( !startTestProcess(m_server.get(), QStringList(), QIODevice::NotOpen) ) {
return QString::fromLatin1("Failed to launch \"%1\": %2")
.arg(QCoreApplication::applicationFilePath())
.arg(m_server->errorString())
.toUtf8();
}
m_server->closeReadChannel(QProcess::StandardOutput);
RETURN_ON_ERROR( readServerErrors(), "Failed to start server" );
return waitForServerToStart();
}
QByteArray stopServer() override
{
if ( !isServerRunning() )
return "Server is not running";
QByteArray errors;
const int exitCode = run(Args("exit"), nullptr, &errors);
if ( !testStderr(errors) || exitCode != 0 ) {
return "Command 'exit' failed."
+ printClienAndServerStderr(errors, exitCode);
}
return waitForServerToStop();
}
QByteArray waitForServerToStop() override
{
PerformanceTimer perf;
// Process events in case we own clipboard and the new process requests the contents.
SleepTimer t(30000);
while ( m_server->state() != QProcess::NotRunning && !m_server->waitForFinished(50) && t.sleep() ) {}
perf.printPerformance("stopServer");
if ( m_server->state() != QProcess::NotRunning ) {
qWarning() << "terminating server process";
m_server->terminate();
if ( !m_server->waitForFinished() ) {
qWarning() << "killing server process";
terminateProcess(m_server.get());
}
return "Failed to close server properly!" + readServerErrors(ReadAllStderr);
}
return readServerErrors();
}
bool isServerRunning() override
{
return m_server != nullptr && m_server->state() == QProcess::Running;
}
int run(const QStringList &arguments, QByteArray *stdoutData = nullptr,
QByteArray *stderrData = nullptr, const QByteArray &in = QByteArray(),
const QStringList &environment = QStringList()) override
{
if (stdoutData != nullptr)
stdoutData->clear();
if (stderrData != nullptr)
stderrData->clear();
QProcess p;
if (!startTestProcess(&p, arguments, QIODevice::ReadWrite, environment))
return -1;
if (in != KEEP_STDIN_OPEN) {
if ( p.write(in) != in.size() )
return -2;
p.closeWriteChannel();
}
if (stdoutData == nullptr)
p.closeReadChannel(QProcess::StandardOutput);
if (stderrData == nullptr)
p.closeReadChannel(QProcess::StandardError);
PerformanceTimer perf;
SleepTimer t(waitClientRun);
while ( p.state() == QProcess::Running ) {
if ( stdoutData != nullptr ) {
const auto out = p.readAllStandardOutput();
stdoutData->append(out);
}
if (stderrData != nullptr) {
const auto err = p.readAllStandardError();
stderrData->append(err);
}
if ( !t.sleep() ) {
qWarning() << "Client process timed out" << arguments;
return -1;
}
}
if (stderrData != nullptr) {
stderrData->append(p.readAllStandardError());
stderrData->replace('\r', "");
}
if (stdoutData != nullptr) {
stdoutData->append(p.readAllStandardOutput());
stdoutData->replace('\r', "");
}
perf.printPerformance("run", arguments);
return p.exitCode();
}
QByteArray printClienAndServerStderr(const QByteArray &clientStderr, int exitCode)
{
return "\n Client exit code: " + QByteArray::number(exitCode) + "\n"
+ decorateOutput("Client STDERR", clientStderr)
+ readServerErrors(ReadAllStderr);
}
QByteArray runClient(const QStringList &arguments, const QByteArray &stdoutExpected,
const QByteArray &input = QByteArray()) override
{
if (!isServerRunning() )
return "Server is not running!" + readServerErrors(ReadAllStderr);
QByteArray stdoutActual;
QByteArray stderrActual;
const int exitCode = run(arguments, &stdoutActual, &stderrActual, input);
if ( !testStderr(stderrActual) || exitCode != 0 )
return printClienAndServerStderr(stderrActual, exitCode);
if (stdoutActual != stdoutExpected) {
return "Test failed:"
+ decorateOutput("Unexpected output", stdoutActual)
+ decorateOutput("Expected output", stdoutExpected)
+ printClienAndServerStderr(stderrActual, exitCode);
}
return readServerErrors();
}
QByteArray runClientWithError(const QStringList &arguments, int expectedExitCode,
const QByteArray &stderrContains = QByteArray()) override
{
Q_ASSERT(expectedExitCode != 0);
if ( !isServerRunning() )
return "Server is not running!" + readServerErrors(ReadAllStderr);
QByteArray stdoutActual;
QByteArray stderrActual;
const int exitCode = run(arguments, &stdoutActual, &stderrActual);
if ( testStderr(stderrActual) ) {
return "Test failed: Expected error output on client side."
+ printClienAndServerStderr(stderrActual, exitCode);
}
if ( !stdoutActual.isEmpty() ) {
return "Test failed: Expected empty output."
+ decorateOutput("Unexpected output", stdoutActual)
+ printClienAndServerStderr(stderrActual, exitCode);
}
if (exitCode != expectedExitCode) {
return QString::fromLatin1("Test failed: Unexpected exit code %1; expected was %2")
.arg(exitCode)
.arg(expectedExitCode)
.toUtf8()
+ printClienAndServerStderr(stderrActual, exitCode);
}
if ( !stderrActual.contains(stderrContains) ) {
return QString::fromLatin1("Test failed: Expected error output on client side with \"%1\".")
.arg(QString::fromUtf8(stderrContains)).toUtf8()
+ printClienAndServerStderr(stderrActual, exitCode);
}
return readServerErrors(ReadErrorsWithoutScriptException);
}
QByteArray getClipboard(const QString &mime = QString("text/plain"), ClipboardMode mode = ClipboardMode::Clipboard)
{
return clipboard()->data(mode, QStringList(mime)).value(mime).toByteArray();
}
QByteArray setClipboard(const QVariantMap &data, ClipboardMode mode) override
{
if ( !data.isEmpty() ) {
// Wait for clipboard monitor
QByteArray error;
SleepTimer t(8000);
do {
error = runClient(
Args("monitoring() == isClipboardMonitorRunning()"),
QByteArrayLiteral("true\n"));
} while (!error.isEmpty() && t.sleep());
if (!error.isEmpty())
return "Clipboard monitor is not running:" + error;
}
clipboard()->setData(mode, data);
return {};
}
QByteArray setClipboard(const QByteArray &bytes, const QString &mime, ClipboardMode mode) override
{
if ( const QByteArray error = setClipboard(createDataMap(mime, bytes), mode);
!error.isEmpty() )
{
return error;
}
return verifyClipboard(bytes, mime);
}
QByteArray verifyClipboard(const QByteArray &data, const QString &mime, bool exact = true) override
{
// Due to image conversions in clipboard check only png.
if ( mime.startsWith(QStringLiteral("image/")) && mime != QStringLiteral("image/png") )
return verifyClipboard("PNG", QStringLiteral("image/png"), false);
PerformanceTimer perf;
SleepTimer t(5000);
QByteArray actualBytes;
do {
actualBytes = getClipboard(mime);
if ( exact ? actualBytes == data : actualBytes.contains(data) ) {
perf.printPerformance("verifyClipboard", QStringList() << QString::fromUtf8(data) << mime);
waitFor(waitMsSetClipboard);
RETURN_ON_ERROR( readServerErrors(), "Failed to set or test clipboard content" );
return QByteArray();
}
} while (t.sleep());
return QString::fromLatin1("Unexpected clipboard data for MIME \"%1\":")
.arg(mime).toUtf8()
+ decorateOutput("Unexpected content", actualBytes)
+ decorateOutput("Expected content", data)
+ readServerErrors(ReadAllStderr);
}
QByteArray readServerErrors(ReadStderrFlag flag = ReadErrors) override
{
if (m_server) {
QCoreApplication::processEvents();
QByteArray output = readLogFile(maxReadLogSize);
if ( flag == ReadAllStderr || !testStderr(output, flag) )
return decorateOutput("Server STDERR", output);
}
return QByteArray();
}
QByteArray getClientOutput(const QStringList &arguments, QByteArray *stdoutActual) override
{
stdoutActual->clear();
QByteArray stderrActual;
int exitCode = run(arguments, stdoutActual, &stderrActual);
if ( !testStderr(stderrActual) || exitCode != 0 )
return printClienAndServerStderr(stderrActual, exitCode);
RETURN_ON_ERROR( readServerErrors(), "Failed getting client output" );
return "";
}
QByteArray waitOnOutput(const QStringList &arguments, const QByteArray &stdoutExpected) override
{
PerformanceTimer perf;
QByteArray stdoutActual;
SleepTimer t_(8000);
do {
RETURN_ON_ERROR( getClientOutput(arguments, &stdoutActual), "Failed to wait on client output" );
} while (stdoutActual != stdoutExpected && t_.sleep());
if (stdoutActual == stdoutExpected)
return QByteArray();
return QString::fromLatin1("Unexpected output for command \"%1\":")
.arg(arguments.join(' ')).toUtf8()
+ decorateOutput("Unexpected content", stdoutActual)
+ decorateOutput("Expected content", stdoutExpected)
+ readServerErrors(ReadAllStderr);
}
QByteArray cleanupTestCase() override
{
return cleanup();
}
QByteArray initTestCase() override
{
return QByteArray();
}
QByteArray init() override
{
RETURN_ON_ERROR( cleanup(), "Failed to cleanup" );
if ( isServerRunning() )
RETURN_ON_ERROR( stopServer(), "Failed to stop server" );
// Remove all configuration files and tab data.
const auto settingsPath = settingsDirectoryPath();
Q_ASSERT( !settingsPath.isEmpty() );
QDir settingsDir(settingsPath);
const QStringList settingsFileFilters("copyq.test*");
// Omit using dangerous QDir::removeRecursively().
for ( const auto &fileName : settingsDir.entryList(settingsFileFilters) ) {
const auto path = settingsDir.absoluteFilePath(fileName);
QFile settingsFile(path);
if ( settingsFile.exists() && !settingsFile.remove() ) {
return QString::fromLatin1("Failed to remove settings file \"%1\": %2")
.arg(settingsPath, settingsFile.errorString())
.toUtf8();
}
}
// Update settings for tests.
{
Settings settings;
settings.clear();
settings.beginGroup("Options");
settings.setValue( Config::clipboard_tab::name(), clipboardTabName );
settings.setValue( Config::close_on_unfocus::name(), false );
// Exercise limiting rows in Process Manager dialog when testing.
settings.setValue( Config::max_process_manager_rows::name(), 4 );
settings.endGroup();
if ( !m_settings.isEmpty() ) {
const bool pluginsTest = m_testId != "CORE";
if (pluginsTest) {
settings.beginGroup("Plugins");
settings.beginGroup(m_testId);
}
for (auto it = m_settings.constBegin(); it != m_settings.constEnd(); ++it)
settings.setValue( it.key(), it.value() );
if (pluginsTest) {
settings.endGroup();
settings.endGroup();
}
}
}
verifyConfiguration();
// Clear clipboard.
RETURN_ON_ERROR( setClipboard({}, ClipboardMode::Clipboard), "Failed to reset clipboard" );
#ifdef HAS_MOUSE_SELECTIONS
RETURN_ON_ERROR( setClipboard({}, ClipboardMode::Selection), "Failed to reset selection" );
#endif
RETURN_ON_ERROR( startServer(), "Failed to initialize server" );
// Always show main window first so that the results are consistent with desktop environments
// where user cannot hide main window (tiling window managers without tray).
RETURN_ON_ERROR( runClient(Args("show"), ""), "Failed to show main window" );
return QByteArray();
}
QByteArray cleanup() override
{
addFailedTest();
return QByteArray();
}
QString shortcutToRemove() override
{
return ::shortcutToRemove();
}
void setEnv(const QString &name, const QString &value) override
{
m_env.insert(name, value);
}
bool writeOutErrors(const QByteArray &errors) override
{
if (errors.isEmpty())
return false;
QFile ferr;
ferr.open(stderr, QIODevice::WriteOnly);
ferr.write(errors);
ferr.write("\n");
ferr.close();
return true;
}
void setupTest(const QString &id, const QVariant &settings)
{
m_testId = id;
m_settings = settings.toMap();
m_env.insert("COPYQ_TEST_ID", id);
}
int runTests(QObject *testObject, int argc = 0, char **argv = nullptr)
{
int exitCode = QTest::qExec(testObject, argc, argv);
const int maxRuns = m_env.value("COPYQ_TESTS_RERUN_FAILED", "0").toInt();
for (int runCounter = 0; exitCode != 0 && !m_failed.isEmpty() && runCounter < maxRuns; ++runCounter) {
qInfo() << QString::fromLatin1("Rerunning %1 failed tests (%2/%3): %4")
.arg(m_failed.size())
.arg(runCounter + 1)
.arg(maxRuns)
.arg(m_failed.join(", "));
QStringList args = m_failed;
m_failed.clear();
args.prepend( QString::fromUtf8(argv[0]) );
exitCode = QTest::qExec(testObject, args);
}
m_failed.clear();
return exitCode;
}
private:
void addFailedTest()
{
if ( QTest::currentTestFailed() )
m_failed.append( QString::fromUtf8(QTest::currentTestFunction()) );
}
void verifyConfiguration()
{
AppConfig appConfig;
QCOMPARE( appConfig.option<Config::close_on_unfocus>(), false );
QCOMPARE( appConfig.option<Config::clipboard_tab>(), QString(clipboardTabName) );
QCOMPARE( appConfig.option<Config::maxitems>(), Config::maxitems::defaultValue() );
QCOMPARE( savedTabs(), QStringList(clipboardTabName) );
QCOMPARE( AppConfig().option<Config::tabs>(), QStringList() );
}
bool startTestProcess(QProcess *p, const QStringList &arguments,
QIODevice::OpenMode mode = QIODevice::ReadWrite,
const QStringList &environment = QStringList())
{
if ( environment.isEmpty() ) {
p->setProcessEnvironment(m_env);
} else {
auto env = m_env;
for (const QString &nameValue : environment) {
const auto i = nameValue.indexOf(QLatin1Char('='));
Q_ASSERT(i != -1);
const auto name = nameValue.left(i);
const auto value = nameValue.mid(i+1);
env.insert(name, value);
}
p->setProcessEnvironment(env);
}
p->start( QCoreApplication::applicationFilePath(), arguments, mode );
return p->waitForStarted(10000);
}
QByteArray waitForServerToStart()
{
SleepTimer t(15000);
do {
if ( run(Args() << "") == 0 )
return QByteArray();
} while ( t.sleep() );
return "Unable to start server!" + readServerErrors(ReadAllStderr);
}
PlatformClipboard *clipboard()
{
if (m_clipboard == nullptr)
m_clipboard = platformNativeInterface()->clipboard();
return m_clipboard.get();
}
std::unique_ptr<QProcess> m_server;
QProcessEnvironment m_env;
QString m_testId;
QVariantMap m_settings;
QStringList m_failed;
PlatformClipboardPtr m_clipboard;
};
} // namespace
Tests::Tests(const TestInterfacePtr &test, QObject *parent)
: QObject(parent)
, m_test(test)
{
}
void Tests::initTestCase()
{
TEST(m_test->initTestCase());
}
void Tests::cleanupTestCase()
{
TEST(m_test->cleanupTestCase());
}
void Tests::init()
{
TEST(m_test->init());
}
void Tests::cleanup()
{
TEST( m_test->cleanup() );
}
int Tests::run(
const QStringList &arguments, QByteArray *stdoutData, QByteArray *stderrData, const QByteArray &in,
const QStringList &environment)
{
return m_test->run(arguments, stdoutData, stderrData, in, environment);
}
bool Tests::hasTab(const QString &tabName)
{
QByteArray out;
run(Args("tab"), &out);
return splitLines(out).contains(tabName);
}
int runTests(int argc, char *argv[])
{
QRegularExpression onlyPlugins;
bool runPluginTests = true;
if (argc > 1) {
QString arg = argv[1];
if (arg.startsWith("PLUGINS:")) {
arg.remove(QRegularExpression("^PLUGINS:"));
onlyPlugins = QRegularExpression(arg, QRegularExpression::CaseInsensitiveOption);
--argc;
++argv;
} else {
// Omit plugin tests if specific core tests requested.
const QString lastArg(argv[argc - 1]);
runPluginTests = lastArg.startsWith("-");
}
}
const auto platform = platformNativeInterface();
std::unique_ptr<QGuiApplication> app( platform->createTestApplication(argc, argv) );
Q_UNUSED(app)
const QString session = "copyq.test";
QCoreApplication::setOrganizationName(session);
QCoreApplication::setApplicationName(session);
initLogging();
// Set higher default tests timeout.
// The default value is 5 minutes (in Qt 5.15) which is not enough to run
// all tests in Tests class on some systems.
bool ok;
const int timeout = qEnvironmentVariableIntValue("QTEST_FUNCTION_TIMEOUT", &ok);
if (!ok || timeout <= 0)
qputenv("QTEST_FUNCTION_TIMEOUT", QByteArray::number(15 * 60 * 1000));
int exitCode = 0;
std::shared_ptr<TestInterfaceImpl> test(new TestInterfaceImpl);
const auto runTests = [&](QObject *tests){
exitCode = std::max(exitCode, test->runTests(tests, argc, argv));
};
if (onlyPlugins.pattern().isEmpty()) {
test->setupTest("CORE", QVariant());
Tests tc(test);
runTests(&tc);
test->stopServer();
}
if (runPluginTests) {
ItemFactory itemFactory;
itemFactory.loadPlugins();
for ( const auto &loader : itemFactory.loaders() ) {
if ( loader->id().contains(onlyPlugins) ) {
std::unique_ptr<QObject> pluginTests( loader->tests(test) );
if ( pluginTests != nullptr ) {
test->setupTest(loader->id(), pluginTests->property("CopyQ_test_settings"));
runTests(pluginTests.get());
test->stopServer();
}
}
}
}
return exitCode;
}
| 22,596
|
C++
|
.cpp
| 574
| 30.097561
| 119
| 0.605445
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,129
|
tests_script_commands.cpp
|
hluk_CopyQ/src/tests/tests_script_commands.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "test_utils.h"
#include "tests.h"
#include "common/commandstatus.h"
#include "common/mimetypes.h"
#include "common/sleeptimer.h"
void Tests::scriptCommandLoaded()
{
const auto script = R"(
setCommands([{
isScript: true,
cmd: 'add("LOADED")'
}])
)";
RUN(script, "");
RUN("read(0)", "LOADED");
}
void Tests::scriptCommandAddFunction()
{
const auto script = R"(
setCommands([{
isScript: true,
cmd: 'global.test = function() { return "TEST"; }'
}])
)";
RUN(script, "");
RUN("test", "TEST\n");
}
void Tests::scriptCommandOverrideFunction()
{
const auto script = R"(
setCommands([{
isScript: true,
cmd: 'popup = function(msg) { return msg; }'
}])
)";
RUN(script, "");
RUN("popup" << "test" << "xxx", "test");
}
void Tests::scriptCommandEnhanceFunction()
{
const auto script = R"(
setCommands([
{
isScript: true,
cmd: 'var popup_ = popup; global.popup = function(msg) { popup_(msg); return msg + 1; }'
},
{
isScript: true,
cmd: 'var popup_ = popup; global.popup = function(msg) { return popup_(msg) + msg + 2; }'
},
])
)";
RUN(script, "");
RUN("popup" << "test", "test1test2\n");
}
void Tests::scriptCommandEndingWithComment()
{
/*
With Qml scripts in Qt 5, it's not possible to execute script in new context,
only in the global one.
Workaround is to wrap the script properly in a new function:
function() {
%1
}()
(Unfortunately, it's still possible to escape the new context with a script injection.)
*/
const auto script = R"(
setCommands([
{
isScript: true,
cmd: 'global.popup = function(msg) { return msg + 1; } // TEST'
},
])
)";
RUN(script, "");
RUN("popup" << "test", "test1\n");
}
void Tests::scriptCommandWithError()
{
const auto script = R"(
setCommands([
{
isScript: true,
name: 'bad_script',
cmd: 'if (env("COPYQ_TEST_THROW") == "1") throw Error("BAD SCRIPT")'
},
])
)";
RUN(script, "");
m_test->setEnv("COPYQ_TEST_THROW", "1");
RUN_EXPECT_ERROR_WITH_STDERR(
"", CommandError,
"ScriptError: BAD SCRIPT\n"
"\n"
"--- backtrace ---\n"
);
RUN_EXPECT_ERROR_WITH_STDERR(
"", CommandError,
"\neval:source@<bad_script>\n"
"--- end backtrace ---\n"
);
m_test->setEnv("COPYQ_TEST_THROW", "0");
}
void Tests::scriptPaste()
{
const auto script = R"(
setCommands([
{
isScript: true,
cmd: 'global.paste = function() { add("PASTE") }'
},
])
)";
RUN(script, "");
RUN("add(1)", "");
RUN("keys" << clipboardBrowserId << "ENTER", "");
WAIT_ON_OUTPUT("read(0)", "PASTE");
}
void Tests::scriptOnTabSelected()
{
const auto script = R"(
setCommands([
{
isScript: true,
cmd: 'global.onTabSelected = function() { add(selectedTab()) }'
},
])
)";
RUN(script, "");
const auto tab1 = testTab(1);
const auto tab2 = testTab(2);
RUN("show" << tab1, "");
WAIT_ON_OUTPUT("tab" << tab1 << "read(0)", tab1);
RUN("show" << tab2, "");
WAIT_ON_OUTPUT("tab" << tab2 << "read(0)", tab2);
}
void Tests::scriptOnItemsRemoved()
{
const auto script = R"(
setCommands([
{
isScript: true,
cmd: `
global.onItemsRemoved = function() {
items = ItemSelection().current().items();
tab(tab()[0]);
add("R0:" + str(items[0][mimeText]));
add("R1:" + str(items[1][mimeText]));
}
`
},
])
)";
RUN(script, "");
const auto tab1 = testTab(1);
RUN("tab" << tab1 << "add(3,2,1,0)", "");
RUN("tab" << tab1 << "remove(1,2)", "");
WAIT_ON_OUTPUT("separator" << "," << "read(0,1,2,)", "R1:2,R0:1,");
// Cancel item removal
const auto script2 = R"(
setCommands([
{
isScript: true,
cmd: "global.onItemsRemoved = global.fail",
},
])
)";
RUN(script2, "");
const auto tab2 = testTab(2);
RUN("tab" << tab2 << "add(3,2,1,0)", "");
RUN("tab" << tab2 << "remove(1,2)", "");
waitFor(1000);
RUN("tab" << tab2 << "separator" << "," << "read(0,1,2,3,4)", "0,1,2,3,");
// Avoid crash if the tab itself is removed while removing items
const auto script3 = R"(
setCommands([
{
isScript: true,
cmd: `
global.onItemsRemoved = function() {
removeTab(selectedTab())
}
`
},
])
)";
RUN(script3, "");
const auto tab3 = testTab(3);
RUN("tab" << tab3 << "add(3,2,1,0)", "");
RUN("tab" << tab3 << "remove(1,2)", "");
waitFor(1000);
RUN("tab" << tab3 << "separator" << "," << "read(0,1,2,3,4)", ",,,,");
}
void Tests::scriptOnItemsAdded()
{
const auto script = R"(
setCommands([
{
isScript: true,
cmd: `
global.onItemsAdded = function() {
sel = ItemSelection().current();
items = sel.items();
for (i = 0; i < items.length; ++i)
items[i][mimeText] = "A:" + str(items[i][mimeText])
sel.setItems(items);
}
`
},
])
)";
RUN(script, "");
const auto tab1 = testTab(1);
RUN("tab" << tab1 << "add(1,0)", "");
WAIT_ON_OUTPUT("tab" << tab1 << "separator" << "," << "read(0,1,2)", "A:0,A:1,");
}
void Tests::scriptOnItemsChanged()
{
const auto script = R"(
setCommands([
{
isScript: true,
cmd: `
global.onItemsChanged = function() {
if (selectedTab() == tab()[0]) abort();
items = ItemSelection().current().items();
tab(tab()[0]);
add("C:" + str(items[0][mimeText]));
}
`
},
])
)";
RUN(script, "");
const auto tab1 = testTab(1);
RUN("tab" << tab1 << "add(0)", "");
RUN("tab" << tab1 << "change(0, mimeText, 'A')", "");
WAIT_ON_OUTPUT("separator" << "," << "read(0,1,2)", "C:A,,");
RUN("tab" << tab1 << "change(0, mimeText, 'B')", "");
WAIT_ON_OUTPUT("separator" << "," << "read(0,1,2)", "C:B,C:A,");
}
void Tests::scriptOnItemsLoaded()
{
const auto script = R"(
setCommands([
{
isScript: true,
cmd: `
global.onItemsLoaded = function() {
if (selectedTab() == tab()[0]) abort();
tab(tab()[0]);
add(selectedTab());
}
`
},
])
)";
RUN(script, "");
const auto tab1 = testTab(1);
RUN("show" << tab1, "");
WAIT_ON_OUTPUT("separator" << "," << "read(0,1,2)", tab1 + ",,");
const auto tab2 = testTab(2);
RUN("show" << tab2, "");
WAIT_ON_OUTPUT("separator" << "," << "read(0,1,2)", tab2 + "," + tab1 + ",");
}
void Tests::scriptEventMaxRecursion()
{
const auto script = R"(
setCommands([
{
isScript: true,
cmd: `global.onItemsRemoved = function() {
const toRemove = str(selectedItemData(0)[mimeText]);
const newItem = (toRemove == "X") ? "A" : ("WRONG:" + toRemove);
add(newItem);
remove(size()-1);
}`
},
])
)";
RUN(script, "");
RUN("add('X'); remove(0)", "");
WAIT_ON_OUTPUT("separator" << "," << "read(0,1,2,3,4,5,6,7,8,9,10)", "A,A,A,A,A,A,A,A,A,A,");
waitFor(200);
RUN("separator" << "," << "read(0,1,2,3,4,5,6,7,8,9,10)", "A,A,A,A,A,A,A,A,A,A,");
}
void Tests::scriptSlowCollectOverrides()
{
const auto script = R"(
setCommands([
{
isScript: true,
cmd: 'global.onTabSelected = function() { add(selectedTab()) }'
},
{
isScript: true,
cmd: `
var collectOverrides_ = global.collectOverrides;
global.collectOverrides = function() { sleep(1000); collectOverrides_() }
`
},
])
)";
RUN(script, "");
const auto tab1 = testTab(1);
RUN("show" << tab1, "");
WAIT_ON_OUTPUT("tab" << tab1 << "read(0)", tab1);
}
void Tests::displayCommand()
{
const auto testMime = COPYQ_MIME_PREFIX "test";
const auto script = QString(R"(
setCommands([{
display: true,
input: '%1',
cmd: 'copyq:'
+ 'text = str(data(mimeText));'
+ 'currentTab = str(data(mimeCurrentTab));'
+ 'add(currentTab + "/" + text);'
}])
)").arg(testMime);
RUN(script, "");
RUN("write" << "0" << testMime << "" << mimeText << "a", "");
WAIT_ON_OUTPUT(
"read(0,1,2)",
QString::fromLatin1("%1/a\na\n")
.arg(clipboardTabName)
.toUtf8() );
RUN("write" << "0" << testMime << "" << mimeText << "b", "");
WAIT_ON_OUTPUT(
"read(0,1,2,3,4)",
QString::fromLatin1("%1/b\nb\n%1/a\na\n")
.arg(clipboardTabName)
.toUtf8() );
}
void Tests::displayCommandForMenu()
{
const auto tab = testTab(1);
const auto args = Args("tab") << tab << "separator" << ",";
const auto script = QString(R"(
setCommands([{
display: true,
cmd: 'copyq:'
+ 'currentTab = str(data(mimeCurrentTab));'
+ 'inMenu = str(data(mimeDisplayItemInMenu));'
+ 'if (inMenu != "1" || currentTab != "%1") abort();'
+ 'text = str(data(mimeText));'
+ 'setData(mimeText, "display:" + text);'
+ 'setData(mimeIcon, String.fromCharCode(0xF328));'
+ 'setData("application/x-copyq-item-tag", "TAG");'
+ 'tab(tab()[0]);'
+ 'old = str(read(0));'
+ 'add(old + "|" + text);'
}])
)").arg(tab);
RUN("config" << "tray_tab" << tab, tab + "\n");
RUN("config" << "tray_tab_is_current" << "false", "false\n");
RUN(script, "");
RUN(args << "add(1,2,3,4,5)", "");
RUN("menu", "");
WAIT_ON_OUTPUT("read(0)", "|5|4|3|2|1");
}
| 11,199
|
C++
|
.cpp
| 363
| 21.421488
| 105
| 0.455707
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,130
|
tests_common.cpp
|
hluk_CopyQ/src/tests/tests_common.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "test_utils.h"
#include "tests/tests_common.h"
#include <QRegularExpression>
#include <QTemporaryFile>
TemporaryFile::TemporaryFile()
{
QTemporaryFile tmp;
tmp.setAutoRemove(false);
QVERIFY(tmp.open());
m_fileName = tmp.fileName();
tmp.close();
}
TemporaryFile::~TemporaryFile()
{
QFile::remove(m_fileName);
}
bool testStderr(const QByteArray &stderrData, TestInterface::ReadStderrFlag flag)
{
static const QRegularExpression reFailure("(Warning:|ERROR:|ASSERT|ScriptError:).*", QRegularExpression::CaseInsensitiveOption);
const QLatin1String scriptError("ScriptError:");
const auto plain = [](const char *str){
return QRegularExpression(QRegularExpression::escape(QLatin1String(str)));
};
const auto regex = [](const char *str){
return QRegularExpression(QLatin1String(str));
};
// Ignore exceptions and errors from clients in application log
// (these are expected in some tests).
static const std::array ignoreList{
regex(R"(CopyQ Note \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}\] <Client-[^\n]*)"),
plain("Event handler maximum recursion reached"),
// X11 (Linux)
plain("QtWarning: QXcbXSettings::QXcbXSettings(QXcbScreen*) Failed to get selection owner for XSETTINGS_S atom"),
plain("QtWarning: QXcbConnection: XCB error:"),
plain("QtWarning: QXcbClipboard: SelectionRequest too old"),
plain("QtWarning: libpng warning: iCCP: known incorrect sRGB profile"),
plain("QtWarning: QMime::convertToMime: unhandled mimetype: text/plain"),
// Wayland (Linux)
plain("QtWarning: Wayland does not support QWindow::requestActivate()"),
plain("QtWarning: Unexpected wl_keyboard.enter event"),
plain("QtWarning: The compositor sent a wl_pointer.enter"),
// Windows
plain("QtWarning: QWindowsWindow::setGeometry: Unable to set geometry"),
plain("QtWarning: QWinEventNotifier: no event dispatcher, application shutting down? Cannot deliver event."),
plain("QtWarning: setGeometry: Unable to set geometry"),
plain("ERROR: QtCritical: QWindowsPipeWriter::write failed. (The pipe is being closed.)"),
plain("ERROR: QtCritical: QWindowsPipeWriter: asynchronous write failed. (The pipe has been ended.)"),
plain("[kf.notifications] QtWarning: Received a response for an unknown notification."),
// KStatusNotifierItem
plain("[kf.windowsystem] QtWarning: Could not find any platform plugin"),
regex("QtWarning: QTemporaryDir: Unable to remove .* most likely due to the presence of read-only files."),
// Windows Qt 5.15.2
plain("[qt.qpa.mime] QtWarning: Retrying to obtain clipboard."),
plain("[default] QtWarning: QSystemTrayIcon::setVisible: No Icon set"),
// macOS
plain("QtWarning: Failed to get QCocoaScreen for NSObject(0x0)"),
plain("ERROR: Failed to open session mutex: QSystemSemaphore::handle:: ftok failed"),
regex(R"(QtWarning: Window position.* outside any known screen.*)"),
regex(R"(QtWarning: Populating font family aliases took .* ms. Replace uses of missing font family "Font Awesome.*" with one that exists to avoid this cost.)"),
// New in Qt 5.15.0
regex(R"(QtWarning: Populating font family aliases took .* ms. Replace uses of missing font family "Monospace" with one that exists to avoid this cost.)"),
// New in Qt 6.5
regex("QtWarning: Error in contacting registry"),
// KNotification bug
plain(R"(QtWarning: QLayout: Attempting to add QLayout "" to QWidget "", which already has a layout)"),
// Warnings from itemsync plugin, not sure what it causes
regex(R"(QtWarning: Could not remove our own lock file .* maybe permissions changed meanwhile)"),
};
static QHash<QString, bool> ignoreLog;
const QString output = QString::fromUtf8(stderrData);
QRegularExpressionMatchIterator it = reFailure.globalMatch(output);
while ( it.hasNext() ) {
const auto match = it.next();
const QString log = match.captured();
if ( flag == TestInterface::ReadErrorsWithoutScriptException
&& log.contains(scriptError) )
{
return false;
}
if ( ignoreLog.contains(log) )
return ignoreLog[log];
qDebug() << "Failure in logs:" << log;
const bool ignore = std::any_of(
std::begin(ignoreList), std::end(ignoreList),
[&output](const QRegularExpression &reIgnore){
return output.contains(reIgnore);
});
ignoreLog[log] = ignore;
if (!ignore)
return false;
}
return true;
}
int count(const QStringList &items, const QString &pattern)
{
int from = -1;
int count = 0;
const QRegularExpression re(pattern);
while ( (from = items.indexOf(re, from + 1)) != -1 )
++count;
return count;
}
QStringList splitLines(const QByteArray &nativeText)
{
return QString::fromUtf8(nativeText).split(QRegularExpression("\r\n|\n|\r"));
}
QByteArray generateData()
{
static int i = 0;
const QByteArray id = "tests_"
+ QByteArray::number(QDateTime::currentMSecsSinceEpoch() % 1000);
return id + '_' + QByteArray::number(++i);
}
QString appWindowTitle(const QString &text)
{
#ifdef Q_OS_MAC
return QStringLiteral("CopyQ - %1\n").arg(text);
#elif defined(Q_OS_WIN)
return QStringLiteral("%1 - CopyQ-TEST\n").arg(text);
#else
return QStringLiteral("%1 — CopyQ-TEST\n").arg(text);
#endif
}
| 5,697
|
C++
|
.cpp
| 124
| 39.298387
| 168
| 0.673223
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,131
|
tests_dialogs.cpp
|
hluk_CopyQ/src/tests/tests_dialogs.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "test_utils.h"
#include "tests.h"
#include "tests_common.h"
#include "common/mimetypes.h"
void Tests::createTabDialog()
{
const auto tab1 = testTab(1);
RUN("keys"
<< clipboardBrowserId << "CTRL+T"
<< tabDialogLineEditId << ":" + tab1 << "ENTER", "");
RUN("testSelected", tab1 + "\n");
}
void Tests::showHideAboutDialog()
{
const auto aboutShortcut = keyNameFor(QKeySequence::QKeySequence::WhatsThis);
RUN("keys" << clipboardBrowserId << aboutShortcut << aboutDialogId, "");
RUN("keys" << aboutDialogId << "ESCAPE" << clipboardBrowserId, "");
}
void Tests::showHideClipboardDialog()
{
TEST( m_test->setClipboard("TEST", "test-format") );
RUN("keys" << clipboardBrowserId << "CTRL+SHIFT+C" << clipboardDialogId, "");
RUN("keys" << clipboardDialogId << "DOWN" << "HOME" << clipboardDialogFormatListId, "");
RUN("keys" << clipboardDialogFormatListId << keyNameFor(QKeySequence::Copy), "");
#ifdef Q_OS_WIN
WAIT_FOR_CLIPBOARD("application/x-qt-windows-mime;value=\"test-format\"");
#else
WAIT_FOR_CLIPBOARD("test-format");
#endif
RUN("keys" << clipboardDialogId << "ESCAPE" << clipboardBrowserId, "");
}
void Tests::showHideItemDialog()
{
RUN("write" << "test-format" << "TEST", "");
RUN("selectItems" << "0", "true\n");
RUN("keys" << clipboardBrowserId << "F4" << clipboardDialogId, "");
RUN("keys" << clipboardDialogId << "DOWN" << clipboardDialogFormatListId, "");
RUN("keys" << clipboardDialogFormatListId << keyNameFor(QKeySequence::Copy), "");
WAIT_FOR_CLIPBOARD("test-format");
RUN("keys" << clipboardDialogFormatListId << "DOWN", "");
RUN("keys" << clipboardDialogFormatListId << keyNameFor(QKeySequence::Copy), "");
WAIT_FOR_CLIPBOARD("test-format");
RUN("keys" << clipboardDialogId << "ESCAPE" << clipboardBrowserId, "");
}
void Tests::showHideLogDialog()
{
RUN("keys" << clipboardBrowserId << "F12" << logDialogId, "");
RUN("keys" << logDialogId << "CTRL+A" << "CTRL+C" << logDialogId, "");
const QByteArray expectedLog = "Starting callback: onStart";
TEST( m_test->verifyClipboard(expectedLog, mimeHtml, false) );
RUN("keys" << logDialogId << "ESCAPE" << clipboardBrowserId, "");
}
void Tests::showHideActionHandlerDialog()
{
RUN("keys" << clipboardBrowserId << "CTRL+SHIFT+Z" << actionHandlerDialogId, "");
RUN("keys" << actionHandlerFilterId << ":onstart" << "TAB" << actionHandlerTableId, "");
RUN("keys" << actionHandlerTableId << "RIGHT" << "CTRL+C", "");
WAIT_FOR_CLIPBOARD("copyq onStart");
RUN("keys" << actionHandlerDialogId << "ESCAPE" << clipboardBrowserId, "");
}
void Tests::shortcutDialogAddShortcut()
{
#ifdef Q_OS_MAC
SKIP("Mnemonic for focusing shortcut button doesn't work on OS X");
#endif
RUN("setCommands([{name: 'test', inMenu: true, cmd: 'copyq add OK'}])", "");
RUN("commands()[0].shortcuts", "");
RUN("keys" << clipboardBrowserId << "F6" << commandDialogId, "");
RUN("keys" << commandDialogId << "ALT+S" << shortcutButtonId, "");
RUN("keys" << shortcutButtonId << "Space" << shortcutDialogId, "");
RUN("keys" << shortcutDialogId << "CTRL+F1" << shortcutButtonId, "");
RUN("keys" << commandDialogId << "ESCAPE" << commandDialogSaveButtonId, "");
RUN("keys" << commandDialogSaveButtonId << "Enter" << clipboardBrowserId, "");
RUN("commands()[0].shortcuts", "ctrl+f1\n");
}
void Tests::shortcutDialogAddTwoShortcuts()
{
#ifdef Q_OS_MAC
SKIP("Mnemonic for focusing shortcut button doesn't work on OS X");
#endif
RUN("setCommands([{name: 'test', inMenu: true, shortcuts: ['ctrl+f1'], cmd: 'copyq add OK'}])", "");
RUN("commands()[0].shortcuts", "ctrl+f1\n");
RUN("keys" << clipboardBrowserId << "F6" << commandDialogId, "");
RUN("keys" << commandDialogId << "ALT+S" << shortcutButtonId, "");
RUN("keys" << shortcutButtonId << "TAB" << shortcutButtonId, "");
RUN("keys" << shortcutButtonId << "Space" << shortcutDialogId, "");
RUN("keys" << shortcutDialogId << "F1" << shortcutButtonId, "");
RUN("keys" << shortcutButtonId << "Space" << shortcutDialogId, "");
RUN("keys" << shortcutDialogId << "F2" << shortcutButtonId, "");
RUN("keys" << commandDialogId << "ESCAPE" << commandDialogSaveButtonId, "");
RUN("keys" << commandDialogSaveButtonId << "Enter" << clipboardBrowserId, "");
RUN("commands()[0].shortcuts", "ctrl+f1\nf1\nf2\n");
}
void Tests::shortcutDialogChangeShortcut()
{
#ifdef Q_OS_MAC
SKIP("Mnemonic for focusing shortcut button doesn't work on OS X");
#endif
RUN("setCommands([{name: 'test', inMenu: true, shortcuts: ['f1','f2','f3'], cmd: 'copyq add OK'}])", "");
RUN("commands()[0].shortcuts", "f1\nf2\nf3\n");
RUN("keys" << clipboardBrowserId << "F6" << commandDialogId, "");
RUN("keys" << commandDialogId << "ALT+S" << shortcutButtonId, "");
RUN("keys" << commandDialogId << "TAB" << shortcutButtonId, "");
RUN("keys" << shortcutButtonId << "Space" << shortcutDialogId, "");
RUN("keys" << shortcutDialogId << "F4" << shortcutButtonId, "");
RUN("keys" << commandDialogId << "ESCAPE" << commandDialogSaveButtonId, "");
RUN("keys" << commandDialogSaveButtonId << "Enter" << clipboardBrowserId, "");
RUN("commands()[0].shortcuts", "f1\nf4\nf3\n");
}
void Tests::shortcutDialogSameShortcut()
{
#ifdef Q_OS_MAC
SKIP("Mnemonic for focusing shortcut button doesn't work on OS X");
#endif
RUN("setCommands([{name: 'test', inMenu: true, shortcuts: ['ctrl+f1'], cmd: 'copyq add OK'}])", "");
RUN("commands()[0].shortcuts", "ctrl+f1\n");
RUN("keys" << clipboardBrowserId << "F6" << commandDialogId, "");
RUN("keys" << commandDialogId << "ALT+S" << shortcutButtonId, "");
RUN("keys" << shortcutButtonId << "TAB" << shortcutButtonId, "");
RUN("keys" << shortcutButtonId << "Space" << shortcutDialogId, "");
RUN("keys" << shortcutDialogId << "CTRL+F1" << shortcutButtonId, "");
RUN("keys" << commandDialogId << "ESCAPE" << clipboardBrowserId, "");
RUN("commands()[0].shortcuts", "ctrl+f1\n");
}
void Tests::shortcutDialogCancel()
{
#ifdef Q_OS_MAC
SKIP("Mnemonic for focusing shortcut button doesn't work on OS X");
#endif
RUN("setCommands([{name: 'test', inMenu: true, shortcuts: ['ctrl+f1'], cmd: 'copyq add OK'}])", "");
RUN("commands()[0].shortcuts", "ctrl+f1\n");
RUN("keys" << clipboardBrowserId << "F6" << commandDialogId, "");
RUN("keys" << commandDialogId << "ALT+S" << shortcutButtonId, "");
RUN("keys" << commandDialogId << "TAB" << shortcutButtonId, "");
RUN("keys" << shortcutButtonId << "Space" << shortcutDialogId, "");
RUN("keys" << shortcutDialogId << "TAB" << "focus:ShortcutDialog", "");
RUN("keys" << "ESCAPE" << shortcutButtonId, "");
RUN("keys" << commandDialogId << "ESCAPE" << clipboardBrowserId, "");
RUN("commands()[0].shortcuts", "ctrl+f1\n");
}
void Tests::actionDialogCancel()
{
const auto script = R"(
setCommands([{
name: 'test',
inMenu: true,
shortcuts: ['ctrl+f1'],
wait: true,
cmd: 'copyq settings test SHOULD_NOT_BE_SET'
}])
)";
RUN(script, "");
RUN("keys" << clipboardBrowserId << "CTRL+F1" << actionDialogId, "");
RUN("keys" << actionDialogId << "ESCAPE" << clipboardBrowserId, "");
RUN("settings" << "test", "");
}
void Tests::actionDialogAccept()
{
const auto script = R"(
setCommands([{
name: 'test',
inMenu: true,
shortcuts: ['ctrl+f1'],
wait: true,
cmd: 'copyq settings test SHOULD_BE_SET'
}])
)";
RUN(script, "");
RUN("keys" << clipboardBrowserId << "CTRL+F1" << actionDialogId, "");
// Can't focus configuration checkboxes on OS X
#ifdef Q_OS_MAC
RUN("keys" << actionDialogId << "BACKTAB" << "ENTER" << clipboardBrowserId, "");
#else
RUN("keys" << actionDialogId << "ENTER" << clipboardBrowserId, "");
#endif
WAIT_ON_OUTPUT("settings" << "test", "SHOULD_BE_SET");
}
void Tests::actionDialogSelectionInputOutput()
{
const auto script = R"(
setCommands([{
name: 'test',
inMenu: true,
shortcuts: ['ctrl+f1'],
wait: true,
input: 'text/plain',
output: 'text/plain',
cmd: `
copyq settings test %1
copyq input
`
}])
)";
RUN(script, "");
const auto tab = testTab(1);
const auto args = Args("tab") << tab;
RUN(args << "add" << "C" << "B" << "A", "");
RUN("setCurrentTab" << tab, "");
RUN(args << "selectItems" << "0" << "2", "true\n");
RUN("keys" << clipboardBrowserId << "CTRL+F1" << actionDialogId, "");
// Can't focus configuration checkboxes on OS X
#ifdef Q_OS_MAC
RUN("keys" << actionDialogId << "BACKTAB" << "ENTER" << clipboardBrowserId, "");
#else
RUN("keys" << actionDialogId << "ENTER" << clipboardBrowserId, "");
#endif
WAIT_ON_OUTPUT("settings" << "test", "A\nC");
WAIT_ON_OUTPUT(args << "read" << "0", "A\nC");
}
void Tests::exitConfirm()
{
RUN("keys" << clipboardBrowserId << "CTRL+Q" << confirmExitDialogId, "");
RUN("keys" << confirmExitDialogId << "ENTER", "");
TEST( m_test->waitForServerToStop() );
}
void Tests::exitNoConfirm()
{
RUN("config" << "confirm_exit" << "false", "false\n");
RUN("keys" << clipboardBrowserId << "CTRL+Q", "");
TEST( m_test->waitForServerToStop() );
}
void Tests::exitStopCommands()
{
RUN("config" << "confirm_exit" << "false", "false\n");
RUN("action" << "copyq sleep 999999", "");
RUN("keys" << clipboardBrowserId << "CTRL+Q", "");
RUN("keys" << confirmExitDialogId << "ENTER", "");
TEST( m_test->waitForServerToStop() );
}
| 9,873
|
C++
|
.cpp
| 230
| 38.082609
| 109
| 0.617141
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,132
|
tests_other.cpp
|
hluk_CopyQ/src/tests/tests_other.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "test_utils.h"
#include "tests.h"
#include "tests_common.h"
#include "common/commandstatus.h"
#include "common/mimetypes.h"
#include "common/sleeptimer.h"
#include "platform/platformnativeinterface.h"
namespace {
bool waitWhileFileExists(const QFile &file)
{
SleepTimer t(2000);
while (file.exists() && t.sleep()) {}
return !file.exists();
}
QVariantMap secretData(const QByteArray &text)
{
#ifdef Q_OS_WIN
const QString format("application/x-qt-windows-mime;value=\"Clipboard Viewer Ignore\"");
const QByteArray value("");
#elif defined(Q_OS_MACOS)
const QString format("application/x-nspasteboard-concealed-type");
const QByteArray value("secret");
#elif defined(Q_OS_UNIX)
const QString format("x-kde-passwordManagerHint");
const QByteArray value("secret");
#endif
return QVariantMap{
{format, value},
{mimeText, text},
};
}
} // namespace
void Tests::pipingCommands()
{
const auto tab = testTab(1);
const Args args = Args("tab") << tab << "separator" << ",";
RUN(args << "action"
<< "copyq print HELLO | copyq print(str(input()).toLowerCase())", "");
WAIT_ON_OUTPUT(args << "read" << "0" << "1", "hello,");
RUN(args << "action"
<< "copyq print TEST"
" | copyq 'print(str(input()) + 1)'"
" | copyq 'print(str(input()) + 2)'"
" | copyq 'print(str(input()) + 3)'"
, "");
WAIT_ON_OUTPUT(args << "read" << "0" << "1", "TEST123,hello");
}
void Tests::copyPasteCommands()
{
const QByteArray commands =
"[Commands]\n"
"1\\Name=Test 1\n"
"2\\Name=Test 2\n"
"size=2";
RUN("keys" << clipboardBrowserId << "F6", "");
TEST( m_test->setClipboard(commands) );
RUN("keys" << commandDialogListId << keyNameFor(QKeySequence::Paste), "");
TEST( m_test->setClipboard(QByteArray()) );
RUN("keys" << commandDialogListId << keyNameFor(QKeySequence::Copy), "");
WAIT_FOR_CLIPBOARD(commands);
RUN("keys" << commandDialogListId << "Enter" << clipboardBrowserId, "");
RUN("commands().length", "2\n");
}
void Tests::toggleClipboardMonitoring()
{
const QByteArray data1 = generateData();
TEST( m_test->setClipboard(data1) );
RUN("clipboard", data1);
WAIT_ON_OUTPUT("read" << "0", data1);
RUN("disable", "");
RUN("monitoring", "false\n");
WAIT_ON_OUTPUT("isClipboardMonitorRunning", "false\n");
const QByteArray data2 = generateData();
TEST( m_test->setClipboard(data2) );
RUN("clipboard", data2);
WAIT_ON_OUTPUT("read" << "0", data1);
RUN("enable", "");
RUN("monitoring", "true\n");
WAIT_ON_OUTPUT("isClipboardMonitorRunning", "true\n");
const QByteArray data3 = generateData();
TEST( m_test->setClipboard(data3) );
RUN("clipboard", data3);
WAIT_ON_OUTPUT("read" << "0", data3);
}
void Tests::clipboardToItem()
{
TEST( m_test->setClipboard("TEXT1") );
RUN("clipboard", "TEXT1");
WAIT_ON_OUTPUT("read" << "0", "TEXT1");
RUN("read" << "?" << "0", "text/plain\n");
TEST( m_test->setClipboard("DATA1", "DATA") );
WAIT_ON_OUTPUT("clipboard" << "DATA", "DATA1");
// Unicode test.
const auto test = QString::fromUtf8(QByteArray("Zkouška s různými českými znaky!"));
const auto bytes = test.toUtf8();
TEST( m_test->setClipboard(bytes) );
RUN("clipboard", bytes);
WAIT_ON_OUTPUT("read" << "0", bytes);
}
void Tests::itemToClipboard()
{
RUN("add" << "TESTING2" << "TESTING1", "");
RUN("read" << "0" << "1", "TESTING1\nTESTING2");
RUN("select" << "0", "");
WAIT_FOR_CLIPBOARD("TESTING1");
RUN("clipboard", "TESTING1");
// select second item and move to top
RUN("config" << "move" << "true", "true\n");
RUN("select" << "1", "");
RUN("read" << "0" << "1", "TESTING2\nTESTING1");
WAIT_FOR_CLIPBOARD("TESTING2");
RUN("clipboard", "TESTING2");
// select without moving
RUN("config" << "move" << "0", "false\n");
RUN("select" << "1", "");
RUN("read" << "0" << "1", "TESTING2\nTESTING1");
WAIT_FOR_CLIPBOARD("TESTING1");
RUN("clipboard", "TESTING1");
}
void Tests::tabAdd()
{
const QString tab = testTab(1);
const Args args = Args("tab") << tab << "separator" << " ";
QVERIFY( !hasTab(tab) );
RUN(args, "");
RUN(args << "size", "0\n");
RUN(args << "add" << "ghi" << "def" << "abc", "");
QVERIFY( hasTab(tab) );
// Restart server.
TEST( m_test->stopServer() );
TEST( m_test->startServer() );
QVERIFY( hasTab(tab) );
RUN(args << "size", "3\n");
RUN(args << "read" << "0" << "1" << "2", "abc def ghi");
}
void Tests::tabRemove()
{
const QString tab = testTab(1);
const Args args = Args("tab") << tab << "separator" << " ";
RUN(args << "add" << "", "");
QVERIFY( hasTab(tab) );
RUN(Args() << "removetab" << tab, "");
QVERIFY( !hasTab(tab) );
RUN_EXPECT_ERROR("removetab" << tab, CommandException);
}
void Tests::tabIcon()
{
const QString tab = testTab(1);
const QString icon = ":/images/icon";
RUN("tab" << tab << "add" << "", "");
RUN("tabIcon" << tab, "\n");
RUN("tabicon" << tab << icon, "");
RUN("tabIcon" << tab, icon + "\n");
RUN("tabIcon" << tab << "", "");
RUN("tabicon" << tab, "\n");
}
void Tests::action()
{
const Args args = Args("tab") << testTab(1);
const Args argsAction = Args(args) << "action";
const QString action = QString::fromLatin1("copyq %1 %2").arg(args.join(" "));
// action with size
RUN(argsAction << action.arg("size") << "", "");
WAIT_ON_OUTPUT(args << "size", "1\n");
RUN(args << "read" << "0", "0\n");
// action with size
RUN(argsAction << action.arg("size") << "", "");
WAIT_ON_OUTPUT(args << "size", "2\n");
RUN(args << "read" << "0", "1\n");
// action with eval print
RUN(argsAction << action.arg("eval 'print(\"A,B,C\")'") << "", "");
WAIT_ON_OUTPUT(args << "size", "3\n");
RUN(args << "read" << "0", "A,B,C");
// action with read and comma separator for new items
RUN(argsAction << action.arg("read 0") << ",", "");
WAIT_ON_OUTPUT(args << "size", "6\n");
RUN(args << "read" << "0" << "1" << "2", "C\nB\nA");
}
void Tests::renameTab()
{
const QString tab1 = testTab(1);
const QString tab2 = testTab(2);
RUN("tab" << tab1 << "add" << "ghi" << "def" << "abc", "");
RUN("renametab" << tab1 << tab2, "");
RUN("tab" << tab2 << "size", "3\n");
RUN("tab" << tab2 << "read" << "0" << "1" << "2", "abc\ndef\nghi");
QVERIFY( !hasTab(tab1) );
// Rename non-existing tab.
RUN_EXPECT_ERROR("renametab" << tab1 << tab2, CommandException);
// Rename to same name.
RUN_EXPECT_ERROR("renametab" << tab2 << tab2, CommandException);
// Rename to empty name.
RUN_EXPECT_ERROR("renametab" << tab2 << "", CommandException);
// Rename to existing tab.
RUN_EXPECT_ERROR("renametab" << tab2 << clipboardTabName, CommandException);
QVERIFY( !hasTab(tab1) );
QVERIFY( hasTab(tab2) );
RUN("renametab" << tab2 << tab1, "");
RUN("tab" << tab1 << "read" << "0" << "1" << "2", "abc\ndef\nghi");
QVERIFY( hasTab(tab1) );
QVERIFY( !hasTab(tab2) );
}
void Tests::renameClipboardTab()
{
const QString newClipboardTabName = clipboardTabName + QStringLiteral("2");
RUN("config" << "tray_tab" << clipboardTabName, clipboardTabName + QStringLiteral("\n"));
const QString icon = ":/images/icon";
RUN("tabicon" << clipboardTabName << icon, "");
RUN("renametab" << clipboardTabName << newClipboardTabName, "");
RUN("tab", newClipboardTabName + "\n");
RUN("config" << "clipboard_tab", newClipboardTabName + QStringLiteral("\n"));
RUN("config" << "tray_tab", newClipboardTabName + QStringLiteral("\n"));
RUN("tabicon" << newClipboardTabName, icon + QStringLiteral("\n"));
TEST( m_test->setClipboard("test1") );
WAIT_ON_OUTPUT("tab" << newClipboardTabName << "read" << "0", "test1");
RUN("tab", newClipboardTabName + "\n");
WAIT_ON_OUTPUT("read" << "0", "test1");
RUN("tab", newClipboardTabName + "\n");
}
void Tests::importExportTab()
{
const QString tab = testTab(1);
const Args args = Args("tab") << tab << "separator" << " ";
RUN(args << "add" << "ghi" << "def" << "abc", "");
TemporaryFile tmp;
RUN(args << "exporttab" << tmp.fileName(), "");
RUN("removetab" << tab, "");
QVERIFY( !hasTab(tab) );
RUN(args << "importtab" << tmp.fileName(), "");
RUN(args << "read" << "0" << "1" << "2", "abc def ghi");
RUN(args << "size", "3\n");
// Export with relative path.
TemporaryFile tmp2;
// Change back to original working directory once finished.
struct CurrentDirectoryGuard {
CurrentDirectoryGuard() : oldDir(QDir::currentPath()) {}
~CurrentDirectoryGuard() { QDir::setCurrent(oldDir); }
const QString oldDir;
} currentDirectoryGuard;
QDir::setCurrent( QDir::cleanPath(tmp2.fileName() + "/..") );
const QString fileName = QFileInfo( tmp2.fileName() ).fileName();
RUN(args << "add" << "012", "");
RUN(args << "exporttab" << fileName, "");
RUN("removetab" << tab, "");
QVERIFY( !hasTab(tab) );
RUN(args << "importtab" << fileName, "");
RUN(args << "read" << "0" << "1" << "2" << "3", "012 abc def ghi");
}
void Tests::removeAllFoundItems()
{
auto args = Args("add");
for (int i = 0; i < 50; ++i) {
args << QString::fromLatin1("a%1").arg(i);
args << QString::fromLatin1("b%1").arg(i);
}
RUN(args, "");
RUN("size", "100\n");
RUN("filter" << "a", "");
RUN("keys" << "CTRL+A" << m_test->shortcutToRemove(), "");
RUN("size", "50\n");
RUN("read" << "49" << "48" << "47", "b0\nb1\nb2");
RUN("read" << "0" << "1" << "2", "b49\nb48\nb47");
}
void Tests::nextPrevious()
{
const QString tab = testTab(1);
const Args args = Args("tab") << tab;
RUN(args << "add" << "C" << "B" << "A", "");
RUN("setCurrentTab" << tab, "");
RUN(args << "next", "");
WAIT_FOR_CLIPBOARD("B");
RUN(args << "next", "");
WAIT_FOR_CLIPBOARD("C");
RUN(args << "next", "");
WAIT_FOR_CLIPBOARD("C");
RUN(args << "previous", "");
WAIT_FOR_CLIPBOARD("B");
RUN(args << "previous", "");
WAIT_FOR_CLIPBOARD("A");
RUN(args << "previous", "");
WAIT_FOR_CLIPBOARD("A");
}
void Tests::externalEditor()
{
const QString tab = testTab(1);
const Args args = Args("tab") << tab;
const QString editorTab = testTab(2);
const Args editorArgs = Args("tab") << editorTab;
const Args editorFileNameArgs = Args(editorArgs) << "read" << "0";
const Args editorEndArgs = Args(editorArgs) << "remove" << "0";
// Set editor command which add file name to edit to special editor tab.
// The command finishes when the special tab is emptied by this test.
// File to edit is removed by application when the command finished.
const auto cmd = QString(
R"(copyq tab "%1" eval "add(arguments[1]); while(length()) sleep(100);" --)"
).arg(editorTab) + " %1";
RUN("config" << "editor" << cmd, cmd + "\n");
// Set clipboard.
const QByteArray data1 = generateData();
TEST( m_test->setClipboard(data1) );
RUN("clipboard", data1);
#define EDIT(DATA1, DATA2) \
do { \
WAIT_ON_OUTPUT(editorArgs << "size", "1\n"); \
QByteArray out; \
QByteArray err; \
run(editorFileNameArgs, &out, &err); \
QVERIFY2( testStderr(err), err ); \
QFile file(out); \
QVERIFY( file.exists() ); \
QVERIFY( file.open(QIODevice::ReadWrite) ); \
QVERIFY( file.readAll() == (DATA1) ); \
file.write(DATA2); \
file.close(); \
RUN(editorEndArgs, ""); \
waitWhileFileExists(file); \
} while(false)
// Edit clipboard.
RUN("edit" << "-1", "");
const QByteArray data2 = generateData();
EDIT(data1, data2);
// Check if clipboard changed.
WAIT_ON_OUTPUT("read" << "0", data1 + data2);
WAIT_FOR_CLIPBOARD(data1 + data2);
// Edit existing item.
const QString text =
"Some text to edit,\n"
"with second line!\n"
+ generateData();
RUN(args << "add" << text, "");
// Modify first item.
RUN(args << "edit" << "0", "");
const QByteArray data3 = generateData();
EDIT(text.toUtf8(), data3);
// Check first item.
WAIT_ON_OUTPUT(args << "read" << "0", text.toUtf8() + data3);
// Edit new item.
RUN(args << "edit", "");
const QByteArray data4 = generateData();
EDIT(QByteArray(), data4);
// Check first item.
WAIT_ON_OUTPUT(args << "read" << "0", data4);
#undef EDIT
}
void Tests::nextPreviousTab()
{
const auto tab1 = testTab(1);
RUN("tab" << tab1 << "size", "0\n");
const auto tab2 = testTab(2);
RUN("tab" << tab2 << "size", "0\n");
using KeyPair = QPair<QString, QString>;
const QList<KeyPair> keyPairs = QList<KeyPair>()
<< KeyPair(keyNameFor(QKeySequence::NextChild), keyNameFor(QKeySequence::PreviousChild))
<< KeyPair("RIGHT", "LEFT");
for (const auto &keyPair : keyPairs) {
for (const auto &optionValue : {"false", "true"}) {
RUN("config" << "tab_tree" << optionValue, QString(optionValue) + "\n");
RUN("keys" << keyPair.first, "");
RUN("testSelected", tab1 + "\n");
RUN("keys" << keyPair.first, "");
RUN("testSelected", tab2 + "\n");
RUN("keys" << keyPair.first, "");
RUN("keys" << keyPair.second, "");
RUN("testSelected", tab2 + "\n");
RUN("keys" << keyPair.second, "");
RUN("testSelected", tab1 + "\n");
RUN("keys" << keyPair.second, "");
}
}
}
void Tests::itemPreview()
{
const auto tab1 = testTab(1);
RUN("tab" << tab1 << "add" << "def" << "abc", "");
RUN("setCurrentTab" << tab1, "");
RUN("preview", "false\n");
RUN("keys" << clipboardBrowserId << "F7", "");
RUN("preview", "true\n");
RUN("keys" << clipboardBrowserId << "TAB" << itemPreviewId, "");
RUN("keys" << itemPreviewId << "HOME", "");
RUN("keys" << itemPreviewId << "RIGHT", "");
RUN("keys" << itemPreviewId << "SHIFT+RIGHT", "");
RUN("keys" << itemPreviewId << keyNameFor(QKeySequence::Copy), "");
WAIT_FOR_CLIPBOARD("b");
RUN("keys" << itemPreviewId << "F7" << clipboardBrowserId, "");
RUN("preview" << "true", "false\n");
RUN("preview" << "false", "true\n");
RUN("preview" << "1", "false\n");
RUN("preview" << "0", "true\n");
RUN("preview(true)", "false\n");
RUN("preview(false)", "true\n");
RUN("preview", "false\n");
}
void Tests::openAndSavePreferences()
{
#ifdef Q_OS_MAC
SKIP("Can't focus configuration checkboxes on OS X");
#endif
RUN("config" << "check_clipboard" << "false", "false\n");
// Open preferences dialog.
RUN("keys" << "Ctrl+P" << configurationDialogId, "");
// Focus and set wrap text option.
// This behavior could differ on some systems and in other languages.
RUN("keys" << configurationDialogId << "ALT+1", "");
// Wait for any checkbox animation or delay
waitFor(1000);
RUN("keys" << configurationDialogId << "ENTER" << clipboardBrowserId, "");
WAIT_ON_OUTPUT("config" << "check_clipboard", "true\n");
}
void Tests::pasteFromMainWindow()
{
RUN("config"
<< "activate_closes" << "true"
<< "activate_focuses" << "true"
<< "activate_pastes" << "true"
,
"activate_closes=true\n"
"activate_focuses=true\n"
"activate_pastes=true\n"
);
RUN("add" << "TEST", "");
RUN("hide", "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('text')", "TEST\n"); },
[&]() {
RUN("keys" << "focus::QLineEdit in :QDialog", "");
RUN("show", "");
RUN("keys" << clipboardBrowserId << "ENTER", "");
WAIT_FOR_CLIPBOARD("TEST");
waitFor(waitMsPasteClipboard);
RUN("keys" << "focus::QLineEdit in :QDialog" << "ENTER", "");
}
);
}
void Tests::pasteNext()
{
const auto tab1 = testTab(1);
RUN("setCurrentTab" << tab1, "");
RUN("keys"
<< clipboardBrowserId << "CTRL+N"
<< editorId << ":NEW ", "");
const auto tab2 = testTab(2);
RUN("tab" << tab2 << "add" << "test3" << "test2" << "test1", "");
RUN("tab" << tab2 << "next(); paste(); next()", "");
waitFor(waitMsPasteClipboard);
RUN("keys" << editorId, "");
WAIT_FOR_CLIPBOARD("test3");
RUN("keys" << editorId << "F2", "");
RUN("tab" << tab1 << "read" << "0", "NEW test2");
}
void Tests::configAutostart()
{
if ( !platformNativeInterface()->canAutostart() ) {
SKIP("Autostart is unsupported on this platform");
return;
}
RUN("config" << "autostart" << "true", "true\n");
RUN("config" << "autostart", "true\n");
RUN("config" << "autostart" << "false", "false\n");
RUN("config" << "autostart", "false\n");
}
void Tests::configPathEnvVariable()
{
const auto path = QDir::home().absoluteFilePath("copyq-settings");
const auto environment = QStringList("COPYQ_SETTINGS_PATH=" + path);
QByteArray out;
QByteArray err;
run(Args() << "info" << "config", &out, &err, QByteArray(), environment);
QVERIFY2( testStderr(err), err );
const auto expectedOut = path.toUtf8();
QCOMPARE( out.left(expectedOut.size()), expectedOut );
}
void Tests::itemDataPathEnvVariable()
{
const auto path = QDir::home().absoluteFilePath("copyq-data");
const auto environment = QStringList("COPYQ_ITEM_DATA_PATH=" + path);
QByteArray out;
QByteArray err;
run(Args() << "info" << "data", &out, &err, QByteArray(), environment);
QVERIFY2( testStderr(err), err );
const auto expectedOut = path.toUtf8();
QCOMPARE( out.left(expectedOut.size()), expectedOut );
}
void Tests::configTabs()
{
const QString sep = QStringLiteral("\n");
RUN("config" << "tabs", clipboardTabName + sep);
const QString tab1 = testTab(1);
RUN("tab" << tab1 << "add" << "test", "");
RUN("config" << "tabs", clipboardTabName + sep + tab1 + sep);
const QString tab2 = testTab(2);
RUN(QString("config('tabs', ['%1', '%2'])").arg(clipboardTabName, tab2), clipboardTabName + sep + tab2 + sep);
RUN("config" << "tabs", clipboardTabName + sep + tab2 + sep + tab1 + sep);
RUN("tab", clipboardTabName + sep + tab2 + sep + tab1 + sep);
RUN(QString("config('tabs', ['%1', '%2'])").arg(tab1, tab2), tab1 + sep + tab2 + sep);
RUN("config" << "tabs", tab1 + sep + tab2 + sep + clipboardTabName + sep);
RUN("tab", tab1 + sep + tab2 + sep + clipboardTabName + sep);
}
void Tests::selectedItems()
{
const auto tab1 = testTab(1);
const Args args = Args("tab") << tab1;
RUN("selectedTab", "CLIPBOARD\n");
RUN("selectedItems", "");
RUN(args << "add" << "D" << "C" << "B" << "A", "");
RUN(args << "setCurrentTab" << tab1 << "selectItems" << "1" << "2", "true\n");
RUN("selectedTab", tab1 + "\n");
RUN("selectedItems", "1\n2\n");
RUN("currentItem", "2\n");
const auto print = R"(
print([selectedTab(), "c:" + currentItem(), "s:" + selectedItems()]);
print("\\n")
)";
// Selection stays consistent when moving items
RUN(print << "move(0)" << print, tab1 + ",c:2,s:1,2\n" + tab1 + ",c:1,s:0,1\n");
RUN(print, tab1 + ",c:1,s:0,1\n");
RUN(print << "keys('HOME', 'CTRL+DOWN')" << print, tab1 + ",c:1,s:0,1\n" + tab1 + ",c:0,s:1,0\n");
RUN(print, tab1 + ",c:1,s:1\n");
// Selection stays consistent when removing items
RUN(args << "setCurrentTab" << tab1 << "selectItems" << "1" << "2" << "3", "true\n");
RUN(print << "remove(2)" << print, tab1 + ",c:3,s:1,2,3\n" + tab1 + ",c:2,s:1,-1,2\n");
RUN(print, tab1 + ",c:2,s:1,2\n");
// Renaming tab invalidates selection and all items because the tab
// underlying data needs to be loaded again using plugins.
const QString tab2 = testTab(2);
const auto rename = QString("renameTab('%1', '%2')").arg(tab1, tab2);
RUN(print << rename << print, tab1 + ",c:2,s:1,2\n" + tab1 + ",c:-1,s:-1,-1\n");
RUN(print, tab2 + ",c:0,s:0\n");
}
void Tests::synchronizeInternalCommands()
{
// Keep internal commands synced with the latest version
// but allow user to change some attributes.
const auto script = R"(
setCommands([
{
internalId: 'copyq_global_toggle',
enable: false,
icon: 'icon.png',
shortcuts: ['Ctrl+F1'],
globalShortcuts: ['Ctrl+F2'],
name: 'Old name',
cmd: 'Old command',
},
])
)";
RUN(script, "");
RUN("commands()[0].internalId", "copyq_global_toggle\n");
RUN("commands()[0].enable", "false\n");
RUN("commands()[0].icon", "icon.png\n");
RUN("commands()[0].shortcuts", "Ctrl+F1\n");
RUN("commands()[0].globalShortcuts", "Ctrl+F2\n");
RUN("commands()[0].name", "Show/hide main window\n");
RUN("commands()[0].cmd", "copyq: toggle()\n");
}
void Tests::queryKeyboardModifiersCommand()
{
RUN("queryKeyboardModifiers()", "");
// TODO: Is there a way to press modifiers?
}
void Tests::pointerPositionCommand()
{
QCursor::setPos(1, 2);
RUN("pointerPosition", "1\n2\n");
QCursor::setPos(2, 3);
RUN("pointerPosition", "2\n3\n");
}
void Tests::setPointerPositionCommand()
{
RUN("setPointerPosition(1,2)", "");
QCOMPARE(QPoint(1, 2), QCursor::pos());
RUN("setPointerPosition(2,3)", "");
QCOMPARE(QPoint(2, 3), QCursor::pos());
}
void Tests::setTabName()
{
const auto script = R"(
tab('1')
add(1)
tab1Size = size()
tab('2')
tab2Size = size()
print(tab1Size + ',' + tab2Size)
)";
RUN(script, "1,0");
}
void Tests::abortInputReader()
{
RUN_WITH_INPUT("afterMilliseconds(0, abort); input(); 'DONE'", KEEP_STDIN_OPEN, "");
RUN_WITH_INPUT("afterMilliseconds(50, abort); input(); 'DONE'", KEEP_STDIN_OPEN, "");
RUN_WITH_INPUT("afterMilliseconds(250, abort); input(); 'DONE'", KEEP_STDIN_OPEN, "");
}
void Tests::changeAlwaysOnTop()
{
// The window should be still visible and focused after changing always-on-top flag.
RUN("visible", "true\n");
RUN("focused", "true\n");
RUN("config" << "always_on_top", "false\n");
RUN("config" << "always_on_top" << "true", "true\n");
WAIT_ON_OUTPUT("visible", "true\n");
// There is a problem activating the window again after
// changing the always-on-top flag on macOS with Qt 6.
#if !defined(Q_OS_MAC) || QT_VERSION < QT_VERSION_CHECK(6,0,0)
WAIT_ON_OUTPUT("focused", "true\n");
#endif
RUN("config" << "always_on_top" << "false", "false\n");
WAIT_ON_OUTPUT("visible", "true\n");
#if !defined(Q_OS_MAC) || QT_VERSION < QT_VERSION_CHECK(6,0,0)
WAIT_ON_OUTPUT("focused", "true\n");
#endif
RUN("hide", "");
RUN("visible", "false\n");
RUN("focused", "false\n");
RUN("config" << "always_on_top" << "true", "true\n");
WAIT_ON_OUTPUT("visible", "false\n");
WAIT_ON_OUTPUT("focused", "false\n");
RUN("config" << "always_on_top" << "false", "false\n");
WAIT_ON_OUTPUT("visible", "false\n");
WAIT_ON_OUTPUT("focused", "false\n");
}
void Tests::networkGet()
{
SKIP_ON_ENV("COPYQ_TESTS_NO_NETWORK");
RUN("r = networkGet('https://example.com'); r.data; r.status", "200\n");
}
void Tests::networkGetPostAsync()
{
RUN("r = networkGetAsync('copyq-test://example.com'); print([r.finished,r.error,r.finished])",
"false,Protocol \"copyq-test\" is unknown,true");
RUN("r = networkPostAsync('copyq-test://example.com'); print([r.finished,r.error,r.finished])",
"false,Protocol \"copyq-test\" is unknown,true");
}
void Tests::pluginNotInstalled()
{
#if QT_VERSION >= QT_VERSION_CHECK(5,10,0)
RUN_EXPECT_ERROR_WITH_STDERR(
"plugins.bad_plugin", CommandException,
"Plugin \"bad_plugin\" is not installed"
);
#else
SKIP("Not supported in older Qt version");
#endif
}
void Tests::startServerAndRunCommand()
{
RUN("--start-server" << "tab" << testTab(1) << "write('TEST');read(0)", "TEST");
TEST( m_test->stopServer() );
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("--start-server") << "tab" << testTab(1) << "read" << "0", &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QCOMPARE(stdoutActual, "TEST");
QCOMPARE( run(Args() << "tab" << testTab(1) << "read" << "0", &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QCOMPARE(stdoutActual, "TEST");
// The sleep() call ensures that the server finishes and terminates the
// client connection.
QCOMPARE( run(Args("--start-server") << "exit();sleep(10000)", &stdoutActual, &stderrActual), 0 );
QCOMPARE(stdoutActual, "Terminating server.\n");
// Try to start new client.
SleepTimer t(10000);
while ( run(Args("exit();sleep(10000)")) == 0 && t.sleep() ) {}
}
void Tests::avoidStoringPasswords()
{
TEST( m_test->setClipboard(secretData("secret")) );
WAIT_ON_OUTPUT("clipboard", "secret");
RUN("read" << "0" << "1" << "2", "\n\n");
RUN("count", "0\n");
RUN("keys" << clipboardBrowserId << keyNameFor(QKeySequence::Paste), "");
waitFor(waitMsPasteClipboard);
RUN("read" << "0" << "1" << "2", "secret\n\n");
RUN("count", "1\n");
}
void Tests::scriptsForPasswords()
{
const auto script = R"(
setCommands([{
isScript: true,
cmd: `global.onSecretClipboardChanged = function() {
add("SECRET");
}`
}])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "1\n");
TEST( m_test->setClipboard(secretData("secret")) );
WAIT_ON_OUTPUT("read" << "0" << "1" << "2", "SECRET\n\n");
RUN("count", "1\n");
}
void Tests::currentClipboardOwner()
{
const auto script = R"(
setCommands([
{
isScript: true,
cmd: 'global.currentClipboardOwner = function() { return settings("clipboard_owner"); }'
},
{
automatic: true,
input: mimeWindowTitle,
cmd: 'copyq: setData("application/x-copyq-owner-test", input())',
},
{
automatic: true,
wndre: '.*IGNORE',
cmd: 'copyq ignore; copyq add IGNORED',
},
])
)";
RUN("settings" << "clipboard_owner" << "TEST1", "");
RUN(script, "");
TEST( m_test->setClipboard("test1") );
WAIT_ON_OUTPUT("read(0)", "test1");
RUN("read('application/x-copyq-owner-test', 0)", "TEST1");
RUN("settings" << "clipboard_owner" << "TEST2", "");
RUN("config" << "update_clipboard_owner_delay_ms" << "10000", "10000\n");
TEST( m_test->setClipboard("test2") );
WAIT_ON_OUTPUT("read(0)", "test2");
RUN("read('application/x-copyq-owner-test', 0)", "TEST2");
RUN("settings" << "clipboard_owner" << "TEST3", "");
TEST( m_test->setClipboard("test3") );
WAIT_ON_OUTPUT("read(0)", "test3");
RUN("read('application/x-copyq-owner-test', 0)", "TEST2");
RUN("settings" << "clipboard_owner" << "TEST4_IGNORE", "");
RUN("config" << "update_clipboard_owner_delay_ms" << "0", "0\n");
TEST( m_test->setClipboard("test4") );
WAIT_ON_OUTPUT("read(0)", "IGNORED");
RUN("settings" << "clipboard_owner" << "TEST5", "");
TEST( m_test->setClipboard("test5") );
WAIT_ON_OUTPUT("read(0)", "test5");
RUN("read('application/x-copyq-owner-test', 0)", "TEST5");
}
void Tests::saveLargeItem()
{
const auto tab = testTab(1);
const auto args = Args("tab") << tab;
const auto script = R"(
write(0, [{
'text/plain': '1234567890'.repeat(10000),
'application/x-copyq-test-data': 'abcdefghijklmnopqrstuvwxyz'.repeat(10000),
}])
)";
RUN(args << script, "");
for (int i = 0; i < 2; ++i) {
RUN(args << "read(0).left(20)", "12345678901234567890");
RUN(args << "read(0).length", "100000\n");
RUN(args << "getItem(0)[mimeText].length", "100000\n");
RUN(args << "getItem(0)[mimeText].left(20)", "12345678901234567890");
RUN(args << "getItem(0)['application/x-copyq-test-data'].left(26)", "abcdefghijklmnopqrstuvwxyz");
RUN(args << "getItem(0)['application/x-copyq-test-data'].length", "260000\n");
RUN(args << "ItemSelection().selectAll().itemAtIndex(0)[mimeText].length", "100000\n");
RUN("unload" << tab, tab + "\n");
}
RUN("show" << tab, "");
RUN("keys" << clipboardBrowserId << keyNameFor(QKeySequence::Copy), "");
WAIT_ON_OUTPUT("clipboard().left(20)", "12345678901234567890");
RUN("clipboard('application/x-copyq-test-data').left(26)", "abcdefghijklmnopqrstuvwxyz");
RUN("clipboard('application/x-copyq-test-data').length", "260000\n");
const auto tab2 = testTab(2);
const auto args2 = Args("tab") << tab2;
RUN("show" << tab2, "");
waitFor(waitMsPasteClipboard);
RUN("keys" << clipboardBrowserId << keyNameFor(QKeySequence::Paste), "");
RUN(args2 << "read(0).left(20)", "12345678901234567890");
RUN(args2 << "read(0).length", "100000\n");
RUN(args << "getItem(0)['application/x-copyq-test-data'].left(26)", "abcdefghijklmnopqrstuvwxyz");
RUN(args << "getItem(0)['application/x-copyq-test-data'].length", "260000\n");
}
void Tests::clipboardUriList()
{
const auto script = R"(
setCommands([
{
isScript: true,
cmd: 'global.clipboardFormatsToSave = function() { return [mimeUriList] }'
},
])
)";
RUN(script, "");
WAIT_ON_OUTPUT("commands().length", "1\n");
const QByteArray uri = "https://test1.example.com";
TEST( m_test->setClipboard(uri, mimeUriList) );
WAIT_ON_OUTPUT("clipboard(mimeUriList)", uri);
}
| 30,301
|
C++
|
.cpp
| 786
| 33.001272
| 117
| 0.58116
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,133
|
tests_slow_clipboard.cpp
|
hluk_CopyQ/src/tests/tests_slow_clipboard.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "test_utils.h"
#include "tests.h"
#include "tests_common.h"
#include "common/log.h"
#include "common/sleeptimer.h"
#include "platform/platformclipboard.h"
#include "platform/platformnativeinterface.h"
#include <QMimeData>
namespace {
class SlowMimeData final : public QMimeData {
public:
explicit SlowMimeData(const QByteArray &data, int delayMs)
: m_data(data)
, m_delayMs(delayMs)
{}
bool hasFormat(const QString &mimeType) const override
{
return formats().contains(mimeType);
}
QStringList formats() const override
{
return {"a/a", "b/b", "c/c"};
}
protected:
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
QVariant retrieveData(const QString &mimeType, QMetaType) const override
#else
QVariant retrieveData(const QString &mimeType, QVariant::Type) const override
#endif
{
if (formats().contains(mimeType)) {
waitFor(m_delayMs);
return m_data;
}
return {};
}
private:
QByteArray m_data;
int m_delayMs;
};
} // namespace
void Tests::slowClipboard()
{
const auto script = R"(
setCommands([
{
isScript: true,
cmd: 'global.clipboardFormatsToSave = function() { return ["a/a", "b/b", "c/c"] }'
},
])
)";
RUN(script, "");
WAIT_ON_OUTPUT("clipboardFormatsToSave", "a/a\nb/b\nc/c\n");
TEST( m_test->setClipboard("A", "a/a") );
WAIT_ON_OUTPUT("clipboard" << "a/a", "A");
auto clipboard = platformNativeInterface()->clipboard();
for (int i = 0; i < 3; ++i) {
QMimeData *data = new SlowMimeData(QByteArray::number(i), i == 2 ? 100 : 501);
clipboard->setRawData(ClipboardMode::Clipboard, data);
waitFor(50);
}
WAIT_ON_OUTPUT("read('a/a', 0, 1, 2, 3)", "2\nA\n\n");
RUN("read('b/b', 0)", "2");
RUN("read('c/c', 0)", "2");
RUN("read('?', 0)", "a/a\nb/b\nc/c\n");
QMimeData *data = new SlowMimeData("X", 1500);
clipboard->setRawData(ClipboardMode::Clipboard, data);
waitFor(2000);
const auto expectedLog = R"(^.*<monitorClipboard-\d+>: Aborting clipboard cloning: Data access took too long$)";
QTRY_COMPARE( count(splitLines(readLogFile(maxReadLogSize)), expectedLog), 1 );
TEST( m_test->setClipboard("B", "a/a") );
WAIT_ON_OUTPUT("clipboard" << "a/a", "B");
RUN("read('a/a', 0, 1, 2, 3)", "B\n2\nA\n");
}
| 2,478
|
C++
|
.cpp
| 75
| 27.586667
| 116
| 0.614902
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,134
|
tests_items.cpp
|
hluk_CopyQ/src/tests/tests_items.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "test_utils.h"
#include "tests.h"
#include "tests_common.h"
#include "common/mimetypes.h"
#include "common/commandstatus.h"
void Tests::configMaxitems()
{
RUN("config" << "maxitems" << "3", "3\n");
RUN("add" << "A" << "B" << "C", "");
RUN("add" << "D", "");
RUN("separator" << " " << "read" << "0" << "1" << "2", "D C B");
RUN("size", "3\n");
RUN("add" << "E" << "F", "");
RUN("separator" << " " << "read" << "0" << "1" << "2", "F E D");
RUN("size", "3\n");
RUN("config" << "maxitems" << "2", "2\n");
RUN("separator" << " " << "read" << "0" << "1", "F E");
RUN("size", "2\n");
// Adding too many items fails.
RUN_EXPECT_ERROR("add" << "1" << "2" << "3", CommandException);
RUN("separator" << " " << "read" << "0" << "1", "F E");
RUN("size", "2\n");
// Single item in tabs.
RUN("config" << "maxitems" << "1", "1\n");
RUN("separator" << " " << "read" << "0", "F");
RUN("size", "1\n");
RUN("add" << "G", "");
RUN("separator" << " " << "read" << "0", "G");
RUN("size", "1\n");
RUN("write" << "1" << "text/plain" << "H", "");
RUN("separator" << " " << "read" << "0", "H");
RUN("size", "1\n");
// No items in tabs.
RUN("config" << "maxitems" << "0", "0\n");
RUN("size", "0\n");
RUN_EXPECT_ERROR("add" << "1", CommandException);
RUN_EXPECT_ERROR("write" << "1", CommandException);
RUN("size", "0\n");
// Invalid value.
RUN("config" << "maxitems" << "-99", "0\n");
RUN("size", "0\n");
}
void Tests::keysAndFocusing()
{
RUN("disable", "");
RUN("keys" << clipboardBrowserId << "CTRL+T", "");
WAIT_ON_OUTPUT("currentWindowTitle", appWindowTitle("New Tab"));
RUN("keys" << tabDialogLineEditId << "ESC", "");
WAIT_ON_OUTPUT("currentWindowTitle", appWindowTitle("*Clipboard Storing Disabled*"));
RUN("enable", "");
}
void Tests::selectItems()
{
const auto tab = QString(clipboardTabName);
RUN("add" << "C" << "B" << "A", "");
RUN("keys" << "RIGHT" << "SHIFT+DOWN" << "SHIFT+DOWN", "");
RUN("testSelected", tab + " 2 0 1 2\n");
RUN("keys" << "SHIFT+UP", "");
RUN("testSelected", tab + " 1 0 1\n");
RUN("keys" << "END", "");
RUN("testSelected", tab + " 2 2\n");
RUN("keys" << "SHIFT+UP", "");
RUN("testSelected", tab + " 1 1 2\n");
RUN("keys" << "CTRL+A", "");
RUN("testSelected", tab + " 1 0 1 2\n");
// CTRL+SPACE toggles current item selection
RUN("add" << "D", "");
RUN("keys" << "PGUP" << "CTRL+SHIFT+DOWN" << "CTRL+SHIFT+DOWN", "");
RUN("testSelected", tab + " 2 0\n");
RUN("keys" << "CTRL+SPACE", "");
RUN("testSelected", tab + " 2 0 2\n");
RUN("keys" << "SHIFT+DOWN", "");
RUN("testSelected", tab + " 3 0 2 3\n");
RUN("keys" << "CTRL+SPACE", "");
RUN("testSelected", tab + " 3 0 2\n");
}
void Tests::moveItems()
{
const auto tab = QString(clipboardTabName);
const auto args = Args() << "separator" << " ";
RUN(args << "add" << "C" << "B" << "A", "");
// move item one down
RUN(args << "keys" << "RIGHT" << "CTRL+DOWN", "");
RUN(args << "read" << "0" << "1" << "2", "B A C");
RUN(args << "testSelected", tab + " 1 1\n");
// move items to top
RUN(args << "keys" << "SHIFT+DOWN" << "CTRL+HOME", "");
RUN(args << "read" << "0" << "1" << "2", "A C B");
RUN(args << "testSelected", tab + " 1 0 1\n");
}
void Tests::deleteItems()
{
const auto tab = QString(clipboardTabName);
const auto args = Args() << "separator" << ",";
RUN(args << "add" << "C" << "B" << "A", "");
// delete first item
RUN(args << "keys" << "RIGHT" << m_test->shortcutToRemove(), "");
RUN(args << "read" << "0" << "1" << "2", "B,C,");
RUN(args << "testSelected", tab + " 0 0\n");
// select all and delete
RUN(args << "keys" << "CTRL+A" << m_test->shortcutToRemove(), "");
RUN(args << "size", "0\n");
}
void Tests::searchItems()
{
RUN("add" << "a" << "b" << "c", "");
RUN("keys" << ":b" << "TAB", "");
RUN("testSelected", QString(clipboardTabName) + " 1 1\n");
}
void Tests::searchItemsAndSelect()
{
RUN("add" << "xx1" << "a" << "xx2" << "c" << "xx3" << "d", "");
RUN("keys" << ":xx" << filterEditId, "");
RUN("testSelected", QString(clipboardTabName) + " 1 1\n");
RUN("keys" << filterEditId << "DOWN" << filterEditId, "");
RUN("testSelected", QString(clipboardTabName) + " 3 3\n");
RUN("keys" << filterEditId << "DOWN" << filterEditId, "");
RUN("testSelected", QString(clipboardTabName) + " 5 5\n");
RUN("keys" << filterEditId << "TAB" << clipboardBrowserId, "");
}
void Tests::searchItemsAndCopy()
{
RUN("add" << "TEST_ITEM", "");
RUN("keys" << ":test" << "CTRL+C" << filterEditId, "");
WAIT_FOR_CLIPBOARD("TEST_ITEM");
}
void Tests::searchRowNumber()
{
RUN("add" << "d2" << "c" << "b2" << "a", "");
RUN("keys" << ":2" << "TAB", "");
RUN("testSelected", QString(clipboardTabName) + " 1 1\n");
RUN("keys" << "CTRL+A", "");
RUN("testSelected", QString(clipboardTabName) + " 1 1 3\n");
RUN("config" << "row_index_from_one" << "false", "false\n");
RUN("keys" << ":2" << "TAB", "");
RUN("testSelected", QString(clipboardTabName) + " 2 2\n");
RUN("keys" << "CTRL+A", "");
RUN("testSelected", QString(clipboardTabName) + " 2 1 2 3\n");
}
void Tests::searchAccented()
{
RUN("add" << "a" << "väčšina" << "a", "");
RUN("filter" << "vacsina", "");
WAIT_ON_OUTPUT("testSelected", QByteArray(clipboardTabName) + " 1 1\n");
}
void Tests::copyItems()
{
const auto tab = QString(clipboardTabName);
RUN("add" << "C" << "B" << "A", "");
// Select and copy all items.
RUN("keys" << "CTRL+A" << keyNameFor(QKeySequence::Copy), "");
// This seems to be required on Windows.
WAIT_ON_OUTPUT("clipboard", "A\nB\nC");
// Paste all items.
RUN("keys" << keyNameFor(QKeySequence::Paste), "");
RUN("separator" << " " << "read" << "0" << "1" << "2" << "3" << "4" << "5", "A B C A B C");
RUN("size", "6\n");
}
void Tests::selectAndCopyOrder()
{
const auto tab = testTab(1);
const Args args = Args("tab") << tab << "separator" << " ";
RUN(args << "add" << "D" << "C" << "B" << "A", "");
RUN("setCurrentTab" << tab, "");
RUN("keys" << "END" << "SHIFT+UP" << "SHIFT+UP" << "SHIFT+UP", "");
RUN(args << "testSelected", tab + " 0 0 1 2 3\n");
RUN("keys" << keyNameFor(QKeySequence::Copy), "");
WAIT_ON_OUTPUT("clipboard", "D\nC\nB\nA");
}
void Tests::sortAndReverse()
{
const auto tab = testTab(1);
const Args args = Args("tab") << tab << "separator" << " ";
RUN(args << "add" << "D" << "A" << "C" << "B", "");
RUN("setCurrentTab" << tab, "");
RUN("keys" << "CTRL+A", "");
RUN(args << "testSelected", tab + " 0 0 1 2 3\n");
RUN("keys" << "CTRL+SHIFT+S", "");
RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "A B C D ");
RUN(args << "testSelected", tab + " 1 0 1 2 3\n");
RUN("keys" << keyNameFor(QKeySequence::Copy), "");
WAIT_ON_OUTPUT("clipboard", "A\nB\nC\nD");
RUN("keys" << "CTRL+SHIFT+R", "");
RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "D C B A ");
RUN(args << "testSelected", tab + " 2 0 1 2 3\n");
RUN("keys" << keyNameFor(QKeySequence::Copy), "");
WAIT_ON_OUTPUT("clipboard", "D\nC\nB\nA");
RUN("keys" << "CTRL+SHIFT+R", "");
RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "A B C D ");
RUN(args << "testSelected", tab + " 1 0 1 2 3\n");
}
void Tests::editItems()
{
RUN("config" << "edit_ctrl_return" << "true", "true\n");
RUN("add" << "Line 4" << "Line 1", "");
RUN("keys"
<< clipboardBrowserId << "F2"
<< editorId << "END" << "ENTER" << ":Line 2" << "F2", "");
RUN("read" << "0", "Line 1\nLine 2");
RUN("keys"
<< clipboardBrowserId << "DOWN" << "F2"
<< editorId << "HOME" << ":Line 3" << "ENTER" << "F2", "");
RUN("read" << "1", "Line 3\nLine 4");
RUN("read" << "0", "Line 1\nLine 2");
// Edit multiple items
RUN("keys"
<< clipboardBrowserId << "SHIFT+UP" << "F2"
<< editorId << "END" << "ENTER" << ":Line 5" << "F2", "");
RUN("read" << "0", "Line 3\nLine 4\nLine 1\nLine 2\nLine 5");
RUN("read" << "1", "Line 1\nLine 2");
RUN("read" << "2", "Line 3\nLine 4");
}
void Tests::createNewItem()
{
RUN("config" << "edit_ctrl_return" << "true", "true\n");
RUN("keys" << "CTRL+N" << editorId << ":Line 1" << "ENTER" << ":Line 2" << "F2", "");
RUN("read" << "0", "Line 1\nLine 2");
RUN("keys" << "CTRL+N" << editorId << ":Line 3" << "ENTER" << ":Line 4" << "F2", "");
RUN("read" << "0", "Line 3\nLine 4");
}
void Tests::editNotes()
{
RUN("add" << "B" << "A", "");
RUN("config" << "editor" << "", "\n");
RUN("keys" << "SHIFT+F2" << ":A Note" << "F2", "");
RUN("read" << mimeText << "0" << mimeItemNotes << "0" << "F2", "A\nA Note");
RUN("read" << mimeText << "1" << mimeItemNotes << "1" << "F2", "B\n");
RUN("keys" << "DOWN", "");
RUN("keys" << "SHIFT+F2" << ":B Note" << "F2", "");
RUN("read" << mimeText << "1" << mimeItemNotes << "1" << "F2", "B\nB Note");
RUN("read" << mimeText << "0" << mimeItemNotes << "0" << "F2", "A\nA Note");
}
| 9,348
|
C++
|
.cpp
| 233
| 35.665236
| 95
| 0.499558
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,135
|
tests_scripts.cpp
|
hluk_CopyQ/src/tests/tests_scripts.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "test_utils.h"
#include "tests.h"
#include "tests_common.h"
#include "common/mimetypes.h"
#include "common/commandstatus.h"
#include <QRegularExpression>
#include <QTemporaryFile>
void Tests::commandExit()
{
RUN("exit", "Terminating server.\n");
TEST( m_test->waitForServerToStop() );
QCOMPARE( run(Args("exit")), 1 );
}
void Tests::commandEval()
{
RUN("eval" << "", "");
RUN("eval" << "1", "1\n");
RUN("eval" << "[1,2,3]", "1\n2\n3\n");
RUN("eval" << "'123'", "123\n");
RUN("eval" << "'123'", "123\n");
RUN("-e" << "", "");
RUN("-e" << "1", "1\n");
}
void Tests::commandEvalThrows()
{
RUN_EXPECT_ERROR_WITH_STDERR(
"throw Error('Some exception')", CommandException,
"ScriptError: Some exception\n"
"\n"
"--- backtrace ---\n"
);
RUN_EXPECT_ERROR_WITH_STDERR(
"throw 'Some exception'", CommandException,
"ScriptError: Some exception\n"
);
RUN_EXPECT_ERROR("eval('throw Error(1)')", CommandException);
RUN_EXPECT_ERROR("eval('throw 1')", CommandException);
RUN_EXPECT_ERROR("eval" << "throw Error(1)", CommandException);
RUN_EXPECT_ERROR("eval" << "throw 1", CommandException);
}
void Tests::commandEvalSyntaxError()
{
RUN_EXPECT_ERROR_WITH_STDERR("eval" << "(", CommandException, "SyntaxError");
}
void Tests::commandEvalArguments()
{
RUN("eval" << "str(arguments[1]) + ', ' + str(arguments[2])" << "Test 1" << "Test 2",
"Test 1, Test 2\n");
}
void Tests::commandEvalEndingWithComment()
{
/*
With Qml scripts in Qt 5, it's not possible to get uncaught exceptions
from `QJSEngine::evaluate()`.
Workaround is to wrap the script properly in an try/catch block:
try {
%1
} catch(e) {
_store_exception_internally(e);
throw e;
}
(Unfortunately, it's still possible to escape the function with a script injection.)
*/
RUN("eval" << "1 // TEST", "1\n");
}
void Tests::commandPrint()
{
RUN("print" << "1", "1");
RUN("print" << "TEST", "TEST");
}
void Tests::commandAbort()
{
RUN("eval" << "abort(); 1", "");
RUN("eval" << "eval('abort(); print(1)'); 2", "");
RUN("eval" << "execute('copyq', 'eval', '--', 'abort(); print(1)'); 2", "2\n");
}
void Tests::commandFail()
{
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("fail"), &stdoutActual, &stderrActual), 1 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QCOMPARE( stdoutActual, QByteArray() );
}
void Tests::commandSource()
{
const auto script =
R"(
test = function() { return " TEST" }
print("SOURCED")
)";
QTemporaryFile scriptFile;
QVERIFY(scriptFile.open());
scriptFile.write(script);
scriptFile.close();
const auto scriptFileName = scriptFile.fileName();
RUN("source" << scriptFileName, "SOURCED");
RUN("source" << scriptFileName << "test()", "SOURCED TEST\n");
}
void Tests::commandVisible()
{
RUN("visible", "true\n");
}
void Tests::commandToggle()
{
RUN("visible", "true\n");
RUN("toggle", "false\n");
WAIT_ON_OUTPUT("visible", "false\n");
RUN("toggle", "true\n");
WAIT_ON_OUTPUT("visible", "true\n");
}
void Tests::commandHide()
{
RUN("visible", "true\n");
RUN("hide", "");
WAIT_ON_OUTPUT("visible", "false\n");
}
void Tests::commandShow()
{
RUN("visible", "true\n");
RUN("hide", "");
WAIT_ON_OUTPUT("visible", "false\n");
RUN("show", "");
WAIT_ON_OUTPUT("visible", "true\n");
}
void Tests::commandShowAt()
{
RUN("visible", "true\n");
RUN("hide", "");
WAIT_ON_OUTPUT("visible", "false\n");
RUN("showAt", "");
WAIT_ON_OUTPUT("visible", "true\n");
}
void Tests::commandFocused()
{
RUN("focused", "true\n");
RUN("hide", "");
RUN("focused", "false\n");
}
void Tests::commandsUnicode()
{
const auto text = QString::fromUtf8(QByteArray("Zkouška s různými českými znaky!"));
RUN_WITH_INPUT("eval" << "input()", text, text);
RUN_WITH_INPUT("eval" << "str(input())", text, text + "\n");
RUN_WITH_INPUT("eval" << "fromUnicode(str(input()), 'utf8')", text, text);
RUN_WITH_INPUT("eval" << "toUnicode(fromUnicode(str(input()), 'utf16'), 'utf16')", text, text + "\n");
RUN_WITH_INPUT("eval" << "toUnicode(fromUnicode(str(input()), 'utf32le'), 'utf32le')", text, text + "\n");
RUN_WITH_INPUT("eval" << "toUnicode( fromUnicode(str(input()), 'utf16le') )", text, text + "\n");
}
void Tests::commandsAddRead()
{
RUN("add" << "A", "");
RUN("read" << "0", "A");
RUN("add" << "B", "");
RUN("read" << "0", "B");
RUN("read" << "1", "A");
RUN("add" << "C" << "D", "");
RUN("read" << "0", "D");
RUN("read" << "1", "C");
RUN("read" << "2", "B");
RUN("read" << "3", "A");
}
void Tests::commandsWriteRead()
{
const QByteArray input("\x00\x01\x02\x03\x04", 5);
const auto arg1 = QString::fromLatin1("\x01\x02\x03\x04");
const auto arg2 = QString::fromLatin1("\x7f\x6f\x5f\x4f");
TEST( m_test->runClient(
Args() << "write"
<< COPYQ_MIME_PREFIX "test1" << arg1
<< COPYQ_MIME_PREFIX "test2" << "-"
<< COPYQ_MIME_PREFIX "test3" << arg2, "",
input) );
RUN("read" << COPYQ_MIME_PREFIX "test1" << "0", arg1.toLatin1());
RUN("read" << COPYQ_MIME_PREFIX "test2" << "0", input);
RUN("read" << COPYQ_MIME_PREFIX "test3" << "0", arg2.toLatin1());
RUN("write(1, {'text/plain': 'A'}, {'text/plain': 'B'})", "");
RUN("read(mimeText, 0, 1, 2, 3)", "\nB\nA\n");
RUN("write(0, [{'text/plain': 'C'}, {'text/plain': 'D'}])", "");
RUN("read(mimeText, 0, 1, 2, 3)", "D\nC\n\nB");
RUN("write(0, ['E', 'F'])", "");
RUN("read(mimeText, 0, 1, 2, 3)", "F\nE\nD\nC");
RUN_EXPECT_ERROR_WITH_STDERR(
"write(0, [{}], [{}])",
CommandException, "Unexpected multiple item list arguments");
RUN_EXPECT_ERROR_WITH_STDERR(
"write(0)",
CommandException, "Expected item arguments");
RUN_EXPECT_ERROR_WITH_STDERR(
"write(0, '1', '2', '3')",
CommandException, "Unexpected uneven number of mimeType/data arguments");
}
void Tests::commandChange()
{
RUN("add" << "C" << "B" << "A", "");
RUN("change" << "1" << "text/plain" << "b", "");
RUN("separator" << " " << "read" << "0" << "1" << "2", "A b C");
RUN("change" << "1" << "text/plain" << "B" << "text/html" << "<b>B</b>", "");
RUN("read" << "text/html" << "1", "<b>B</b>");
RUN("separator" << " " << "read" << "0" << "1" << "2", "A B C");
RUN("change(1, 'text/html', undefined)", "");
RUN("read" << "?" << "1", "text/plain\n");
}
void Tests::commandSetCurrentTab()
{
const auto tab = testTab(1);
RUN("setCurrentTab" << tab, "");
RUN("testSelected", tab + "\n");
}
void Tests::commandConfig()
{
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("config"), &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY( !stdoutActual.isEmpty() );
// invalid option
RUN_EXPECT_ERROR_WITH_STDERR("config" << "xxx", CommandException, "xxx");
QCOMPARE( run(Args("config") << "tab_tree", &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY2( stdoutActual == "true\n" || stdoutActual == "false\n", stdoutActual);
RUN("config" << "tab_tree" << "true", "true\n");
RUN("config" << "tab_tree", "true\n");
RUN("config" << "tab_tree" << "false", "false\n");
RUN("config" << "tab_tree", "false\n");
RUN("config" << "tab_tree" << "1", "true\n");
RUN("config" << "tab_tree", "true\n");
RUN("config" << "tab_tree" << "0", "false\n");
RUN("config" << "tab_tree", "false\n");
// Set multiple options.
RUN("config" << "tab_tree" << "0" << "text_wrap" << "1",
"tab_tree=false\n"
"text_wrap=true\n");
// Don't set any options if there is an invalid one.
RUN_EXPECT_ERROR_WITH_STDERR("config" << "tab_tree" << "1" << "xxx" << "0", CommandException, "xxx");
RUN("config" << "tab_tree", "false\n");
}
void Tests::commandToggleConfig()
{
RUN("toggleConfig" << "check_clipboard", "false\n");
RUN("config" << "check_clipboard", "false\n");
RUN("toggleConfig" << "check_clipboard", "true\n");
RUN("config" << "check_clipboard", "true\n");
RUN_EXPECT_ERROR("toggleConfig", CommandException);
RUN_EXPECT_ERROR_WITH_STDERR("toggleConfig" << "xxx", CommandException, "xxx");
RUN_EXPECT_ERROR_WITH_STDERR("toggleConfig" << "clipboard_tab", CommandException, "clipboard_tab");
}
void Tests::commandDialog()
{
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('text')", "TEST\n"); },
[&]() { RUN(Args() << "keys" << "focus::QLineEdit in :QDialog" << ":TEST" << "ENTER", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('text') === undefined", "true\n"); },
[&]() { RUN(Args() << "keys" << "focus::QLineEdit in :QDialog" << "ESCAPE", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('.defaultChoice', 2, 'list', [1, 2, 3])", "2\n"); },
[&]() { RUN(Args() << "keys" << "focus::QComboBox in :QDialog" << "ENTER", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('.defaultChoice', '', 'list', [1, 2, 3])", "\n"); },
[&]() { RUN(Args() << "keys" << "focus::QComboBox in :QDialog" << "ENTER", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('list', [0, 1, 2])", "0\n"); },
[&]() { RUN(Args() << "keys" << "focus::QComboBox in :QDialog" << "ENTER", ""); }
);
// Can't focus configuration checkboxes on OS X
#ifndef Q_OS_MAC
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('boolean', true) === true", "true\n"); },
[&]() { RUN(Args() << "keys" << "focus::QCheckBox in :QDialog" << "ENTER", ""); }
);
#endif
// Verify that special argument ".title" changes dialog's object name
// so that geometry can be stored.
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('.title', 'test', 'text')", ""); },
[&]() { RUN(Args() << "keys" << "focus::QLineEdit in dialog_test:QDialog" << "ESCAPE", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
const QByteArray script = R"(
dialog(
'.width', 100,
'.height', 100,
'.x', 10,
'.y', 10,
'.style', 'background: red',
'.icon', '',
'.label', 'TEST',
'text', 'DEFAULT',
)
)";
runMultiple(
[&]() { RUN(WITH_TIMEOUT + script, "DEFAULT\n"); },
[&]() { RUN(Args() << "keys" << "focus::QLineEdit in :QDialog" << "ENTER", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('.title', 'Remove Items', '.label', 'Remove all items?') === true", "true\n"); },
[&]() { RUN(Args() << "keys" << "focus::QPushButton in dialog_Remove Items:QDialog" << "ENTER", ""); }
);
}
void Tests::commandDialogCloseOnDisconnect()
{
RUN("afterMilliseconds(0, abort); dialog()", "");
}
void Tests::commandMenuItems()
{
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "menuItems('a', 'b', 'c')", "a\n"); },
[&]() { RUN(Args() << "keys" << customMenuId << "ENTER", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "menuItems([{'text/plain': 'a'}, {'text/plain': 'b'}])", "0\n"); },
[&]() { RUN(Args() << "keys" << customMenuId << "ENTER", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "menuItems('a', 'b', 'c')", "\n"); },
[&]() { RUN(Args() << "keys" << customMenuId << "ESCAPE", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "menuItems([{'text/plain': 'a'}, {'text/plain': 'b'}])", "-1\n"); },
[&]() { RUN(Args() << "keys" << customMenuId << "ESCAPE", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "menuItems('a', 'b', 'c')", "b\n"); },
[&]() { RUN(Args() << "keys" << customMenuId << ":b" << "ENTER", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "menuItems([{'text/plain': 'a'}, {'text/plain': 'b'}])", "1\n"); },
[&]() { RUN(Args() << "keys" << customMenuId << ":b" << "ENTER", ""); }
);
RUN("afterMilliseconds(0, abort); menuItems('a', 'b', 'c')", "");
}
void Tests::commandsPackUnpack()
{
QMap<QLatin1String, QByteArray> data;
data[mimeText] = "plain text";
data[mimeHtml] = "<b>HTML text</b>";
data[QLatin1String(COPYQ_MIME_PREFIX "test1")] = "test1 data";
data[QLatin1String(COPYQ_MIME_PREFIX "test2")] = "test2 data";
auto args = Args() << "write";
for (const auto &mime : data.keys())
args << mime << data[mime];
RUN(args, "");
const QByteArray script1 =
"var data = read('" + toByteArray(mimeItems) + "', 0); var item = unpack(data);";
// Unpack item read from list.
for (const auto &mime : data.keys()) {
RUN("eval"
<< script1 + "var mime = '" + mime + "'; print(mime + ':' + str(item[mime]))",
mime + ':' + data[mime]);
}
// Test pack and unpack consistency.
const QByteArray script2 = "data = pack(item); item = unpack(data);";
for (const auto &mime : data.keys()) {
RUN("eval"
<< script1 + script2 + "var mime = '" + mime + "'; print(mime + ':' + str(item[mime]))",
mime + ':' + data[mime]);
}
}
void Tests::commandsBase64()
{
const QByteArray data = "0123456789\001\002\003\004\005\006\007abcdefghijklmnopqrstuvwxyz!";
const QByteArray base64 = data.toBase64();
TEST( m_test->runClient(Args() << "eval" << "print(input())", data, data) );
TEST( m_test->runClient(Args() << "eval" << "print(tobase64(input()))", base64, data) );
// Line break is added only if return value is string;
// tobase64() returns string, frombase64() returns byte array.
RUN("tobase64" << data, base64 + '\n');
RUN("frombase64" << base64, data);
TEST( m_test->runClient(Args() << "eval" << "print(frombase64(tobase64(input())))", data, data) );
// Test Base64 encoding and decoding consistency.
TEST( m_test->runClient(
Args() << "eval"
<< "var base64 = tobase64(input()); if (str(input()) === str(frombase64(base64))) print('OK')",
"OK", data) );
}
void Tests::commandsGetSetItem()
{
QMap<QByteArray, QByteArray> data;
data["text/plain"] = "plain text";
data["text/html"] = "<b>HTML text</b>";
data[COPYQ_MIME_PREFIX "test1"] = "test1 data";
data[COPYQ_MIME_PREFIX "test2"] = "test2 data";
const QString tab = testTab(1);
const Args args = Args("tab") << tab;
Args args2 = args;
args2 << "write";
for (const auto &mime : data.keys())
args2 << mime << data[mime];
RUN(args2, "");
// Get item from list.
for (const auto &mime : data.keys()) {
RUN(args << "eval"
<< "var mime = '" + mime + "'; print(mime + ':' + str(getitem(0)[mime]))",
mime + ':' + data[mime]);
}
// Set item.
RUN(args << "eval"
<< "setitem(1, { 'text/plain': 'plain text 2', 'text/html': '<b>HTML text 2</b>' })",
"");
RUN(args << "eval" << "print(getitem(1)['text/plain'])", "plain text 2");
RUN(args << "eval" << "print(getitem(1)['text/html'])", "<b>HTML text 2</b>");
}
void Tests::commandsChecksums()
{
RUN("md5sum" << "TEST", "033bd94b1168d7e4f0d644c3c95e35bf\n");
RUN("sha1sum" << "TEST", "984816fd329622876e14907634264e6f332e9fb3\n");
RUN("sha256sum" << "TEST", "94ee059335e587e501cc4bf90613e0814f00a7b08bc7c648fd865a2af6a22cc2\n");
RUN("sha512sum" << "TEST", "7bfa95a688924c47c7d22381f20cc926f524beacb13f84e203d4bd8cb6ba2fce81c57a5f059bf3d509926487bde925b3bcee0635e4f7baeba054e5dba696b2bf\n");
}
void Tests::commandEscapeHTML()
{
RUN("escapeHTML" << "&\n<\n>", "&<br /><<br />>\n");
}
void Tests::commandExecute()
{
const QByteArray script =
"function test(c, expected_stdout, expected_exit_code) {"
" if (str(c.stdout) !== expected_stdout) print('Unexpected stdout: \"' + str(c.stdout) + '\"');"
" if (c.exit_code !== expected_exit_code) print('Unexpected exit_code: ' + str(c.exit_code));"
"}";
RUN("eval" << script +
"c = execute('copyq', 'write', 'text/plain', 'plain text', 'text/html', '<b>test HTML</b>');"
"test(c, '', 0);"
, "");
RUN("eval" << script +
"c = execute('copyq', 'read', 'text/plain', 0);"
"test(c, 'plain text', 0);"
, "");
RUN("eval" << script +
"c = execute('copyq', 'read', 'text/html', 0);"
"test(c, '<b>test HTML</b>', 0);"
, "");
RUN("eval" << script +
"c = execute('copyq', 'read', 0, function(lines) { print(lines); });"
"test(c, 'plain text', 0);"
, "plain text");
}
void Tests::commandSettings()
{
RUN("config" << "clipboard_tab" << "TEST", "TEST\n");
RUN("settings" << "test_variable", "");
RUN("settings" << "test_variable" << "TEST VALUE", "");
RUN("settings" << "test_variable", "TEST VALUE");
RUN("settings" << "test_variable" << "TEST VALUE 2", "");
RUN("settings" << "test_variable", "TEST VALUE 2");
RUN("config" << "clipboard_tab", "TEST\n");
}
void Tests::commandsEnvSetEnv()
{
RUN("eval" <<
"\n var name = 'COPYQ_ENV_TEST'"
"\n if (setEnv(name, 'OK'))"
"\n print(env(name))"
"\n else"
"\n print('FAILED')"
, "OK"
);
}
void Tests::commandSleep()
{
QElapsedTimer t;
t.start();
RUN("sleep" << "100", "");
const auto afterElapsed100Ms = t.elapsed();
QVERIFY(afterElapsed100Ms > 100);
t.start();
RUN("sleep" << "1000", "");
const auto afterElapsed1000Ms = t.elapsed();
QVERIFY(afterElapsed1000Ms > 1000);
}
void Tests::commandsData()
{
RUN("eval" << "setData('x', 'X'); data('x')", "X");
RUN("eval" << "setData('x', 'X'); setData('y', 'Y'); str(data('x')) + str(data('y'))", "XY\n");
RUN("dataFormats", "");
RUN("eval" << "setData('x'); dataFormats()", "x\n");
RUN("eval" << "setData('x'); setData('y'); dataFormats()", "x\ny\n");
RUN("eval" << "setData('x'); setData('y'); removeData('x'); dataFormats()", "y\n");
RUN("eval" << "setData('x'); setData('y'); removeData('y'); dataFormats()", "x\n");
}
void Tests::commandCurrentWindowTitle()
{
RUN("disable", "");
WAIT_ON_OUTPUT("currentWindowTitle", appWindowTitle("*Clipboard Storing Disabled*"));
RUN("enable", "");
}
void Tests::commandCopy()
{
RUN("copy" << "A", "true\n");
WAIT_FOR_CLIPBOARD("A");
RUN("copy" << "DATA" << "B", "true\n");
WAIT_FOR_CLIPBOARD2("B", "DATA");
RUN( Args() << "copy"
<< "DATA3" << "C"
<< "DATA4" << "D"
, "true\n" );
WAIT_FOR_CLIPBOARD2("C", "DATA3");
WAIT_FOR_CLIPBOARD2("D", "DATA4");
RUN( "copy({'DATA1': 1, 'DATA2': 2})", "true\n" );
WAIT_FOR_CLIPBOARD2("1", "DATA1");
WAIT_FOR_CLIPBOARD2("2", "DATA2");
RUN_EXPECT_ERROR_WITH_STDERR(
"copy({}, {})",
CommandException, "Expected single item");
RUN_EXPECT_ERROR_WITH_STDERR(
"copy([{}, {}])",
CommandException, "Expected single item");
}
void Tests::commandClipboard()
{
TEST( m_test->setClipboard("A") );
WAIT_FOR_CLIPBOARD("A");
RUN("clipboard", "A");
TEST( m_test->setClipboard("B", "DATA") );
WAIT_FOR_CLIPBOARD2("B", "DATA");
RUN("clipboard" << "DATA", "B");
}
void Tests::commandHasClipboardFormat()
{
TEST( m_test->setClipboard("B", "DATA") );
WAIT_FOR_CLIPBOARD2("B", "DATA");
WAIT_ON_OUTPUT("hasClipboardFormat('DATA')", "true\n");
WAIT_ON_OUTPUT("hasClipboardFormat('text/plain')", "false\n");
}
void Tests::commandEdit()
{
SKIP_ON_ENV("COPYQ_TESTS_SKIP_COMMAND_EDIT");
RUN("config" << "editor" << "", "\n");
// Edit clipboard and new item.
TEST( m_test->setClipboard("TEST") );
RUN("edit" << "-1", "");
RUN("keys" << "END" << ":LINE 1" << "F2", "");
RUN("read" << "0", "TESTLINE 1");
WAIT_FOR_CLIPBOARD("TESTLINE 1");
// Edit existing item.
RUN("edit" << "0", "");
RUN("keys" << "END" << "ENTER" << ":LINE 2" << "F2", "");
RUN("read" << "0", "TESTLINE 1\nLINE 2");
WAIT_FOR_CLIPBOARD("TESTLINE 1");
// Edit clipboard (ignore existing data) and new item.
RUN("edit", "");
RUN("keys" << "END" << ":LINE 1" << "F2", "");
RUN("read" << "0", "LINE 1");
WAIT_FOR_CLIPBOARD("LINE 1");
}
void Tests::commandEditItem()
{
SKIP_ON_ENV("COPYQ_TESTS_SKIP_COMMAND_EDIT");
RUN("config" << "editor" << "", "\n");
// Edit clipboard and new item.
TEST( m_test->setClipboard("TEST", mimeHtml) );
RUN("editItem" << "-1" << mimeHtml, "");
RUN("keys" << "END" << ":LINE 1" << "F2", "");
#ifdef Q_OS_WIN
# define FRAG_START "<!--StartFragment-->"
# define FRAG_END "<!--EndFragment-->"
const auto expected = QByteArrayLiteral(FRAG_START "TEST" FRAG_END "LINE 1");
#else
const auto expected = QByteArrayLiteral("TESTLINE 1");
#endif
RUN("read" << mimeHtml << "0", expected);
RUN("read" << "0", "");
WAIT_FOR_CLIPBOARD2(expected, mimeHtml);
WAIT_FOR_CLIPBOARD("");
// Edit existing item.
RUN("editItem" << "0" << mimeHtml, "");
RUN("keys" << "END" << "ENTER" << ":LINE 2" << "F2", "");
RUN("read" << mimeHtml << "0", expected + "\nLINE 2");
RUN("read" << "0", "");
WAIT_FOR_CLIPBOARD2(expected, mimeHtml);
WAIT_FOR_CLIPBOARD("");
// Edit clipboard (ignore existing data) and new item.
RUN("editItem" << "-1" << mimeHtml << "TEST", "");
RUN("keys" << "END" << ":LINE 1" << "F2", "");
RUN("read" << mimeHtml << "0", "TESTLINE 1");
RUN("read" << "0", "");
#ifdef Q_OS_WIN
WAIT_FOR_CLIPBOARD2(FRAG_START "TESTLINE 1" FRAG_END, mimeHtml);
#else
WAIT_FOR_CLIPBOARD2("TESTLINE 1", mimeHtml);
#endif
WAIT_FOR_CLIPBOARD("");
}
void Tests::commandGetSetCurrentPath()
{
RUN("currentPath", QDir::currentPath() + "\n");
const auto newPath = QDir::homePath().toUtf8();
TEST( m_test->runClient(
Args("eval") << "currentPath(input()); print(currentPath())",
newPath, newPath) );
TEST( m_test->runClient(
Args("eval") << "currentPath(input()); print(Dir().absolutePath())",
newPath, newPath) );
}
void Tests::commandSelectItems()
{
RUN("add" << "C" << "B" << "A", "");
RUN("selectItems" << "1", "true\n");
RUN("testSelected", QString(clipboardTabName) + " 1 1\n");
RUN("selectItems" << "0" << "2", "true\n");
RUN("testSelected", QString(clipboardTabName) + " 2 0 2\n");
const auto tab = testTab(1);
const auto args = Args("tab") << tab;
RUN(args << "add" << "C" << "B" << "A", "");
RUN(args << "selectItems" << "1" << "2", "true\n");
RUN("testSelected", QString(clipboardTabName) + " 2 0 2\n");
RUN("setCurrentTab" << tab, "");
RUN("testSelected", tab + " 2 1 2\n");
}
void Tests::commandsExportImport()
{
const auto tab1 = testTab(1);
RUN("tab" << tab1 << "add" << "C" << "B" << "A", "");
const auto tab2 = testTab(2);
RUN("tab" << tab2 << "add" << "3" << "2", "");
RUN("config" << "maxitems" << "3", "3\n");
RUN("config" << "editor" << "EDITOR1 %1", "EDITOR1 %1\n");
TemporaryFile tmp;
const auto fileName = tmp.fileName();
RUN("exportData" << fileName, "");
RUN("config" << "maxitems" << "1", "1\n");
RUN("config" << "editor" << "EDITOR2 %1", "EDITOR2 %1\n");
RUN("removetab" << tab1, "");
RUN("tab" << tab2 << "add" << "1", "");
RUN("importData" << fileName, "");
RUN("config" << "maxitems", "3\n");
RUN("config" << "editor", "EDITOR1 %1\n");
const auto suffix = " (1)";
RUN("tab",
QString(clipboardTabName) + "\n"
+ tab2 + "\n"
+ clipboardTabName + suffix + "\n"
+ tab1 + "\n"
+ tab2 + suffix + "\n");
RUN("tab" << tab1 << "read" << "0" << "1" << "2", "A\nB\nC");
RUN("tab" << tab2 + suffix << "read" << "0" << "1", "2\n3");
RUN("tab" << tab2 << "read" << "0", "1");
}
void Tests::commandsGetSetCommands()
{
RUN("commands().length", "0\n");
RUN("setCommands([{name: 'test', cmd: 'copyq help'}])", "");
RUN("commands().length", "1\n");
RUN("commands()[0].name", "test\n");
RUN("commands()[0].cmd", "copyq help\n");
RUN("commands()[0].enable", "true\n");
RUN("setCommands(commands())", "");
RUN("commands().length", "1\n");
RUN("commands()[0].name", "test\n");
RUN("commands()[0].enable", "true\n");
}
void Tests::commandsImportExportCommands()
{
const QString commands =
R"('
[Commands]
1\Name=Test 1
2\Name=Test 2
size=2
')";
RUN("eval" << "importCommands(arguments[1]).length" << "--" << commands, "2\n");
RUN("eval" << "importCommands(arguments[1])[0].name" << "--" << commands, "Test 1\n");
RUN("eval" << "importCommands(arguments[1])[1].name" << "--" << commands, "Test 2\n");
RUN("importCommands(exportCommands([{},{}])).length", "2\n");
RUN("importCommands(exportCommands([{},{name: 'Test 2'}]))[1].name", "Test 2\n");
}
void Tests::commandsImportExportCommandsFixIndentation()
{
{
const QString commands =
"[Command]\n"
"Command=\"\n 1\n 2\n 3\"";
RUN("eval" << "importCommands(arguments[1])[0].cmd" << "--" << commands, "1\n2\n3\n");
}
{
const QString commands =
"[Command]\n"
"Command=\"\r\n 1\r\n 2\r\n 3\"";
RUN("eval" << "importCommands(arguments[1])[0].cmd" << "--" << commands, "1\n2\n3\n");
}
}
void Tests::commandsAddCommandsRegExp()
{
const QString commands =
"[Command]\n"
"Match=^(https?|ftps?)://\\\\$\n";
// Ensure there is a basic RegExp support.
RUN("/test/", "/test/\n");
RUN("/test/.source", "test\n");
RUN("eval" << "exportCommands(importCommands(arguments[1]))" << "--" << commands, commands);
RUN("eval" << "Object.prototype.toString.call(importCommands(arguments[1])[0].re)" << "--" << commands, "[object RegExp]\n");
RUN("eval" << "Object.prototype.toString.call(importCommands(arguments[1])[0].wndre)" << "--" << commands, "[object RegExp]\n");
RUN("eval" << "importCommands(arguments[1])[0].re" << "--" << commands, "/^(https?|ftps?):\\/\\/\\$/\n");
RUN("eval" << "importCommands(arguments[1])[0].wndre" << "--" << commands, "/(?:)/\n");
RUN("eval" << "addCommands(importCommands(arguments[1]))" << "--" << commands, "");
RUN("keys" << commandDialogListId << "Enter" << clipboardBrowserId, "");
RUN("exportCommands(commands())", commands);
RUN("commands()[0].name", "\n");
RUN("commands()[0].re", "/^(https?|ftps?):\\/\\/\\$/\n");
RUN("commands()[0].wndre", "/(?:)/\n");
}
void Tests::commandScreenshot()
{
RUN("screenshot().size() > 0", "true\n");
}
void Tests::commandNotification()
{
const auto script = R"(
notification(
'.title', 'title',
'.message', 'message',
'.time', 1000,
'.id', 'test',
'.icon', 'copyq',
'.button', 'OK', '', '',
'.button', 'CANCEL', '', ''
)
)";
RUN(script, "");
RUN_EXPECT_ERROR_WITH_STDERR(
"notification('.message', 'message', 'BAD')", CommandException, "Unknown argument: BAD");
}
void Tests::commandIcon()
{
RUN("iconColor", QByteArray(defaultSessionColor) + "\n");
RUN("iconColor" << "red", "");
RUN("iconColor", "#ff0000\n");
RUN_EXPECT_ERROR("iconColor" << "BAD_COLOR_NAME", CommandException);
RUN("iconColor", "#ff0000\n");
RUN("iconColor" << "", "");
RUN("iconColor", QByteArray(defaultSessionColor) + "\n");
RUN("iconColor" << defaultSessionColor, "");
RUN("iconColor", QByteArray(defaultSessionColor) + "\n");
}
void Tests::commandIconTag()
{
RUN("iconTag", "\n");
RUN("iconTag" << "TEST", "");
RUN("iconTag", "TEST\n");
RUN("iconTag" << "", "");
RUN("iconTag", "\n");
}
void Tests::commandIconTagColor()
{
RUN("iconTagColor", QByteArray(defaultTagColor) + "\n");
RUN("iconTagColor" << "red", "");
RUN("iconTagColor", "#ff0000\n");
RUN_EXPECT_ERROR("iconTagColor" << "BAD_COLOR_NAME", CommandException);
RUN("iconTagColor", "#ff0000\n");
RUN("iconTagColor" << defaultTagColor, "");
RUN("iconTagColor", QByteArray(defaultTagColor) + "\n");
}
void Tests::commandLoadTheme()
{
RUN_EXPECT_ERROR_WITH_STDERR(
"loadTheme" << "a non-existent file", CommandException, "ScriptError: Failed to read theme");
RUN_EXPECT_ERROR_WITH_STDERR(
"loadTheme" << ".", CommandException, "ScriptError: Failed to read theme");
{
QTemporaryFile tmp;
QVERIFY(tmp.open());
tmp.write("INVALID INI FILE");
tmp.close();
RUN_EXPECT_ERROR_WITH_STDERR(
"loadTheme" << tmp.fileName(), CommandException, "ScriptError: Failed to parse theme");
}
{
QTemporaryFile tmp;
QVERIFY(tmp.open());
tmp.write("[General]");
tmp.close();
RUN("loadTheme" << tmp.fileName(), "");
}
// Verify default stylesheets - if there is a syntax error,
// application prints a warning which should be captured by tests.
{
QTemporaryFile tmp;
QVERIFY(tmp.open());
tmp.write("[General]\nstyle_main_window=true");
tmp.close();
RUN("loadTheme" << tmp.fileName(), "");
}
}
void Tests::commandDateString()
{
const auto dateFormat = "TEST:yyyy-MM-dd";
const auto dateTime = QDateTime::currentDateTime();
const auto today = dateTime.toString(dateFormat);
RUN("dateString" << dateFormat, today + "\n");
}
void Tests::commandAfterMilliseconds()
{
const QString script = "afterMilliseconds(100, function(){ print('TEST'); abort(); });";
RUN(script, "");
RUN(script + "sleep(1)", "");
RUN(script + "sleep(200)", "TEST");
}
void Tests::commandAsync()
{
RUN("afterMilliseconds(0, function() { print(currentItem()); abort(); }); dialog()", "-1");
}
void Tests::commandFilter()
{
RUN("filter", "\n");
RUN("filter" << "test", "");
RUN("filter", "test\n");
RUN("filter" << "", "");
RUN("filter", "\n");
// Empty filter() after ESC.
RUN("filter" << "test", "");
RUN("filter", "test\n");
RUN("keys" << "ESC", "");
RUN("filter", "\n");
}
void Tests::commandMimeTypes()
{
RUN("print(mimeText)", mimeText);
RUN("print(mimeHtml)", mimeHtml);
RUN("print(mimeUriList)", mimeUriList);
RUN("print(mimeWindowTitle)", mimeWindowTitle);
RUN("print(mimeItems)", mimeItems);
RUN("print(mimeItemNotes)", mimeItemNotes);
RUN("print(mimeOwner)", mimeOwner);
RUN("print(mimeClipboardMode)", mimeClipboardMode);
RUN("print(mimeCurrentTab)", mimeCurrentTab);
RUN("print(mimeSelectedItems)", mimeSelectedItems);
RUN("print(mimeCurrentItem)", mimeCurrentItem);
RUN("print(mimeHidden)", mimeHidden);
RUN("print(mimeShortcut)", mimeShortcut);
RUN("print(mimeColor)", mimeColor);
RUN("print(mimeOutputTab)", mimeOutputTab);
}
void Tests::commandUnload()
{
// Failure if tab is visible.
RUN("unload", "");
const auto tab = testTab(1);
// Success if tab doesn't exist.
RUN("unload" << tab, tab + "\n");
RUN("tab" << tab << "add" << "A", "");
// Success if tab is not visible and editor is not open.
RUN("unload" << tab, tab + "\n");
RUN("tab" << tab << "add" << "B", "");
RUN("unload", tab + "\n");
// Success if tab is not loaded.
RUN("unload", tab + "\n");
// Success if tab does not exist.
RUN("unload" << "missing-tab", "missing-tab\n");
}
void Tests::commandForceUnload()
{
RUN("forceUnload", "");
RUN_EXPECT_ERROR_WITH_STDERR("add" << "A", CommandException, "ScriptError: Invalid tab");
RUN("keys" << clipboardBrowserRefreshButtonId << "Space", "");
RUN("add" << "A", "");
const auto tab = testTab(1);
RUN("tab" << tab << "add" << "A", "");
RUN("forceUnload" << tab, "");
RUN("setCurrentTab" << tab, "");
RUN_EXPECT_ERROR_WITH_STDERR(
"tab" << tab << "add" << "B", CommandException, "ScriptError: Invalid tab");
RUN("keys" << clipboardBrowserRefreshButtonId << "Space", "");
RUN("add" << "B", "");
}
void Tests::commandServerLogAndLogs()
{
const QByteArray data1 = generateData();
QRegularExpression re("CopyQ Note \\[[^]]+\\] <Server-[0-9]+>: " + QRegularExpression::escape(data1));
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("logs"), &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY( !stdoutActual.isEmpty() );
QVERIFY( !QString::fromUtf8(stdoutActual).contains(re) );
RUN("serverLog" << data1, "");
QCOMPARE( run(Args("logs"), &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY( !stdoutActual.isEmpty() );
QVERIFY( QString::fromUtf8(stdoutActual).contains(re) );
}
void Tests::chainingCommands()
{
const auto tab1 = testTab(1);
RUN("tab" << tab1 << "add" << "C" << "B" << "A", "");
RUN("tab" << tab1 << "separator" << " " << "read" << "0" << "1" << "2", "A B C");
RUN("tab" << tab1 << "separator" << "\\t" << "showAt" << "read" << "0" << "1" << "2", "A\tB\tC");
// Chain functions without arguments.
RUN("enable" << "disable" << "monitoring", "false\n");
RUN("if (!monitoring()) enable" << "monitoring", "true\n");
// Don't treat arguments after "eval" as functions.
RUN("eval" << "arguments[1]" << "TEST", "TEST");
RUN("eval" << "arguments[1]" << "--" << "TEST", "TEST");
}
void Tests::insertRemoveItems()
{
const Args args = Args("tab") << testTab(1) << "separator" << ",";
RUN(args << "add" << "ghi" << "abc", "");
RUN(args << "insert" << "1" << "def", "");
RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "abc,def,ghi,,");
RUN(args << "insert" << "0" << "012", "");
RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "012,abc,def,ghi,");
RUN(args << "remove" << "0" << "2", "");
RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "abc,ghi,,,");
QByteArray in("ABC");
QCOMPARE( run(Args(args) << "insert" << "1" << "-", nullptr, nullptr, in), 0);
RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "abc,ABC,ghi,,");
}
| 35,603
|
C++
|
.cpp
| 927
| 33.061489
| 165
| 0.555755
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,136
|
tests_tray.cpp
|
hluk_CopyQ/src/tests/tests_tray.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "test_utils.h"
#include "tests.h"
#include "tests_common.h"
#include "common/sleeptimer.h"
// WORKAROUND: Checking clipboard right after closing menu gets stuck on OS X.
#define ACTIVATE_MENU_ITEM(MENU_ID, WIDGET_ID, CONTENT) \
RUN("keys" << MENU_ID << "ENTER", ""); \
RUN("keys" << WIDGET_ID, ""); \
WAIT_FOR_CLIPBOARD(CONTENT)
void Tests::tray()
{
RUN("add" << "A", "");
RUN("keys" << clipboardBrowserId, "");
RUN("menu", "");
ACTIVATE_MENU_ITEM(trayMenuId, clipboardBrowserId, "A");
}
void Tests::menu()
{
const auto tab = testTab(1);
RUN("tab" << tab << "add" << "D" << "C" << "B" << "A", "");
RUN("keys" << clipboardBrowserId, "");
RUN("menu" << tab, "");
ACTIVATE_MENU_ITEM(menuId, clipboardBrowserId, "A");
// Show menu with 2 items from the tab and select last one.
RUN("keys" << clipboardBrowserId, "");
RUN("menu" << tab << "2", "");
RUN("keys" << menuId << "END", "");
ACTIVATE_MENU_ITEM(menuId, clipboardBrowserId, "B");
#ifdef Q_OS_MAC
SKIP("Number keys don't seem to work in the tray menu on macOS.");
#endif
// Select item by row number.
RUN("tab" << tab << "add(3,2,1,0)", "");
RUN("menu" << tab, "");
RUN("keys" << menuId << "3" << clipboardBrowserId, "");
WAIT_FOR_CLIPBOARD("2");
// Select item by index.
RUN("config" << "row_index_from_one" << "false", "false\n");
RUN("tab" << tab << "add(3,2,1,0)", "");
RUN("menu" << tab, "");
RUN("keys" << menuId << "3" << clipboardBrowserId, "");
WAIT_FOR_CLIPBOARD("3");
}
void Tests::traySearch()
{
RUN("add" << "C" << "B" << "A", "");
RUN("keys" << clipboardBrowserId, "");
RUN("menu", "");
RUN("keys" << trayMenuId << "B", "");
ACTIVATE_MENU_ITEM(trayMenuId, clipboardBrowserId, "B");
}
void Tests::trayPaste()
{
RUN("config" << "tray_tab_is_current" << "false", "false\n");
const auto tab1 = testTab(1);
RUN("setCurrentTab" << tab1, "");
RUN("keys"
<< clipboardBrowserId << "CTRL+N"
<< editorId << ":NEW ", "");
RUN("add" << "TEST", "");
RUN("keys" << editorId, "");
RUN("menu", "");
ACTIVATE_MENU_ITEM(trayMenuId, editorId, "TEST");
waitFor(waitMsPasteClipboard);
RUN("keys" << editorId << "F2", "");
RUN("tab" << tab1 << "read" << "0", "NEW TEST");
RUN("keys"
<< clipboardBrowserId << "CTRL+N"
<< editorId << ":NEW ", "");
RUN("config" << "tray_item_paste" << "false", "false\n");
RUN("add" << "TEST2", "");
RUN("keys" << editorId, "");
RUN("menu", "");
ACTIVATE_MENU_ITEM(trayMenuId, editorId, "TEST2");
RUN("keys" << editorId << "F2", "");
RUN("tab" << tab1 << "read" << "0", "NEW ");
}
void Tests::configTrayTab()
{
const auto tab1 = testTab(1);
RUN("tab" << tab1 << "add" << "A", "");
const auto tab2 = testTab(2);
RUN("tab" << tab2 << "add" << "B", "");
RUN("config" << "tray_tab_is_current" << "false", "false\n");
RUN("config" << "tray_item_paste" << "false", "false\n");
RUN("config" << "tray_tab" << tab1, tab1 + "\n");
RUN("keys" << clipboardBrowserId, "");
RUN("menu", "");
ACTIVATE_MENU_ITEM(trayMenuId, clipboardBrowserId, "A");
RUN("config" << "tray_tab" << tab2, tab2 + "\n");
RUN("keys" << clipboardBrowserId, "");
RUN("menu", "");
ACTIVATE_MENU_ITEM(trayMenuId, clipboardBrowserId, "B");
}
void Tests::configMove()
{
SKIP_ON_ENV("COPYQ_TESTS_SKIP_CONFIG_MOVE");
RUN("add" << "B" << "A", "");
RUN("config" << "tray_item_paste" << "false", "false\n");
RUN("config" << "move" << "true", "true\n");
RUN("keys" << clipboardBrowserId, "");
RUN("menu", "");
RUN("keys" << trayMenuId << "DOWN", "");
ACTIVATE_MENU_ITEM(trayMenuId, clipboardBrowserId, "B");
RUN("read" << "0" << "1", "B\nA");
RUN("config" << "move" << "false", "false\n");
RUN("keys" << clipboardBrowserId, "");
RUN("menu", "");
RUN("keys" << trayMenuId << "DOWN", "");
ACTIVATE_MENU_ITEM(trayMenuId, clipboardBrowserId, "A");
RUN("read" << "0" << "1", "B\nA");
}
void Tests::configTrayTabIsCurrent()
{
const auto tab1 = testTab(1);
RUN("tab" << tab1 << "add" << "A", "");
const auto tab2 = testTab(2);
RUN("tab" << tab2 << "add" << "B", "");
RUN("config" << "tray_tab_is_current" << "true", "true\n");
RUN("setCurrentTab" << tab1, "");
RUN("keys" << clipboardBrowserId, "");
RUN("menu", "");
ACTIVATE_MENU_ITEM(trayMenuId, clipboardBrowserId, "A");
RUN("setCurrentTab" << tab2, "");
RUN("keys" << clipboardBrowserId, "");
RUN("menu", "");
ACTIVATE_MENU_ITEM(trayMenuId, clipboardBrowserId, "B");
}
| 4,746
|
C++
|
.cpp
| 129
| 32.286822
| 78
| 0.555386
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,137
|
itemdelegate.cpp
|
hluk_CopyQ/src/item/itemdelegate.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemdelegate.h"
#include "common/client_server.h"
#include "common/contenttype.h"
#include "common/mimetypes.h"
#include "common/sanitize_text_document.h"
#include "common/textdata.h"
#include "common/timer.h"
#include "gui/clipboardbrowser.h"
#include "gui/iconfactory.h"
#include "item/itemfactory.h"
#include "item/itemwidget.h"
#include "item/itemeditorwidget.h"
#include "item/persistentdisplayitem.h"
#include <QEvent>
#include <QPainter>
#include <QResizeEvent>
#include <QScrollArea>
#include <QVBoxLayout>
#include <algorithm>
namespace {
const char propertySelectedItem[] = "CopyQ_selected";
constexpr int defaultMaxItemHeight = 2048 * 8;
} // namespace
ItemDelegate::ItemDelegate(ClipboardBrowser *view, const ClipboardBrowserSharedPtr &sharedData, QWidget *parent)
: QItemDelegate(parent)
, m_view(view)
, m_sharedData(sharedData)
, m_maxWidth(2048)
, m_idealWidth(m_view->viewport()->contentsRect().width())
{
initSingleShotTimer(
&m_timerInvalidateHidden, 0, this, &ItemDelegate::invalidateAllHiddenNow );
}
ItemDelegate::~ItemDelegate() = default;
QSize ItemDelegate::sizeHint(const QModelIndex &index) const
{
return m_items[index.row()].size;
}
QSize ItemDelegate::sizeHint(const QStyleOptionViewItem &,
const QModelIndex &index) const
{
return sizeHint(index);
}
bool ItemDelegate::eventFilter(QObject *obj, QEvent *event)
{
// resize event for items
if ( event->type() == QEvent::Resize ) {
const int row = findWidgetRow(obj);
Q_ASSERT(row != -1);
const auto index = m_view->index(row);
updateLater();
const auto ev = static_cast<QResizeEvent*>(event);
updateItemSize(index, ev->size());
}
return QItemDelegate::eventFilter(obj, event);
}
void ItemDelegate::dataChanged(const QModelIndex &a, const QModelIndex &b)
{
for ( int row = a.row(); row <= b.row(); ++row )
m_items[row].item.reset();
updateLater();
}
void ItemDelegate::rowsRemoved(const QModelIndex &, int start, int end)
{
for (int row = start; row <= end; ++row) {
if ( m_view->isRowHidden(row) )
continue;
if (m_items[row]) {
const auto index = m_view->index(row);
m_items[row]->widget()->removeEventFilter(this);
setIndexWidget(index, nullptr);
}
}
m_items.erase(std::begin(m_items) + start, std::begin(m_items) + end + 1);
updateLater();
}
void ItemDelegate::rowsMoved(const QModelIndex &, int sourceStart, int sourceEnd,
const QModelIndex &, int destinationRow)
{
auto count = sourceEnd - sourceStart + 1;
auto from = sourceStart;
auto to = destinationRow;
if (to < from) {
std::swap(from, to);
to += count;
count = to - from - count;
}
const auto start1 = std::begin(m_items) + from;
const auto start2 = start1 + count;
const auto end2 = std::begin(m_items) + to;
std::rotate(start1, start2, end2);
updateLater();
}
QWidget *ItemDelegate::createPreview(const QVariantMap &data, QWidget *parent)
{
const bool antialiasing = m_sharedData->theme.isAntialiasingEnabled();
ItemWidget *itemWidget =
m_sharedData->itemFactory->createItem(data, parent, antialiasing, false, true);
const auto height = 2048 * 8;
const auto idealWidth = parent->contentsRect().width();
const auto maxSize = m_sharedData->textWrap ? QSize(idealWidth, height) : QSize(2048, height);
itemWidget->updateSize(maxSize, idealWidth);
highlightMatches(itemWidget);
parent->setFocusProxy( itemWidget->widget() );
emit itemWidgetCreated(PersistentDisplayItem(this, data, itemWidget->widget()));
return itemWidget->widget();
}
void ItemDelegate::rowsInserted(const QModelIndex &, int start, int end)
{
const auto count = static_cast<size_t>(end - start + 1);
const auto oldSize = m_items.size();
m_items.resize(oldSize + count);
std::rotate( std::begin(m_items) + start,
std::begin(m_items) + oldSize,
std::end(m_items) );
updateLater();
}
void ItemDelegate::createItemWidget(const QModelIndex &index)
{
const int row = index.row();
ItemWidget *w = m_items[row].get();
if (w == nullptr) {
QVariantMap data = index.data(contentType::data).toMap();
data.insert(mimeCurrentTab, m_view->tabName());
w = updateWidget(index, data);
emit itemWidgetCreated(PersistentDisplayItem(this, data, w->widget()));
}
}
void ItemDelegate::updateWidget(QObject *widget, const QVariantMap &data)
{
if ( widget->parent() != m_view->viewport() ) {
auto previewParent = qobject_cast<QWidget*>( widget->parent() );
Q_ASSERT(previewParent);
if (!previewParent)
return;
auto scrollArea = qobject_cast<QScrollArea*>( previewParent->parentWidget() );
Q_ASSERT(scrollArea);
if (!scrollArea)
return;
auto newPreview = createPreview(data, scrollArea);
scrollArea->setWidget(newPreview);
newPreview->show();
return;
}
const auto row = findWidgetRow(widget);
if (row == -1)
return;
const auto index = m_view->index(row);
updateWidget(index, data);
}
void ItemDelegate::setItemSizes(int maxWidth, int idealWidth)
{
const auto margins = m_sharedData->theme.margins();
const int margin = 2 * margins.width() + 2 * m_view->spacing();
m_maxWidth = maxWidth - margin;
m_idealWidth = idealWidth - margin;
for (int row = 0; static_cast<size_t>(row) < m_items.size(); ++row) {
if (m_items[row])
updateItemWidgetSize(row);
}
}
void ItemDelegate::updateItemWidgetSize(int row)
{
const int rowNumberWidth = m_sharedData->theme.rowNumberSize(row).width();
ItemWidget *w = m_items[row].get();
w->updateSize(
QSize(m_maxWidth - rowNumberWidth, defaultMaxItemHeight),
m_idealWidth - rowNumberWidth
);
}
void ItemDelegate::updateItemSize(const QModelIndex &index, QSize itemWidgetSize)
{
const int row = index.row();
const auto margins = m_sharedData->theme.margins();
const auto rowNumberSize = m_sharedData->theme.rowNumberSize(row);
const int width = itemWidgetSize.width() + 2 * margins.width() + rowNumberSize.width();
const int height = std::max(
itemWidgetSize.height() + 2 * margins.height(),
rowNumberSize.height()
);
const QSize newSize = QSize(width, height);
if (m_items[row].size == newSize)
return;
m_items[row].size = newSize;
emit sizeHintChanged(index);
}
ItemEditorWidget *ItemDelegate::createCustomEditor(
QWidget *parent, const QModelIndex &index, const QString &format)
{
// Refuse editing non-text data
if ( format != mimeItemNotes && !format.startsWith(QLatin1String("text/")) )
return nullptr;
const QVariantMap data = m_sharedData->itemFactory->data(index);
if ( format != mimeItemNotes && !data.contains(format) )
return nullptr;
auto editorParent = new QWidget(parent);
auto editor = new ItemEditorWidget(index, format, editorParent);
connect(editor, &QObject::destroyed, editorParent, &QObject::deleteLater);
// Prefer editing rich text
if ( format == mimeText && data.contains(mimeHtml) ) {
const QString html = getTextData(data, mimeHtml);
editor->setHtml(html);
sanitizeTextDocument(editor->document());
} else {
const QString text = getTextData(data, format);
editor->setPlainText(text);
}
editor->selectAll();
auto toolBar = editor->createToolbar(editorParent, m_sharedData->menuItems);
auto palette = m_sharedData->theme.editorPalette();
editorParent->setBackgroundRole(QPalette::Base);
editorParent->setAutoFillBackground(true);
editorParent->setPalette(palette);
editor->setPalette(palette);
editor->setStyleSheet("QTextEdit{background:transparent}");
palette.setColor(QPalette::Base, Qt::transparent);
editor->setPalette(palette);
const auto font = m_sharedData->theme.editorFont();
editorParent->setFont(font);
editor->setFont(font);
toolBar->setFont(font);
editor->setSaveOnReturnKey(m_sharedData->saveOnReturnKey);
auto layout = new QVBoxLayout(editorParent);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(toolBar);
layout->addWidget(editor);
editorParent->show();
return editor;
}
void ItemDelegate::highlightMatches(ItemWidget *itemWidget) const
{
QWidget *w = itemWidget->widget();
const auto textEdits = w->findChildren<QTextEdit*>();
auto maybeTextEdit = qobject_cast<QTextEdit*>(w);
if (m_filter) {
QTextCharFormat format;
format.setFont( m_sharedData->theme.searchFont() );
QPalette palette = m_sharedData->theme.searchPalette();
format.setBackground( palette.base() );
format.setForeground( palette.text() );
for (QTextEdit *edit : textEdits)
m_filter->highlight(edit, format);
if (maybeTextEdit)
m_filter->highlight(maybeTextEdit, format);
} else {
for (QTextEdit *edit : textEdits)
edit->setExtraSelections({});
if (maybeTextEdit)
maybeTextEdit->setExtraSelections({});
}
}
void ItemDelegate::updateAllRows()
{
const int s = m_view->spacing();
const int space = 2 * s;
int y = -m_view->verticalOffset() + s;
for (int row = 0; static_cast<size_t>(row) < m_items.size(); ++row) {
const bool hide = m_view->isRowHidden(row);
auto &item = m_items[row];
if (item) {
QWidget *ww = item->widget();
if (hide) {
ww->removeEventFilter(this);
ww->hide();
} else {
if (item.appliedFilterId != m_filterId) {
highlightMatches(item.get());
item.appliedFilterId = m_filterId;
}
ww->move( QPoint(ww->x(), y) );
if ( ww->isHidden() ) {
ww->show();
updateItemWidgetSize(row);
ww->installEventFilter(this);
const auto index = m_view->index(row);
updateItemSize(index, ww->size());
}
}
}
if (!hide)
y += m_items[row].size.height() + space;
}
}
void ItemDelegate::updateLater()
{
m_timerInvalidateHidden.start();
}
void ItemDelegate::updateIfNeeded()
{
if ( m_timerInvalidateHidden.isActive() )
invalidateAllHiddenNow();
}
void ItemDelegate::setItemWidgetCurrent(const QModelIndex &index, bool isCurrent)
{
ItemWidget *w;
const int row = index.row();
if (isCurrent) {
createItemWidget(index);
w = m_items[row].get();
auto ww = w->widget();
QPalette palette( ww->palette() );
const auto highlightPalette = m_sharedData->theme.searchPalette();
palette.setColor(QPalette::Highlight, highlightPalette.base().color());
palette.setColor(QPalette::HighlightedText, highlightPalette.text().color());
ww->setPalette(palette);
for ( auto childWidget : ww->findChildren<QWidget*>() )
childWidget->setPalette(palette);
} else {
w = m_items[row].get();
if (!w)
return;
}
w->setCurrent(isCurrent);
}
void ItemDelegate::setItemWidgetSelected(const QModelIndex &index, bool isSelected)
{
const int row = index.row();
auto w = m_items[row].get();
if (!w)
return;
auto ww = w->widget();
setWidgetSelected(ww, isSelected);
}
void ItemDelegate::setIndexWidget(const QModelIndex &index, ItemWidget *w)
{
const int row = index.row();
const QPoint pos = w ? findPositionForWidget(index) : QPoint();
const bool show = w && !m_view->isIndexHidden(index);
auto &item = m_items[row];
item.item.reset(w);
item.appliedFilterId = 0;
if (w) {
QWidget *ww = w->widget();
// Make background transparent.
ww->setAttribute(Qt::WA_NoSystemBackground);
const bool isCurrent = m_view->currentIndex() == index;
setItemWidgetCurrent(index, isCurrent);
const bool isSelected = m_view->selectionModel()->isSelected(index);
setWidgetSelected(ww, isSelected);
ww->move(pos);
if (show) {
ww->show();
updateItemWidgetSize(row);
}
ww->installEventFilter(this);
updateItemSize(index, ww->size());
updateLater();
}
}
QPoint ItemDelegate::findPositionForWidget(const QModelIndex &index) const
{
const QSize margins = m_sharedData->theme.margins();
const QSize rowNumberSize = m_sharedData->theme.rowNumberSize(index.row());
const int s = m_view->spacing();
int y = 0;
int skipped = 0;
for (int row = index.row() - 1; row >= 0; --row) {
if (!m_items[row]) {
if ( !m_view->isRowHidden(row) )
++skipped;
continue;
}
QWidget *ww = m_items[row]->widget();
if ( ww->isHidden() )
continue;
y = ww->geometry().top() - margins.height() + m_items[row].size.height()
+ skipped * (defaultItemHeight + 2 * s);
break;
}
return QPoint(
s + margins.width() + rowNumberSize.width(),
s + margins.height() + y
);
}
void ItemDelegate::setCurrentRow(int row, bool current)
{
ItemWidget *item = m_items[row].get();
if (!item)
return;
item->setCurrent(false);
item->setCurrent(current);
}
void ItemDelegate::setWidgetSelected(QWidget *ww, bool selected)
{
if ( ww->property(propertySelectedItem).toBool() == selected )
return;
ww->setProperty(propertySelectedItem, selected);
QStyle *style = m_view->style();
ww->setStyle(style);
for (auto child : ww->findChildren<QWidget *>())
child->setStyle(style);
ww->update();
}
int ItemDelegate::findWidgetRow(const QObject *obj) const
{
for (int row = 0; static_cast<size_t>(row) < m_items.size(); ++row) {
auto w = m_items[row].get();
if (w && w->widget() == obj)
return row;
}
return -1;
}
ItemWidget *ItemDelegate::updateWidget(const QModelIndex &index, const QVariantMap &data)
{
const bool antialiasing = m_sharedData->theme.isAntialiasingEnabled();
QWidget *parent = m_view->viewport();
auto w = m_sharedData->showSimpleItems
? m_sharedData->itemFactory->createSimpleItem(data, parent, antialiasing)
: m_sharedData->itemFactory->createItem(data, parent, antialiasing);
setIndexWidget(index, w);
return w;
}
bool ItemDelegate::invalidateHidden(QWidget *widget)
{
if ( widget->isVisible() && m_view->isVisible() )
return false;
const auto row = findWidgetRow(widget);
if (row == -1)
return true;
const auto index = m_view->index(row);
if ( m_view->currentIndex() == index )
return false;
setIndexWidget(index, nullptr);
return true;
}
void ItemDelegate::invalidateAllHiddenNow()
{
m_timerInvalidateHidden.stop();
// Make sure item widgets have up-to-date positions for invalidation.
updateAllRows();
const QRect viewRect = m_view->viewport()->contentsRect();
const int maxY = viewRect.bottom() + viewRect.height() + defaultItemHeight;
const int minY = viewRect.top() - viewRect.height() - defaultItemHeight;
const int currentRow = m_view->currentIndex().row();
const auto isRowAlmostVisible = [&](int row){
if (row < 0 || static_cast<size_t>(row) >= m_items.size() || !m_items[row])
return false;
QWidget *ww = m_items[row]->widget();
if ( ww->isHidden() )
return false;
const QRect g = ww->geometry();
return minY < g.bottom() && g.top() < maxY;
};
for (int row = 0; static_cast<size_t>(row) < m_items.size(); ++row) {
if (!m_items[row] || row == currentRow)
continue;
if ( isRowAlmostVisible(row) )
continue;
if ( isRowAlmostVisible(row + 1) || isRowAlmostVisible(row - 1) )
continue;
const auto index = m_view->index(row);
m_items[row]->widget()->removeEventFilter(this);
setIndexWidget(index, nullptr);
}
}
void ItemDelegate::setItemFilter(const ItemFilterPtr &filter)
{
m_filter = filter;
++m_filterId;
}
void ItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
const bool isSelected = option.state & QStyle::State_Selected;
// Render background (selected, alternate, ...).
QStyle *style = m_view->style();
style->drawControl(QStyle::CE_ItemViewItem, &option, painter, m_view);
// Colorize item.
const QString colorExpr = index.data(contentType::color).toString();
if (!colorExpr.isEmpty()) {
const QColor color = m_sharedData->theme.evalColorExpression(colorExpr);
if (color.isValid()) {
const auto oldMode = painter->compositionMode();
painter->setCompositionMode(QPainter::CompositionMode_Multiply);
painter->fillRect(option.rect, color);
painter->setCompositionMode(oldMode);
}
}
const auto margins = m_sharedData->theme.margins();
// Render number.
if ( m_sharedData->theme.showRowNumber() ) {
const int rowNumber = index.row() + static_cast<int>(m_sharedData->rowIndexFromOne);
const QString num = QString::number(rowNumber);
QPalette::ColorRole role = isSelected ? QPalette::HighlightedText : QPalette::Text;
painter->save();
painter->setFont( m_sharedData->theme.rowNumberFont() );
const auto rowNumberPalette = m_sharedData->theme.rowNumberPalette();
style->drawItemText(painter, option.rect.translated(margins.width(), margins.height()),
Qt::AlignTop | Qt::AlignLeft,
rowNumberPalette, true, num,
role);
painter->restore();
}
}
| 18,368
|
C++
|
.cpp
| 496
| 30.425403
| 112
| 0.643356
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,138
|
itemfactory.cpp
|
hluk_CopyQ/src/item/itemfactory.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemfactory.h"
#include "common/appconfig.h"
#include "common/command.h"
#include "common/common.h"
#include "common/config.h"
#include "common/contenttype.h"
#include "common/log.h"
#include "common/mimetypes.h"
#include "common/textdata.h"
#include "item/itemfilter.h"
#include "item/itemstore.h"
#include "item/itemwidget.h"
#include "item/serialize.h"
#include "platform/platformnativeinterface.h"
#include <QCoreApplication>
#include <QDir>
#include <QIODevice>
#include <QLabel>
#include <QMessageBox>
#include <QMetaObject>
#include <QModelIndex>
#include <QSettings>
#include <QPluginLoader>
#include <algorithm>
namespace {
bool findPluginDir(QDir *pluginsDir)
{
#ifdef COPYQ_PLUGIN_PREFIX
pluginsDir->setPath(COPYQ_PLUGIN_PREFIX);
if ( pluginsDir->isReadable() )
return true;
#endif
return platformNativeInterface()->findPluginDir(pluginsDir)
&& pluginsDir->isReadable();
}
bool priorityLessThan(const ItemLoaderPtr &lhs, const ItemLoaderPtr &rhs)
{
return lhs->priority() > rhs->priority();
}
void trySetPixmap(QLabel *label, const QVariantMap &data, int height)
{
const auto imageFormats = {
"image/svg+xml",
"image/png",
"image/bmp",
"image/jpeg",
"image/gif"
};
for (const auto &format : imageFormats) {
QPixmap pixmap;
if (pixmap.loadFromData(data.value(format).toByteArray())) {
if (height > 0)
pixmap = pixmap.scaledToHeight(height, Qt::SmoothTransformation);
label->setPixmap(pixmap);
break;
}
}
}
bool askToKeepCorruptedTab(const QString &tabName)
{
const int answer = QMessageBox::question(
nullptr,
ItemFactory::tr("Corrupted Tab"),
ItemFactory::tr(
"Not all items in the tab <strong>%1</strong> were loaded successfully. "
"Do you still want to load the tab and potentially lose some items?")
.arg(quoteString(tabName)),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::Yes);
return answer == QMessageBox::Yes;
}
/** Sort plugins by prioritized list of names. */
class PluginSorter final {
public:
explicit PluginSorter(const QStringList &pluginNames) : m_order(pluginNames) {}
int value(const ItemLoaderPtr &item) const
{
const int i = m_order.indexOf( item->id() );
return i == -1 ? m_order.indexOf( item->name() ) : i;
}
bool operator()(const ItemLoaderPtr &lhs, const ItemLoaderPtr &rhs) const
{
const int l = value(lhs);
const int r = value(rhs);
if (l == -1)
return (r == -1) && lhs->priority() > rhs->priority();
if (r == -1)
return true;
return l < r;
}
private:
const QStringList &m_order;
};
class DummyItem final : public QLabel, public ItemWidget {
public:
DummyItem(const QVariantMap &data, QWidget *parent, bool preview)
: QLabel(parent)
, ItemWidget(this)
, m_hasText( data.contains(mimeText)
|| data.contains(mimeTextUtf8)
|| data.contains(mimeUriList) )
, m_data(data)
, m_preview(preview)
{
setMargin(0);
setWordWrap(true);
setTextFormat(Qt::PlainText);
setFocusPolicy(Qt::NoFocus);
setContextMenuPolicy(Qt::NoContextMenu);
if (!preview)
setFixedHeight(sizeHint().height());
if ( !data.value(mimeHidden).toBool() ) {
const int height = preview ? -1 : contentsRect().height();
trySetPixmap(this, m_data, height);
}
if (preview && !hasPixmap()) {
setTextInteractionFlags(
textInteractionFlags()
| Qt::TextSelectableByMouse
| Qt::TextSelectableByKeyboard
| Qt::LinksAccessibleByMouse
| Qt::LinksAccessibleByKeyboard
);
setAlignment(Qt::AlignLeft | Qt::AlignTop);
QString label = getTextData(m_data);
if (label.isEmpty())
label = textLabelForData(m_data);
setText(label);
}
m_data.remove(mimeItemNotes);
}
void updateSize(QSize, int idealWidth) override
{
setFixedWidth(idealWidth);
if (!m_preview && !hasPixmap()) {
const int width = contentsRect().width();
const QString label =
textLabelForData(m_data, font(), QString(), false, width, 1);
setText(label);
}
}
void setTagged(bool tagged) override
{
setVisible( !tagged || (m_hasText && !m_data.contains(mimeHidden)) );
}
private:
bool hasPixmap() const
{
#if QT_VERSION >= QT_VERSION_CHECK(5,15,0)
return !pixmap(Qt::ReturnByValue).isNull();
#else
return pixmap() != nullptr;
#endif
}
bool m_hasText;
QVariantMap m_data;
QString m_imageFormat;
bool m_preview;
};
class DummySaver final : public ItemSaverInterface
{
public:
explicit DummySaver(int itemDataThreshold)
: m_itemDataThreshold(itemDataThreshold)
{}
bool saveItems(const QString & /* tabName */, const QAbstractItemModel &model, QIODevice *file) override
{
return serializeData(model, file, m_itemDataThreshold);
}
private:
int m_itemDataThreshold = -1;
};
class DummyLoader final : public ItemLoaderInterface
{
public:
int priority() const override { return std::numeric_limits<int>::min(); }
QString id() const override { return {}; }
QString name() const override { return {}; }
QString author() const override { return {}; }
QString description() const override { return {}; }
QVariant icon() const override { return {}; }
void setEnabled(bool) override {}
void loadSettings(const QSettings &) override
{
m_itemDataThreshold = AppConfig().option<Config::item_data_threshold>();
}
ItemWidget *create(const QVariantMap &data, QWidget *parent, bool preview) const override
{
return new DummyItem(data, parent, preview);
}
bool canLoadItems(QIODevice *) const override { return true; }
bool canSaveItems(const QString &) const override { return true; }
ItemSaverPtr loadItems(const QString &tabName, QAbstractItemModel *model, QIODevice *file, int maxItems) override
{
if ( file->size() > 0 ) {
if ( !deserializeData(model, file, maxItems) ) {
const int itemsLoadedCount = model->rowCount();
if ( itemsLoadedCount > 0 && askToKeepCorruptedTab(tabName) ) {
log(QStringLiteral("Keeping corrupted tab on user request"));
file->close();
file->open(QIODevice::WriteOnly);
ItemSaverPtr saver = std::make_shared<DummySaver>(m_itemDataThreshold);
saver->saveItems(tabName, *model, file);
return saver;
}
model->removeRows(0, itemsLoadedCount);
return nullptr;
}
}
return std::make_shared<DummySaver>(m_itemDataThreshold);
}
ItemSaverPtr initializeTab(const QString &, QAbstractItemModel *, int) override
{
return std::make_shared<DummySaver>(m_itemDataThreshold);
}
bool matches(const QModelIndex &index, const ItemFilter &filter) const override
{
const QString text = index.data(contentType::text).toString();
return filter.matches(text) || filter.matches(accentsRemoved(text));
}
private:
int m_itemDataThreshold = -1;
};
ItemSaverPtr transformSaver(
QAbstractItemModel *model,
const ItemSaverPtr &saverToTransform, const ItemLoaderPtr ¤tLoader,
const ItemLoaderList &loaders)
{
ItemSaverPtr newSaver = saverToTransform;
for ( auto &loader : loaders ) {
if (loader != currentLoader && loader->isEnabled())
newSaver = loader->transformSaver(newSaver, model);
}
return newSaver;
}
std::pair<ItemSaverPtr, ItemLoaderPtr> saveWithOther(
const QString &tabName,
QAbstractItemModel *model,
const ItemSaverPtr ¤tSaver,
const ItemLoaderPtr ¤tLoader,
const ItemLoaderList &loaders,
int maxItems)
{
ItemLoaderPtr newLoader;
for ( auto &loader : loaders ) {
if ( loader->isEnabled() && loader->canSaveItems(tabName) ) {
newLoader = loader;
break;
}
}
if (!newLoader || newLoader == currentLoader)
return {currentSaver, currentLoader};
COPYQ_LOG( QString("Tab \"%1\": Saving items using other plugin")
.arg(tabName) );
auto newSaver = newLoader->initializeTab(tabName, model, maxItems);
if ( !newSaver || !saveItems(tabName, *model, newSaver) ) {
COPYQ_LOG( QString("Tab \"%1\": Failed to re-save items")
.arg(tabName) );
return {currentSaver, currentLoader};
}
return {newSaver, newLoader};
}
} // namespace
ItemFactory::ItemFactory(QObject *parent)
: QObject(parent)
, m_loaders()
, m_dummyLoader(std::make_shared<DummyLoader>())
, m_loaderChildren()
{
}
ItemFactory::~ItemFactory()
{
// Plugins are unloaded at application exit.
}
ItemWidget *ItemFactory::createItem(
const ItemLoaderPtr &loader, const QVariantMap &data,
QWidget *parent, bool antialiasing, bool transform, bool preview)
{
ItemWidget *item = loader->create(data, parent, preview);
if (item != nullptr) {
if (transform)
item = transformItem(item, data);
QWidget *w = item->widget();
const auto notes = getTextData(data, mimeItemNotes);
if (!notes.isEmpty())
w->setToolTip(notes);
if (!antialiasing) {
QFont f = w->font();
f.setStyleStrategy(QFont::NoAntialias);
w->setFont(f);
for (auto child : w->findChildren<QWidget *>("item_child"))
child->setFont(f);
}
m_loaderChildren[w] = loader;
connect(w, &QObject::destroyed, this, &ItemFactory::loaderChildDestroyed);
return item;
}
return nullptr;
}
ItemWidget *ItemFactory::createItem(
const QVariantMap &data, QWidget *parent, bool antialiasing, bool transform, bool preview)
{
for ( auto &loader : m_loaders ) {
if ( !loader->isEnabled() )
continue;
ItemWidget *item = createItem(loader, data, parent, antialiasing, transform, preview);
if (item != nullptr)
return item;
}
return createSimpleItem(data, parent, antialiasing);
}
ItemWidget *ItemFactory::createSimpleItem(
const QVariantMap &data, QWidget *parent, bool antialiasing)
{
return createItem(m_dummyLoader, data, parent, antialiasing);
}
QStringList ItemFactory::formatsToSave() const
{
QStringList formats;
for (const auto &loader : m_loaders) {
if ( !loader->isEnabled() )
continue;
for ( const auto &format : loader->formatsToSave() ) {
if ( !formats.contains(format) )
formats.append(format);
}
}
if ( !formats.contains(mimeText) )
formats.prepend(mimeText);
if ( !formats.contains(mimeItemNotes) )
formats.append(mimeItemNotes);
if ( !formats.contains(mimeItems) )
formats.append(mimeItems);
if ( !formats.contains(mimeTextUtf8) )
formats.append(mimeTextUtf8);
return formats;
}
void ItemFactory::setPluginPriority(const QStringList &pluginNames)
{
m_loaders.removeOne(m_dummyLoader);
std::sort( m_loaders.begin(), m_loaders.end(), PluginSorter(pluginNames) );
m_loaders.append(m_dummyLoader);
}
ItemSaverPtr ItemFactory::loadItems(const QString &tabName, QAbstractItemModel *model, QIODevice *file, int maxItems)
{
for (auto &loader : m_loaders) {
if ( !loader->isEnabled() )
continue;
file->seek(0);
if ( loader->canLoadItems(file) ) {
file->seek(0);
auto saver = loader->loadItems(tabName, model, file, maxItems);
if (!saver)
return nullptr;
file->close();
ItemLoaderPtr newLoader;
std::tie(saver, newLoader) = saveWithOther(tabName, model, saver, loader, m_loaders, maxItems);
return transformSaver(model, saver, newLoader, m_loaders);
}
}
const auto errorString =
QObject::tr("Tab %1 is corrupted or some CopyQ plugins are missing!")
.arg( quoteString(tabName) );
emitError(errorString);
return nullptr;
}
ItemSaverPtr ItemFactory::initializeTab(const QString &tabName, QAbstractItemModel *model, int maxItems)
{
for (const auto &loader : m_loaders) {
if ( loader->isEnabled() && loader->canSaveItems(tabName) ) {
const auto saver = loader->initializeTab(tabName, model, maxItems);
return saver ? transformSaver(model, saver, loader, m_loaders) : nullptr;
}
}
return nullptr;
}
bool ItemFactory::matches(const QModelIndex &index, const ItemFilter &filter) const
{
if ( filter.matchesIndex(index) )
return true;
for (const auto &loader : m_loaders) {
if ( loader->isEnabled() && loader->matches(index, filter) )
return true;
}
return false;
}
ItemScriptable *ItemFactory::scriptableObject(const QString &name) const
{
for (const auto &loader : m_loaders) {
if (loader->id() == name)
return loader->isEnabled() ? loader->scriptableObject() : nullptr;
}
return nullptr;
}
QVector<Command> ItemFactory::commands(bool enabled) const
{
QVector<Command> commands;
for (const auto &loader : m_loaders) {
if (loader->isEnabled() == enabled)
commands << loader->commands();
}
return commands;
}
void ItemFactory::emitError(const QString &errorString)
{
log(errorString, LogError);
emit error(errorString);
}
void ItemFactory::loaderChildDestroyed(QObject *obj)
{
m_loaderChildren.remove(obj);
}
bool ItemFactory::loadPlugins()
{
QDir pluginsDir;
if ( !findPluginDir(&pluginsDir) )
return false;
// Plugins can be loaded only once.
static bool pluginsLoaded = false;
Q_ASSERT(!pluginsLoaded);
if (pluginsLoaded)
return true;
pluginsLoaded = true;
for (const auto &fileName : pluginsDir.entryList(QDir::Files)) {
const QString path = pluginsDir.absoluteFilePath(fileName);
auto loader = loadPlugin(path, QString());
if (loader)
addLoader(loader);
}
std::sort(m_loaders.begin(), m_loaders.end(), priorityLessThan);
addLoader(m_dummyLoader);
return true;
}
void ItemFactory::loadItemFactorySettings(QSettings *settings)
{
// load settings for each plugin
settings->beginGroup("Plugins");
for (const auto &loader : m_loaders) {
const bool enabled = loadItemFactorySettings(loader, settings);
loader->setEnabled(enabled);
}
settings->endGroup();
// load plugin priority
const QStringList pluginPriority =
settings->value("plugin_priority", QStringList()).toStringList();
setPluginPriority(pluginPriority);
}
QObject *ItemFactory::createExternalEditor(const QModelIndex &index, const QVariantMap &data, QWidget *parent) const
{
for (const auto &loader : m_loaders) {
if ( !loader->isEnabled() )
continue;
QObject *editor = loader->createExternalEditor(index, data, parent);
if (editor != nullptr)
return editor;
}
return nullptr;
}
QVariantMap ItemFactory::data(const QModelIndex &index) const
{
QVariantMap data = index.data(contentType::data).toMap();
for (const auto &loader : m_loaders) {
if ( loader->isEnabled() && !loader->data(&data, index) )
return QVariantMap();
}
return data;
}
bool ItemFactory::setData(const QVariantMap &data, const QModelIndex &index, QAbstractItemModel *model) const
{
for (const auto &loader : m_loaders) {
if ( loader->isEnabled() && loader->setData(data, index, model) )
return true;
}
return model->setData(index, data, contentType::updateData);
}
ItemWidget *ItemFactory::transformItem(ItemWidget *item, const QVariantMap &data)
{
for (const auto &loader : m_loaders) {
if ( !loader->isEnabled() )
continue;
ItemWidget *newItem = loader->transform(item, data);
if (newItem != nullptr)
item = newItem;
}
return item;
}
void ItemFactory::addLoader(const ItemLoaderPtr &loader)
{
m_loaders.append(loader);
const QObject *signaler = loader->signaler();
if (signaler) {
const auto loaderMetaObject = signaler->metaObject();
if ( loaderMetaObject->indexOfSignal("error(QString)") != -1 )
connect( signaler, SIGNAL(error(QString)), this, SIGNAL(error(QString)) );
if ( loaderMetaObject->indexOfSignal("addCommands(QVector<Command>)") != -1 )
connect( signaler, SIGNAL(addCommands(QVector<Command>)), this, SIGNAL(addCommands(QVector<Command>)) );
}
}
ItemLoaderPtr ItemFactory::loadPlugin(const QString &path, const QString &id) const
{
if ( !QLibrary::isLibrary(path) )
return ItemLoaderPtr();
COPYQ_LOG_VERBOSE( QString("Loading plugin: %1").arg(path) );
QPluginLoader pluginLoader(path);
QObject *plugin = pluginLoader.instance();
if (plugin == nullptr) {
log( pluginLoader.errorString(), LogError );
return ItemLoaderPtr();
}
ItemLoaderPtr loader( qobject_cast<ItemLoaderInterface *>(plugin) );
if ( loader == nullptr || (!id.isEmpty() && id != loader->id()) ) {
COPYQ_LOG_VERBOSE( QString("Unloading plugin: %1").arg(path) );
loader = nullptr;
pluginLoader.unload();
return ItemLoaderPtr();
}
return loader;
}
bool ItemFactory::loadItemFactorySettings(const ItemLoaderPtr &loader, QSettings *settings) const
{
if (loader == m_dummyLoader) {
loader->loadSettings(*settings);
return true;
}
settings->beginGroup(loader->id());
const auto enabled = settings->value("enabled", true).toBool();
loader->loadSettings(*settings);
settings->endGroup();
#ifdef HAS_TESTS
// For tests, enable only the tested plugin.
const QString testId = qApp->property("CopyQ_test_id").toString();
if ( !testId.isEmpty() )
return loader->id() == testId;
#endif
return enabled;
}
| 18,746
|
C++
|
.cpp
| 537
| 28.173184
| 117
| 0.644819
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,139
|
persistentdisplayitem.cpp
|
hluk_CopyQ/src/item/persistentdisplayitem.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "persistentdisplayitem.h"
#include "common/mimetypes.h"
#include "gui/traymenu.h"
#include "item/itemdelegate.h"
#include <QAction>
namespace {
bool dataEquals(const QVariantMap &lhs, const QVariantMap &rhs)
{
for (auto it = lhs.constBegin(); it != lhs.constEnd(); ++it) {
if ( it.value().toByteArray() != rhs.value(it.key()).toByteArray() )
return false;
}
return true;
}
} // namespace
PersistentDisplayItem::PersistentDisplayItem(ItemDelegate *delegate,
const QVariantMap &data,
QWidget *widget)
: m_data(data)
, m_widget(widget)
, m_delegate(delegate)
{
// Avoid accessing current selection in Display commands.
if ( !m_data.contains(mimeCurrentTab) )
m_data[mimeSelectedItems] = QByteArray();
}
PersistentDisplayItem::PersistentDisplayItem(QAction *action, const QVariantMap &data)
: m_data(data)
, m_action(action)
{
}
bool PersistentDisplayItem::isValid()
{
return !m_action.isNull() || (
!m_widget.isNull() && !m_delegate.isNull()
&& !m_delegate->invalidateHidden(m_widget.data()) );
}
void PersistentDisplayItem::setData(const QVariantMap &data)
{
if ( data.isEmpty() || dataEquals(data, m_data) )
return;
if ( !m_action.isNull() ) {
TrayMenu::updateTextFromData(m_action, data);
TrayMenu::updateIconFromData(m_action, data);
} else if ( !m_widget.isNull() && !m_delegate.isNull() ) {
m_delegate->updateWidget(m_widget, data);
}
}
| 1,557
|
C++
|
.cpp
| 49
| 27.44898
| 86
| 0.676687
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,140
|
clipboarditem.cpp
|
hluk_CopyQ/src/item/clipboarditem.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "clipboarditem.h"
#include "common/contenttype.h"
#include "common/mimetypes.h"
#include "common/textdata.h"
#include "item/serialize.h"
#include <QBrush>
#include <QByteArray>
#include <QString>
#include <QStringList>
#include <QVariant>
namespace {
void clearDataExceptInternal(QVariantMap *data)
{
QMutableMapIterator<QString, QVariant> it(*data);
while (it.hasNext()) {
const auto item = it.next();
if ( !item.key().startsWith(COPYQ_MIME_PREFIX) )
it.remove();
}
}
} // namespace
ClipboardItem::ClipboardItem()
: m_data()
, m_hash(0)
{
}
ClipboardItem::ClipboardItem(const QVariantMap &data)
: m_data(data)
, m_hash(0)
{
}
bool ClipboardItem::operator ==(const ClipboardItem &item) const
{
return dataHash() == item.dataHash();
}
void ClipboardItem::setText(const QString &text)
{
QMutableMapIterator<QString, QVariant> it(m_data);
while (it.hasNext()) {
const auto item = it.next();
if ( item.key().startsWith("text/") )
it.remove();
}
setTextData(&m_data, text);
invalidateDataHash();
}
bool ClipboardItem::setData(const QVariantMap &data)
{
if (m_data == data)
return false;
const auto oldData = m_data;
m_data = data;
for (auto it = oldData.constBegin(); it != oldData.constEnd(); ++it) {
if (it.key().startsWith(mimePrivatePrefix) && !m_data.contains(it.key()))
m_data[it.key()] = it.value();
}
invalidateDataHash();
return true;
}
bool ClipboardItem::updateData(const QVariantMap &data)
{
const int oldSize = m_data.size();
for (auto it = data.constBegin(); it != data.constEnd(); ++it) {
const auto &format = it.key();
if ( !format.startsWith(COPYQ_MIME_PREFIX) ) {
clearDataExceptInternal(&m_data);
break;
}
}
bool changed = (oldSize != m_data.size());
for (auto it = data.constBegin(); it != data.constEnd(); ++it) {
const auto &format = it.key();
const auto &value = it.value();
if ( !value.isValid() ) {
m_data.remove(format);
changed = true;
} else if ( m_data.value(format) != value ) {
m_data.insert(format, value);
changed = true;
}
}
invalidateDataHash();
return changed;
}
void ClipboardItem::removeData(const QString &mimeType)
{
m_data.remove(mimeType);
invalidateDataHash();
}
bool ClipboardItem::removeData(const QStringList &mimeTypeList)
{
bool removed = false;
for (const auto &mimeType : mimeTypeList) {
if ( m_data.contains(mimeType) ) {
m_data.remove(mimeType);
removed = true;
}
}
if (removed)
invalidateDataHash();
return removed;
}
void ClipboardItem::setData(const QString &mimeType, const QByteArray &data)
{
m_data.insert(mimeType, data);
invalidateDataHash();
}
QVariant ClipboardItem::data(int role) const
{
switch(role) {
case Qt::DisplayRole:
case Qt::EditRole:
return getTextData(m_data);
case contentType::data:
return m_data; // copy-on-write, so this should be fast
case contentType::hasText:
return m_data.contains(mimeText)
|| m_data.contains(mimeTextUtf8)
|| m_data.contains(mimeUriList);
case contentType::hasHtml:
return m_data.contains(mimeHtml);
case contentType::text:
return getTextData(m_data);
case contentType::html:
return getTextData(m_data, mimeHtml);
case contentType::notes:
return getTextData(m_data, mimeItemNotes);
case contentType::color:
return getTextData(m_data, mimeColor);
case contentType::isHidden:
return m_data.contains(mimeHidden);
}
return QVariant();
}
unsigned int ClipboardItem::dataHash() const
{
if (m_hash == 0)
m_hash = hash(m_data);
return m_hash;
}
void ClipboardItem::invalidateDataHash()
{
m_hash = 0;
}
| 4,063
|
C++
|
.cpp
| 145
| 22.765517
| 81
| 0.641699
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,141
|
itemwidgetwrapper.cpp
|
hluk_CopyQ/src/item/itemwidgetwrapper.cpp
|
#include "itemwidgetwrapper.h"
#include <QSize>
ItemWidgetWrapper::ItemWidgetWrapper(ItemWidget *childItem, QWidget *widget)
: ItemWidget(widget)
, m_childItem(childItem)
{
}
void ItemWidgetWrapper::updateSize(QSize maximumSize, int idealWidth)
{
childItem()->updateSize(maximumSize, idealWidth);
}
void ItemWidgetWrapper::setCurrent(bool current)
{
childItem()->setCurrent(current);
}
void ItemWidgetWrapper::setTagged(bool tagged)
{
childItem()->setTagged(tagged);
}
| 494
|
C++
|
.cpp
| 19
| 23.684211
| 76
| 0.787234
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,142
|
itemeditorwidget.cpp
|
hluk_CopyQ/src/item/itemeditorwidget.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "item/itemeditorwidget.h"
#include "item/itemwidget.h"
#include "common/contenttype.h"
#include "common/mimetypes.h"
#include "common/textdata.h"
#include "gui/iconfactory.h"
#include "gui/icons.h"
#include <QAbstractItemModel>
#include <QAction>
#include <QColorDialog>
#include <QFontDialog>
#include <QIcon>
#include <QMimeData>
#include <QPlainTextEdit>
#include <QTextCharFormat>
#include <QTextCursor>
#include <QTextDocument>
#include <QTextFrame>
#include <QToolBar>
namespace {
bool containsRichText(const QTextDocument &document)
{
return document.allFormats().size() > 3;
}
QString findImageFormat(const QMimeData &data)
{
const auto imageFormats = {"image/svg+xml", "image/png", "image/bmp", "image/jpeg", "image/gif"};
for (const auto &format : imageFormats) {
if ( data.hasFormat(format) )
return format;
}
return QString();
}
QAction *addMenuItem(const MenuItem &menuItem, QToolBar *toolBar, ItemEditorWidget *parent)
{
QAction *act = new QAction( getIcon(menuItem.iconName, menuItem.iconId), menuItem.text, parent );
act->setShortcuts(menuItem.shortcuts);
toolBar->addAction(act);
return act;
}
} // namespace
ItemEditorWidget::ItemEditorWidget(const QModelIndex &index, const QString &format, QWidget *parent)
: QTextEdit(parent)
, m_index(index)
, m_saveOnReturnKey(false)
, m_format(format)
{
setFrameShape(QFrame::NoFrame);
setFocusPolicy(Qt::StrongFocus);
}
bool ItemEditorWidget::isValid() const
{
return m_index.isValid();
}
bool ItemEditorWidget::hasChanges() const
{
return isValid() && document()->isModified();
}
void ItemEditorWidget::setHasChanges(bool hasChanges)
{
document()->setModified(hasChanges);
}
void ItemEditorWidget::setSaveOnReturnKey(bool enabled)
{
m_saveOnReturnKey = enabled;
}
QVariantMap ItemEditorWidget::data() const
{
QVariantMap data;
if (m_format == mimeText) {
setTextData( &data, toPlainText(), mimeText );
if ( containsRichText(*document()) )
setTextData( &data, toHtml(), mimeHtml );
} else {
setTextData( &data, toPlainText(), m_format );
}
return data;
}
void ItemEditorWidget::search(const ItemFilterPtr &filter)
{
if ( !filter || filter->matchesNone() )
return;
auto tc = textCursor();
tc.setPosition(tc.selectionStart());
setTextCursor(tc);
m_filter = filter;
findNext();
}
void ItemEditorWidget::findNext()
{
search(false);
}
void ItemEditorWidget::findPrevious()
{
search(true);
}
void ItemEditorWidget::keyPressEvent(QKeyEvent *event)
{
QKeyEvent *keyevent = static_cast<QKeyEvent *>(event);
int k = keyevent->key();
if (k == Qt::Key_Return || k == Qt::Key_Enter) {
Qt::KeyboardModifiers mods = keyevent->modifiers();
if ( (mods & (Qt::ShiftModifier | Qt::AltModifier | Qt::MetaModifier)) == 0 ) {
bool controlPressed = mods.testFlag(Qt::ControlModifier);
if (m_saveOnReturnKey && controlPressed ) {
keyevent->setModifiers(mods & ~Qt::ControlModifier);
} else if ( m_saveOnReturnKey || controlPressed ) {
saveAndExit();
return;
}
}
}
QTextEdit::keyPressEvent(event);
}
bool ItemEditorWidget::canInsertFromMimeData(const QMimeData *source) const
{
return source->hasImage() || QTextEdit::canInsertFromMimeData(source);
}
void ItemEditorWidget::insertFromMimeData(const QMimeData *source)
{
const QString mime = findImageFormat(*source);
if (!mime.isEmpty()) {
const QByteArray imageData = source->data(mime);
textCursor().insertHtml(
"<img src=\"data:" + mime + ";base64," + imageData.toBase64() + "\" />");
} else {
QTextEdit::insertFromMimeData(source);
}
}
void ItemEditorWidget::saveAndExit()
{
emit save();
emit invalidate();
}
void ItemEditorWidget::changeSelectionFont()
{
QTextCursor tc = textCursor();
QTextCharFormat format = tc.charFormat();
QFontDialog dialog(this);
dialog.setOptions(dialog.options() | QFontDialog::DontUseNativeDialog);
dialog.setCurrentFont( format.font() );
if ( dialog.exec() == QDialog::Accepted ) {
const QFont font = dialog.selectedFont();
format.setFont(font);
tc.setCharFormat(format);
}
}
void ItemEditorWidget::toggleBoldText()
{
QTextCursor tc = textCursor();
QTextCharFormat format = tc.charFormat();
const int weight = format.fontWeight() == QFont::Bold ? QFont::Normal : QFont::Bold;
format.setFontWeight(weight);
tc.setCharFormat(format);
}
void ItemEditorWidget::toggleItalicText()
{
QTextCursor tc = textCursor();
QTextCharFormat format = tc.charFormat();
format.setFontItalic( !format.fontItalic() );
tc.setCharFormat(format);
}
void ItemEditorWidget::toggleUnderlineText()
{
QTextCursor tc = textCursor();
QTextCharFormat format = tc.charFormat();
format.setFontUnderline( !format.fontUnderline() );
tc.setCharFormat(format);
}
void ItemEditorWidget::toggleStrikethroughText()
{
QTextCursor tc = textCursor();
QTextCharFormat format = tc.charFormat();
format.setFontStrikeOut( !format.fontStrikeOut() );
tc.setCharFormat(format);
}
void ItemEditorWidget::setForeground()
{
QTextCursor tc = textCursor();
QTextCharFormat format = tc.charFormat();
QColorDialog dialog(this);
dialog.setOptions(dialog.options() | QColorDialog::ShowAlphaChannel | QColorDialog::DontUseNativeDialog);
dialog.setCurrentColor( format.foreground().color() );
if ( dialog.exec() == QDialog::Accepted ) {
const QColor color = dialog.selectedColor();
format.setForeground(color);
tc.setCharFormat(format);
}
}
void ItemEditorWidget::setBackground()
{
QTextCursor tc = textCursor();
QTextCharFormat format = tc.charFormat();
QColorDialog dialog(this);
dialog.setOptions(dialog.options() | QColorDialog::ShowAlphaChannel | QColorDialog::DontUseNativeDialog);
dialog.setCurrentColor( format.background().color() );
if ( dialog.exec() == QDialog::Accepted ) {
const QColor color = dialog.selectedColor();
format.setBackground(color);
tc.setCharFormat(format);
}
}
void ItemEditorWidget::eraseStyle()
{
textCursor().setCharFormat( QTextCharFormat() );
}
QWidget *ItemEditorWidget::createToolbar(QWidget *parent, const MenuItems &menuItems)
{
auto toolBar = new QToolBar(parent);
QAction *act;
act = addMenuItem(menuItems[Actions::Editor_Save], toolBar, this);
connect( act, &QAction::triggered,
this, &ItemEditorWidget::saveAndExit );
act = addMenuItem(menuItems[Actions::Editor_Cancel], toolBar, this);
connect( act, &QAction::triggered,
this, &ItemEditorWidget::cancel );
auto doc = document();
toolBar->addSeparator();
act = addMenuItem(menuItems[Actions::Editor_Undo], toolBar, this);
act->setEnabled(false);
connect( act, &QAction::triggered, doc, static_cast<void (QTextDocument::*)()>(&QTextDocument::undo) );
connect( doc, &QTextDocument::undoAvailable, act, &QAction::setEnabled );
act = addMenuItem(menuItems[Actions::Editor_Redo], toolBar, this);
act->setEnabled(false);
connect( act, &QAction::triggered, doc, static_cast<void (QTextDocument::*)()>(&QTextDocument::redo) );
connect( doc, &QTextDocument::redoAvailable, act, &QAction::setEnabled );
toolBar->addSeparator();
act = addMenuItem(menuItems[Actions::Editor_Font], toolBar, this);
connect( act, &QAction::triggered,
this, &ItemEditorWidget::changeSelectionFont );
act = addMenuItem(menuItems[Actions::Editor_Bold], toolBar, this);
connect( act, &QAction::triggered,
this, &ItemEditorWidget::toggleBoldText );
act = addMenuItem(menuItems[Actions::Editor_Italic], toolBar, this);
connect( act, &QAction::triggered,
this, &ItemEditorWidget::toggleItalicText );
act = addMenuItem(menuItems[Actions::Editor_Underline], toolBar, this);
connect( act, &QAction::triggered,
this, &ItemEditorWidget::toggleUnderlineText );
act = addMenuItem(menuItems[Actions::Editor_Strikethrough], toolBar, this);
connect( act, &QAction::triggered,
this, &ItemEditorWidget::toggleStrikethroughText );
toolBar->addSeparator();
act = addMenuItem(menuItems[Actions::Editor_Foreground], toolBar, this);
connect( act, &QAction::triggered,
this, &ItemEditorWidget::setForeground );
act = addMenuItem(menuItems[Actions::Editor_Background], toolBar, this);
connect( act, &QAction::triggered,
this, &ItemEditorWidget::setBackground );
toolBar->addSeparator();
act = addMenuItem(menuItems[Actions::Editor_EraseStyle], toolBar, this);
connect( act, &QAction::triggered,
this, &ItemEditorWidget::eraseStyle );
toolBar->addSeparator();
act = addMenuItem(menuItems[Actions::Editor_Search], toolBar, this);
connect( act, &QAction::triggered,
this, &ItemEditorWidget::searchRequest );
return toolBar;
}
void ItemEditorWidget::search(bool backwards)
{
if (m_filter)
m_filter->search(this, backwards);
}
| 9,373
|
C++
|
.cpp
| 265
| 30.573585
| 109
| 0.699392
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,143
|
serialize.cpp
|
hluk_CopyQ/src/item/serialize.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "serialize.h"
#include "common/contenttype.h"
#include "common/log.h"
#include "common/mimetypes.h"
#include <QAbstractItemModel>
#include <QCoreApplication>
#include <QByteArray>
#include <QCryptographicHash>
#include <QDataStream>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QIODevice>
#include <QList>
#include <QPair>
#include <QSaveFile>
#include <QStringList>
#include <unordered_map>
class DataFile {
public:
DataFile() {}
explicit DataFile(const QString &path)
: m_path(path)
{}
const QString &path() const { return m_path; }
void setPath(const QString &path) { m_path = path; }
qint64 size() const
{
return QFileInfo(m_path).size();
}
QString toString() const { return m_path; }
QByteArray readAll() const
{
QFile f(m_path);
if ( !f.open(QIODevice::ReadOnly) ) {
log( QStringLiteral("Failed to read file \"%1\": %2")
.arg(m_path, f.errorString()), LogError );
return QByteArray();
}
return f.readAll();
}
bool operator==(const DataFile &other) const {
return m_path == other.m_path;
}
private:
QString m_path;
};
Q_DECLARE_METATYPE(DataFile)
QDataStream &operator<<(QDataStream &out, DataFile value)
{
return out << value.path();
}
QDataStream &operator>>(QDataStream &in, DataFile &value)
{
QString path;
in >> path;
value.setPath(path);
return in;
}
namespace {
const QLatin1String mimeFilePrefix("FILE:");
template <typename T>
bool readOrError(QDataStream *out, T *value, const char *error)
{
*out >> *value;
if ( out->status() == QDataStream::Ok )
return true;
log( QString("Corrupted data: %1").arg(error), LogError );
return false;
}
const std::unordered_map<int, QString> &idToMime()
{
static const std::unordered_map<int, QString> map({
{1, QLatin1String(mimeWindowTitle)},
{2, QLatin1String(mimeItemNotes)},
{3, QLatin1String(COPYQ_MIME_PREFIX)},
{4, QLatin1String(mimeText)},
{5, QLatin1String(mimeHtml)},
{6, QLatin1String(mimeUriList)},
{7, QLatin1String("image/")},
{8, QLatin1String("text/")},
{9, QLatin1String("application/")},
{10, QLatin1String("audio/")},
{11, QLatin1String("video/")}
});
return map;
}
QString decompressMime(QDataStream *out)
{
QString mime;
if ( !readOrError(out, &mime, "Failed to read MIME type") )
return QString();
bool ok;
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
const int id = mime.midRef(0, 1).toInt(&ok, 16);
#else
const int id = QStringView(mime).mid(0, 1).toInt(&ok, 16);
#endif
if (!ok) {
log("Corrupted data: Failed to parse MIME type ID", LogError);
out->setStatus(QDataStream::ReadCorruptData);
return QString();
}
if (id == 0)
return mime.mid(1);
const auto it = idToMime().find(id);
if ( it != std::end(idToMime()) )
return it->second + mime.mid(1);
log("Corrupted data: Failed to decompress MIME type", LogError);
out->setStatus(QDataStream::ReadCorruptData);
return QString();
}
QString compressMime(const QString &mime)
{
for (const auto &idMime : idToMime()) {
if ( mime.startsWith(idMime.second) ) {
const auto prefixSize = idMime.second.size();
return QString::number(idMime.first, 16) + mime.mid(prefixSize);
}
}
return "0" + mime;
}
bool deserializeDataV2(QDataStream *out, QVariantMap *data)
{
qint32 size;
if ( !readOrError(out, &size, "Failed to read size (v2)") )
return false;
QByteArray tmpBytes;
bool compress = false;
for (qint32 i = 0; i < size; ++i) {
QString mime = decompressMime(out);
if ( out->status() != QDataStream::Ok )
return false;
const bool hasDataFile = mime.startsWith(mimeFilePrefix);
if ( !readOrError(out, &compress, "Failed to read compression flag (v2)") )
return false;
if ( !readOrError(out, &tmpBytes, "Failed to read item data (v2)") )
return false;
if (compress) {
tmpBytes = qUncompress(tmpBytes);
if ( tmpBytes.isEmpty() ) {
log("Corrupted data: Failed to decompress data (v2)", LogError);
out->setStatus(QDataStream::ReadCorruptData);
return false;
}
}
if (hasDataFile) {
mime = mime.mid( mimeFilePrefix.size() );
const QString path = QString::fromUtf8(tmpBytes);
const QVariant value = QVariant::fromValue(DataFile(path));
Q_ASSERT(value.canConvert<QByteArray>());
Q_ASSERT(value.value<DataFile>().path() == path);
data->insert(mime, value);
} else {
data->insert(mime, tmpBytes);
}
}
return out->status() == QDataStream::Ok;
}
QString dataFilePath(const QByteArray &bytes, bool create = false)
{
QDir dir(itemDataPath());
QCryptographicHash hash(QCryptographicHash::Sha256);
hash.addData(QByteArrayLiteral("copyq_salt"));
hash.addData(bytes);
const QString sha = QString::fromUtf8( hash.result().toHex() );
const QString subpath = QStringLiteral("%1/%2/%3").arg(
sha.mid(0, 16),
sha.mid(16, 16),
sha.mid(32, 16)
);
if (create && !dir.mkpath(subpath)) {
log( QStringLiteral("Failed to create data directory: %1")
.arg(dir.absoluteFilePath(subpath)), LogError );
return QString();
}
return dir.absoluteFilePath(
QStringLiteral("%1/%2.dat").arg(subpath, sha.mid(48)) );
}
} // namespace
void registerDataFileConverter()
{
QMetaType::registerConverter(&DataFile::readAll);
QMetaType::registerConverter(&DataFile::toString);
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
qRegisterMetaTypeStreamOperators<DataFile>("DataFile");
#else
qRegisterMetaType<DataFile>("DataFile");
#endif
}
void serializeData(QDataStream *stream, const QVariantMap &data, int itemDataThreshold)
{
*stream << static_cast<qint32>(-2);
const qint32 size = data.size();
*stream << size;
for (auto it = data.constBegin(); it != data.constEnd(); ++it) {
const QString &mime = it.key();
const QVariant &value = it.value();
const DataFile dataFile = value.value<DataFile>();
const int dataLength = dataFile.path().isEmpty()
? value.toByteArray().size() : dataFile.size();
if ( (itemDataThreshold >= 0 && dataLength > itemDataThreshold) || mime.startsWith(mimeFilePrefix) ) {
QString path = dataFile.path();
// Already saved into a separate data file?
if ( path.isEmpty() ) {
const QByteArray bytes = value.toByteArray();
path = dataFilePath(bytes, true);
if ( path.isEmpty() ) {
stream->setStatus(QDataStream::WriteFailed);
return;
}
if ( !QFile::exists(path) ) {
QSaveFile f(path);
f.setDirectWriteFallback(false);
if ( !f.open(QIODevice::WriteOnly) || !f.write(bytes) || !f.commit() ) {
log( QStringLiteral("Failed to create data file \"%1\": %2")
.arg(path, f.errorString()),
LogError );
stream->setStatus(QDataStream::WriteFailed);
f.cancelWriting();
return;
}
}
}
if ( mime.startsWith(mimeFilePrefix) )
*stream << compressMime(mime);
else
*stream << compressMime(mimeFilePrefix + mime);
*stream << /* compressData = */ false
<< path.toUtf8();
} else {
const QByteArray bytes = value.toByteArray();
*stream << compressMime(mime)
<< /* compressData = */ false
<< bytes;
}
}
}
bool deserializeData(QDataStream *stream, QVariantMap *data)
{
try {
qint32 length;
if ( !readOrError(stream, &length, "Failed to read length") )
return false;
if (length == -2)
return deserializeDataV2(stream, data);
if (length < 0) {
log("Corrupted data: Invalid length (v1)", LogError);
stream->setStatus(QDataStream::ReadCorruptData);
return false;
}
// Deprecated format.
// TODO: Data should be saved again in new format.
QString mime;
QByteArray tmpBytes;
for (qint32 i = 0; i < length; ++i) {
if ( !readOrError(stream, &mime, "Failed to read MIME type (v1)") )
return false;
if ( !readOrError(stream, &tmpBytes, "Failed to read item data (v1)") )
return false;
if( !tmpBytes.isEmpty() ) {
tmpBytes = qUncompress(tmpBytes);
if ( tmpBytes.isEmpty() ) {
log("Corrupted data: Failed to decompress data (v1)", LogError);
stream->setStatus(QDataStream::ReadCorruptData);
return false;
}
}
data->insert(mime, tmpBytes);
}
} catch (const std::exception &e) {
log( QString("Data deserialization failed: %1").arg(e.what()), LogError );
stream->setStatus(QDataStream::ReadCorruptData);
return false;
}
return stream->status() == QDataStream::Ok;
}
QByteArray serializeData(const QVariantMap &data)
{
QByteArray bytes;
QDataStream out(&bytes, QIODevice::WriteOnly);
serializeData(&out, data);
return bytes;
}
bool deserializeData(QVariantMap *data, const QByteArray &bytes)
{
QDataStream out(bytes);
return deserializeData(&out, data);
}
bool serializeData(const QAbstractItemModel &model, QDataStream *stream, int itemDataThreshold)
{
qint32 length = model.rowCount();
*stream << length;
for(qint32 i = 0; i < length && stream->status() == QDataStream::Ok; ++i) {
const QVariantMap data = model.data(model.index(i, 0), contentType::data).toMap();
serializeData(stream, data, itemDataThreshold);
}
return stream->status() == QDataStream::Ok;
}
bool deserializeData(QAbstractItemModel *model, QDataStream *stream, int maxItems)
{
qint32 length;
if ( !readOrError(stream, &length, "Failed to read length") )
return false;
if (length < 0) {
log("Corrupted data: Invalid length", LogError);
stream->setStatus(QDataStream::ReadCorruptData);
return false;
}
// Limit the loaded number of items to model's maximum.
length = qMin(length, maxItems) - model->rowCount();
if ( length != 0 && !model->insertRows(0, length) )
return false;
for(qint32 i = 0; i < length; ++i) {
QVariantMap data;
if ( !deserializeData(stream, &data) )
return false;
if ( !model->setData(model->index(i, 0), data, contentType::data) ) {
log("Failed to set model data", LogError);
stream->setStatus(QDataStream::ReadCorruptData);
return false;
}
}
return stream->status() == QDataStream::Ok;
}
bool serializeData(const QAbstractItemModel &model, QIODevice *file, int itemDataThreshold)
{
QDataStream stream(file);
stream.setVersion(QDataStream::Qt_4_7);
return serializeData(model, &stream, itemDataThreshold);
}
bool deserializeData(QAbstractItemModel *model, QIODevice *file, int maxItems)
{
QDataStream stream(file);
stream.setVersion(QDataStream::Qt_4_7);
return deserializeData(model, &stream, maxItems);
}
bool itemDataFiles(QIODevice *file, QStringList *files)
{
QDataStream out(file);
out.setVersion(QDataStream::Qt_4_7);
qint32 length;
if ( !readOrError(&out, &length, "Failed to read length") )
return false;
if (length < 0) {
log("Corrupted data: Invalid length", LogError);
return false;
}
for(qint32 i = 0; i < length; ++i) {
qint32 version;
if ( !readOrError(&out, &version, "Failed to read version") )
return false;
if (version != -2)
return true;
qint32 size;
if ( !readOrError(&out, &size, "Failed to read size (v2)") )
return false;
QByteArray tmpBytes;
bool compress;
for (qint32 j = 0; j < size; ++j) {
QString mime = decompressMime(&out);
if ( out.status() != QDataStream::Ok )
return false;
const bool hasDataFile = mime.startsWith(mimeFilePrefix);
if ( !readOrError(&out, &compress, "Failed to read compression flag (v2)") )
return false;
if ( !readOrError(&out, &tmpBytes, "Failed to read item data (v2)") )
return false;
if (hasDataFile) {
const QString path = QString::fromUtf8(tmpBytes);
files->append(path);
}
}
}
return out.status() == QDataStream::Ok;
}
QString itemDataPath()
{
return qApp->property("CopyQ_item_data_path").toString();
}
| 13,483
|
C++
|
.cpp
| 381
| 27.493438
| 110
| 0.599048
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,144
|
itemeditor.cpp
|
hluk_CopyQ/src/item/itemeditor.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemeditor.h"
#include "common/action.h"
#include "common/mimetypes.h"
#include "common/log.h"
#include "common/processsignals.h"
#include "common/temporaryfile.h"
#include <QDir>
#include <QFile>
#include <QHash>
#include <QTemporaryFile>
#include <QTimer>
#include <cstdio>
namespace {
QString getFileSuffixFromMime(const QString &mime)
{
if (mime == mimeText)
return QLatin1String(".txt");
if (mime == "text/html")
return QLatin1String(".html");
if (mime == "text/xml")
return QLatin1String(".xml");
if (mime == "image/bmp")
return QLatin1String(".bmp");
if (mime == "image/jpeg")
return QLatin1String(".jpg");
if (mime == "image/png")
return QLatin1String(".png");
if (mime == "image/gif")
return QLatin1String(".gif");
if (mime == "image/svg+xml" || mime == "image/x-inkscape-svg-compressed")
return QLatin1String(".svg");
if (mime == COPYQ_MIME_PREFIX "theme")
return QLatin1String(".ini");
return QString();
}
} // namespace
ItemEditor::ItemEditor(const QByteArray &data, const QString &mime, const QString &editor,
QObject *parent)
: QObject(parent)
, m_data(data)
, m_mime(mime)
, m_hash( qHash(m_data) )
, m_editorcmd(editor)
, m_editor(nullptr)
, m_timer( new QTimer(this) )
, m_info()
, m_lastmodified()
, m_lastSize(0)
, m_modified(false)
{
if ( !m_editorcmd.contains("%1") )
m_editorcmd.append(" %1");
}
ItemEditor::~ItemEditor()
{
if (m_editor && m_editor->isRunning())
m_editor->terminate();
QString tmpPath = m_info.filePath();
if ( !tmpPath.isEmpty() ) {
if ( !QFile::remove(tmpPath) )
log( QString("Failed to remove temporary file (%1)").arg(tmpPath), LogError );
}
}
void ItemEditor::setIndex(const QModelIndex &index)
{
m_index = index;
}
bool ItemEditor::start()
{
// create temp file
QTemporaryFile tmpfile;
const auto suffix = getFileSuffixFromMime(m_mime);
if ( !openTemporaryFile(&tmpfile, suffix) ) {
log("Failed to create temporary file for external editor", LogError);
return false;
}
const auto fileName = tmpfile.fileName();
// write text to temp file
tmpfile.write(m_data);
// Close file before launching editor (this is required on Windows).
tmpfile.setAutoRemove(false);
tmpfile.close();
// monitor file
m_info.setFile(fileName);
m_lastmodified = m_info.lastModified();
m_lastSize = m_info.size();
m_timer->start(500);
connect( m_timer, &QTimer::timeout,
this, &ItemEditor::onTimer );
// create editor process
m_editor = new Action(this);
connect(m_editor, &Action::actionFinished, this, &ItemEditor::close);
// use native path for filename to edit
const auto nativeFilePath = QDir::toNativeSeparators( m_info.absoluteFilePath() );
// execute editor
m_editor->setCommand(m_editorcmd, {nativeFilePath});
COPYQ_LOG( QString("Starting editor command: %1").arg(m_editor->commandLine()) );
m_editor->start();
return true;
}
void ItemEditor::close()
{
if (m_editor && (m_editor->actionFailed() || m_editor->exitCode() != 0) ) {
const QString errorString = m_editor->errorString();
if ( !errorString.isEmpty() )
log( QString("Editor command error: %1").arg(errorString), LogWarning );
const int exitCode = m_editor->exitCode();
if (exitCode != 0)
log( QString("Editor command exit code: %1").arg(exitCode), LogWarning );
const QString errorOutput = QString::fromUtf8(m_editor->errorOutput());
if ( !errorOutput.isEmpty() )
log( QString("Editor command stderr: %1").arg(errorOutput), LogWarning );
if ( m_editor->actionFailed() )
emit error( tr("Editor command failed (see logs)") );
}
if ( m_modified || wasFileModified() )
emit fileModified(m_data, m_mime, m_index);
emit closed(this, m_index);
}
bool ItemEditor::wasFileModified()
{
m_info.refresh();
if ( m_lastmodified != m_info.lastModified() || m_lastSize != m_info.size() ) {
m_lastmodified = m_info.lastModified();
m_lastSize = m_info.size();
// read text
QFile file( m_info.filePath() );
if ( file.open(QIODevice::ReadOnly) ) {
m_data = file.readAll();
file.close();
} else {
log( QString("Failed to read temporary file (%1)!").arg(m_info.fileName()),
LogError );
}
// new hash
uint newhash = qHash(m_data);
return newhash != m_hash;
}
return false;
}
void ItemEditor::onTimer()
{
if (m_modified) {
// Wait until file is fully overwritten.
if ( !wasFileModified() ) {
m_modified = false;
emit fileModified(m_data, m_mime, m_index);
m_hash = qHash(m_data);
}
} else {
m_modified = wasFileModified();
}
}
| 5,111
|
C++
|
.cpp
| 154
| 27.214286
| 90
| 0.619618
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,145
|
itemwidget.cpp
|
hluk_CopyQ/src/item/itemwidget.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemwidget.h"
#include "common/command.h"
#include "common/contenttype.h"
#include "common/mimetypes.h"
#include "item/itemeditor.h"
#include <QAbstractItemModel>
#include <QApplication>
#include <QDesktopServices>
#include <QEvent>
#include <QMimeData>
#include <QModelIndex>
#include <QMouseEvent>
#include <QPersistentModelIndex>
#include <QTextEdit>
#include <QUrl>
#include <QWidget>
namespace {
bool canMouseInteract(const QMouseEvent &event)
{
return event.modifiers() & Qt::ShiftModifier;
}
} // namespace
ItemWidget::ItemWidget(QWidget *widget)
: m_widget(widget)
{
Q_ASSERT(widget != nullptr);
// Object name for style sheet.
widget->setObjectName("item");
// Item widgets are not focusable.
widget->setFocusPolicy(Qt::NoFocus);
// Limit size of items.
widget->setMaximumSize(2048, 2048);
// Disable drag'n'drop by default.
widget->setAcceptDrops(false);
}
void ItemWidget::updateSize(QSize maximumSize, int idealWidth)
{
QWidget *w = widget();
w->setMaximumSize(maximumSize);
const int idealHeight = w->heightForWidth(idealWidth);
const int maximumHeight = w->heightForWidth(maximumSize.width());
if (idealHeight <= 0 && maximumHeight <= 0)
w->resize(w->sizeHint());
else if (idealHeight != maximumHeight)
w->setFixedSize( maximumSize.width(), maximumHeight );
else
w->setFixedSize(idealWidth, idealHeight);
}
void ItemWidget::setCurrent(bool current)
{
// Propagate mouse events to item list until the item is selected.
widget()->setAttribute(Qt::WA_TransparentForMouseEvents, !current);
}
bool ItemWidget::filterMouseEvents(QTextEdit *edit, QEvent *event)
{
const auto type = event->type();
bool allowMouseInteraction = true;
switch (type) {
case QEvent::Enter:
edit->setMouseTracking(true);
edit->viewport()->setCursor( QCursor() );
return false;
case QEvent::MouseButtonPress:
case QEvent::MouseButtonDblClick: {
QMouseEvent *e = static_cast<QMouseEvent*>(event);
if ( !canMouseInteract(*e) )
allowMouseInteraction = false;
else if (e->button() == Qt::LeftButton)
edit->setTextCursor( edit->cursorForPosition(e->pos()) );
break;
}
case QEvent::MouseMove: {
QMouseEvent *e = static_cast<QMouseEvent*>(event);
if ( !canMouseInteract(*e) )
allowMouseInteraction = false;
break;
}
case QEvent::MouseButtonRelease: {
QMouseEvent *e = static_cast<QMouseEvent*>(event);
if ( canMouseInteract(*e) && edit->textCursor().hasSelection() )
edit->copy();
allowMouseInteraction = false;
break;
}
default:
return false;
}
Qt::TextInteractionFlags flags = edit->textInteractionFlags();
if (allowMouseInteraction) {
flags |= Qt::TextSelectableByMouse;
flags |= Qt::LinksAccessibleByMouse;
} else {
flags &= ~Qt::TextSelectableByMouse;
flags &= ~Qt::LinksAccessibleByMouse;
}
edit->setTextInteractionFlags(flags);
if (type == QEvent::MouseButtonPress || type == QEvent::MouseMove) {
const auto e = static_cast<QMouseEvent*>(event);
if (allowMouseInteraction) {
const auto anchor = edit->anchorAt(e->pos());
if ( anchor.isEmpty() ) {
edit->viewport()->setCursor( QCursor(Qt::IBeamCursor) );
} else {
edit->viewport()->setCursor( QCursor(Qt::PointingHandCursor) );
if (type == QEvent::MouseButtonPress) {
QDesktopServices::openUrl( QUrl(anchor) );
e->accept();
return true;
}
}
} else {
edit->viewport()->setCursor( QCursor() );
}
}
return false;
}
QVariant ItemScriptable::call(const QString &method, const QVariantList &arguments)
{
QVariant result;
QMetaObject::invokeMethod(
m_scriptable, "call", Qt::DirectConnection,
Q_RETURN_ARG(QVariant, result),
Q_ARG(QString, method),
Q_ARG(QVariantList, arguments));
return result;
}
QVariant ItemScriptable::eval(const QString &script)
{
return call("eval", QVariantList() << script);
}
QVariantList ItemScriptable::currentArguments()
{
QVariantList arguments;
QMetaObject::invokeMethod(
m_scriptable, "currentArguments", Qt::DirectConnection,
Q_RETURN_ARG(QVariantList, arguments) );
return arguments;
}
void ItemScriptable::throwError(const QString &message)
{
QMetaObject::invokeMethod(
m_scriptable, "throwException", Qt::DirectConnection,
Q_ARG(QString, message) );
}
bool ItemSaverInterface::saveItems(const QString &, const QAbstractItemModel &, QIODevice *)
{
return false;
}
bool ItemSaverInterface::canRemoveItems(const QList<QModelIndex> &, QString *)
{
return true;
}
bool ItemSaverInterface::canDropItem(const QModelIndex &)
{
return true;
}
bool ItemSaverInterface::canMoveItems(const QList<QModelIndex> &)
{
return true;
}
void ItemSaverInterface::itemsRemovedByUser(const QList<QPersistentModelIndex> &)
{
}
QVariantMap ItemSaverInterface::copyItem(const QAbstractItemModel &, const QVariantMap &itemData)
{
return itemData;
}
void ItemSaverInterface::setFocus(bool)
{
}
ItemWidget *ItemLoaderInterface::create(const QVariantMap &, QWidget *, bool) const
{
return nullptr;
}
QStringList ItemLoaderInterface::formatsToSave() const
{
return {};
}
bool ItemLoaderInterface::canLoadItems(QIODevice *) const
{
return false;
}
bool ItemLoaderInterface::canSaveItems(const QString &) const
{
return false;
}
ItemSaverPtr ItemLoaderInterface::loadItems(const QString &, QAbstractItemModel *, QIODevice *, int)
{
return nullptr;
}
ItemSaverPtr ItemLoaderInterface::initializeTab(const QString &, QAbstractItemModel *, int)
{
return nullptr;
}
ItemWidget *ItemLoaderInterface::transform(ItemWidget *, const QVariantMap &)
{
return nullptr;
}
ItemSaverPtr ItemLoaderInterface::transformSaver(const ItemSaverPtr &saver, QAbstractItemModel *)
{
return saver;
}
bool ItemLoaderInterface::matches(const QModelIndex &, const ItemFilter &) const
{
return false;
}
QObject *ItemLoaderInterface::tests(const TestInterfacePtr &) const
{
return nullptr;
}
const QObject *ItemLoaderInterface::signaler() const
{
return nullptr;
}
ItemScriptable *ItemLoaderInterface::scriptableObject()
{
return nullptr;
}
QVector<Command> ItemLoaderInterface::commands() const
{
return QVector<Command>();
}
bool ItemLoaderInterface::data(QVariantMap *, const QModelIndex &) const
{
return true;
}
bool ItemLoaderInterface::setData(const QVariantMap &, const QModelIndex &, QAbstractItemModel *) const
{
return false;
}
QObject *ItemLoaderInterface::createExternalEditor(const QModelIndex &, const QVariantMap &, QWidget *) const
{
return nullptr;
}
| 7,130
|
C++
|
.cpp
| 235
| 25.485106
| 109
| 0.69548
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,146
|
clipboardmodel.cpp
|
hluk_CopyQ/src/item/clipboardmodel.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "clipboardmodel.h"
#include "common/contenttype.h"
#include "common/mimetypes.h"
#include <QStringList>
#include <algorithm>
#include <functional>
namespace {
QList<QPersistentModelIndex> validIndeces(const QModelIndexList &indexList)
{
QList<QPersistentModelIndex> list;
list.reserve(indexList.size());
for (const auto &index : indexList) {
if ( index.isValid() )
list.append(index);
}
return list;
}
int topMostRow(const QList<QPersistentModelIndex> &indexList)
{
int row = indexList.value(0).row();
for (const auto &index : indexList)
row = qMin(row, index.row());
return row;
}
} // namespace
void ClipboardItemList::move(int from, int count, int to)
{
if (to < from) {
std::swap(from, to);
to += count;
count = to - from - count;
}
const auto start1 = std::begin(m_items) + from;
const auto start2 = start1 + count;
const auto end2 = std::begin(m_items) + to;
std::rotate(start1, start2, end2);
}
ClipboardModel::ClipboardModel(QObject *parent)
: QAbstractListModel(parent)
{
}
int ClipboardModel::rowCount(const QModelIndex&) const
{
return m_clipboardList.size();
}
QVariant ClipboardModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() >= m_clipboardList.size())
return QVariant();
return m_clipboardList[index.row()].data(role);
}
Qt::ItemFlags ClipboardModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::ItemIsEnabled;
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
bool ClipboardModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if ( !index.isValid() )
return false;
int row = index.row();
if (role == Qt::EditRole) {
m_clipboardList[row].setText(value.toString());
} else if (role == contentType::notes) {
const QString notes = value.toString();
if ( notes.isEmpty() )
m_clipboardList[row].removeData(mimeItemNotes);
else
m_clipboardList[row].setData( mimeItemNotes, notes.toUtf8() );
} else if (role == contentType::updateData) {
if ( !m_clipboardList[row].updateData(value.toMap()) )
return false;
} else if (role == contentType::data) {
ClipboardItem &item = m_clipboardList[row];
const QVariantMap dataMap = value.toMap();
// Emit dataChanged() only if really changed.
if ( !item.setData(dataMap) )
return true;
} else if (role >= contentType::removeFormats) {
if ( !m_clipboardList[row].removeData(value.toStringList()) )
return false;
} else {
return false;
}
emit dataChanged(index, index);
return true;
}
void ClipboardModel::insertItem(const QVariantMap &data, int row)
{
ClipboardItem item;
item.setData(data);
beginInsertRows(QModelIndex(), row, row);
m_clipboardList.insert(row, item);
endInsertRows();
}
void ClipboardModel::insertItems(const QVector<QVariantMap> &dataList, int row)
{
if ( dataList.isEmpty() )
return;
int targetRow = row;
m_clipboardList.reserve( m_clipboardList.size() + dataList.size() );
beginInsertRows(QModelIndex(), row, row + dataList.size() - 1);
for ( auto it = std::begin(dataList); it != std::end(dataList); ++it ) {
m_clipboardList.insert(targetRow, ClipboardItem(*it));
++targetRow;
}
endInsertRows();
}
void ClipboardModel::setItemsData(const QMap<QPersistentModelIndex, QVariantMap> &itemsData)
{
QPersistentModelIndex topIndex;
QPersistentModelIndex bottomIndex;
for (auto it = std::begin(itemsData); it != std::end(itemsData); ++it) {
const QPersistentModelIndex &index = it.key();
if ( !index.isValid() )
continue;
const int row = index.row();
ClipboardItem &item = m_clipboardList[row];
// Emit dataChanged() only if really changed.
if ( item.setData(it.value()) ) {
if ( !topIndex.isValid() ) {
topIndex = index;
bottomIndex = index;
} else {
topIndex = std::min(topIndex, index);
bottomIndex = std::max(bottomIndex, index);
}
}
}
if ( topIndex.isValid() )
emit dataChanged(topIndex, bottomIndex);
}
bool ClipboardModel::insertRows(int position, int rows, const QModelIndex&)
{
if ( rows <= 0 || position < 0 )
return false;
beginInsertRows(QModelIndex(), position, position + rows - 1);
for (int row = 0; row < rows; ++row)
m_clipboardList.insert(position, ClipboardItem());
endInsertRows();
return true;
}
bool ClipboardModel::removeRows(int position, int rows, const QModelIndex&)
{
if ( rows <= 0 || position < 0 || position + rows > rowCount() )
return false;
int last = qMin( position + rows, rowCount() ) - 1;
beginRemoveRows(QModelIndex(), position, last);
m_clipboardList.remove(position, last - position + 1);
endRemoveRows();
return true;
}
bool ClipboardModel::moveRows(
const QModelIndex &sourceParent, int sourceRow, int rows,
const QModelIndex &destinationParent, int destinationRow)
{
if (sourceParent.isValid() || destinationParent.isValid())
return false;
if (sourceRow < 0 || destinationRow < 0 || destinationRow > rowCount()
|| rows <= 0 || sourceRow + rows > rowCount())
{
return false;
}
const int last = sourceRow + rows - 1;
if (sourceRow <= destinationRow && destinationRow <= last + 1)
return false;
beginMoveRows(sourceParent, sourceRow, last, destinationParent, destinationRow);
m_clipboardList.move(sourceRow, rows, destinationRow);
endMoveRows();
return true;
}
void ClipboardModel::sortItems(const QModelIndexList &indexList, CompareItems *compare)
{
QList<QPersistentModelIndex> list = validIndeces(indexList);
std::sort( list.begin(), list.end(), compare );
sortItems(list);
}
void ClipboardModel::sortItems(const QList<QPersistentModelIndex> &sorted)
{
int targetRow = topMostRow(sorted);
for (const auto &ind : sorted) {
if (ind.isValid()) {
const int sourceRow = ind.row();
if (targetRow != sourceRow) {
beginMoveRows(QModelIndex(), sourceRow, sourceRow, QModelIndex(), targetRow);
m_clipboardList.move(sourceRow, targetRow);
endMoveRows();
// If the moved item was removed or moved further (as reaction on moving the item),
// stop sorting.
if (!ind.isValid() || ind.row() != targetRow)
break;
}
++targetRow;
}
}
}
int ClipboardModel::findItem(uint itemHash) const
{
for (int i = 0; i < m_clipboardList.size(); ++i) {
if ( m_clipboardList[i].dataHash() == itemHash )
return i;
}
return -1;
}
| 7,133
|
C++
|
.cpp
| 206
| 28.407767
| 99
| 0.643794
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,147
|
itemsaverwrapper.cpp
|
hluk_CopyQ/src/item/itemsaverwrapper.cpp
|
#include "itemsaverwrapper.h"
#include <QVariantMap>
ItemSaverWrapper::ItemSaverWrapper(const ItemSaverPtr &saver)
: m_saver(saver)
{
}
bool ItemSaverWrapper::saveItems(const QString &tabName, const QAbstractItemModel &model, QIODevice *file)
{
return m_saver->saveItems(tabName, model, file);
}
bool ItemSaverWrapper::canRemoveItems(const QList<QModelIndex> &indexList, QString *error)
{
return m_saver->canRemoveItems(indexList, error);
}
bool ItemSaverWrapper::canDropItem(const QModelIndex &index)
{
return m_saver->canDropItem(index);
}
bool ItemSaverWrapper::canMoveItems(const QList<QModelIndex> &indexList)
{
return m_saver->canMoveItems(indexList);
}
void ItemSaverWrapper::itemsRemovedByUser(const QList<QPersistentModelIndex> &indexList)
{
return m_saver->itemsRemovedByUser(indexList);
}
QVariantMap ItemSaverWrapper::copyItem(const QAbstractItemModel &model, const QVariantMap &itemData)
{
return m_saver->copyItem(model, itemData);
}
void ItemSaverWrapper::setFocus(bool focus)
{
return m_saver->setFocus(focus);
}
| 1,070
|
C++
|
.cpp
| 34
| 29.264706
| 106
| 0.801363
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,148
|
itemstore.cpp
|
hluk_CopyQ/src/item/itemstore.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "itemstore.h"
#include "common/config.h"
#include "common/log.h"
#include "common/textdata.h"
#include "item/itemfactory.h"
#include "item/serialize.h"
#include <QAbstractItemModel>
#include <QDir>
#include <QFile>
#include <QSaveFile>
#include <QSet>
namespace {
/// @return File name for data file with items.
QString itemFileName(const QString &id)
{
QString part( id.toUtf8().toBase64() );
part.replace( QChar('/'), QChar('-') );
return getConfigurationFilePath("_tab_") + part + QLatin1String(".dat");
}
void printItemFileError(
const QString &action, const QString &id, const QFileDevice &file)
{
log( QString("Tab %1: Failed to %2, file %3: %4").arg(
quoteString(id),
action,
quoteString(file.fileName()),
file.errorString()
), LogError );
}
ItemSaverPtr loadItems(
const QString &tabName, const QString &tabFileName,
QAbstractItemModel &model, ItemFactory *itemFactory, int maxItems)
{
COPYQ_LOG( QString("Tab \"%1\": Loading items from: %2").arg(tabName, tabFileName) );
QFile tabFile(tabFileName);
if ( !tabFile.open(QIODevice::ReadOnly) ) {
printItemFileError("load tab", tabName, tabFile);
return nullptr;
}
return itemFactory->loadItems(tabName, &model, &tabFile, maxItems);
}
ItemSaverPtr createTab(
const QString &tabName, QAbstractItemModel &model, ItemFactory *itemFactory, int maxItems)
{
COPYQ_LOG( QString("Tab \"%1\": Creating new tab").arg(tabName) );
auto saver = itemFactory->initializeTab(tabName, &model, maxItems);
if (!saver) {
log( QString("Tab \"%1\": Failed to create new tab"), LogError );
return nullptr;
}
if ( !saveItems(tabName, model, saver) )
return nullptr;
return saver;
}
bool itemDataFiles(const QString &tabName, QStringList *files)
{
const QString tabFileName = itemFileName(tabName);
if ( !QFile::exists(tabFileName) )
return true;
QFile tabFile(tabFileName);
if ( !tabFile.open(QIODevice::ReadOnly) ) {
printItemFileError("read tab", tabName, tabFile);
return false;
}
return itemDataFiles(&tabFile, files);
}
void cleanDataDir(QDir *dir)
{
if ( dir->isEmpty() )
QDir().rmdir( dir->absolutePath() );
}
} // namespace
ItemSaverPtr loadItems(const QString &tabName, QAbstractItemModel &model, ItemFactory *itemFactory, int maxItems)
{
const QString tabFileName = itemFileName(tabName);
if ( !QFile::exists(tabFileName) )
return createTab(tabName, model, itemFactory, maxItems);
ItemSaverPtr saver = loadItems(tabName, tabFileName, model, itemFactory, maxItems);
if (saver) {
COPYQ_LOG( QStringLiteral("Tab \"%1\": %2 items loaded from: %3")
.arg(tabName, QString::number(model.rowCount()), tabFileName) );
return saver;
}
log( QStringLiteral("Tab \"%1\": Failed to load tab file: %2")
.arg(tabName, tabFileName), LogError );
model.removeRows(0, model.rowCount());
return nullptr;
}
bool saveItems(const QString &tabName, const QAbstractItemModel &model, const ItemSaverPtr &saver)
{
const QString tabFileName = itemFileName(tabName);
if ( !ensureSettingsDirectoryExists() )
return false;
// Save tab data to a new temporary file.
QSaveFile tabFile(tabFileName);
tabFile.setDirectWriteFallback(false);
if ( !tabFile.open(QIODevice::WriteOnly) ) {
printItemFileError("save tab (open temporary file)", tabName, tabFile);
return false;
}
COPYQ_LOG( QStringLiteral("Tab \"%1\": Saving %2 items")
.arg(tabName, QString::number(model.rowCount())) );
if ( !saver->saveItems(tabName, model, &tabFile) ) {
tabFile.cancelWriting();
printItemFileError("save tab (save items to temporary file)", tabName, tabFile);
return false;
}
if ( !tabFile.flush() ) {
tabFile.cancelWriting();
printItemFileError("save tab (flush to temporary file)", tabName, tabFile);
return false;
}
if ( !tabFile.commit() ) {
printItemFileError("save tab (commit)", tabName, tabFile);
return false;
}
COPYQ_LOG( QStringLiteral("Tab \"%1\": Items saved").arg(tabName) );
return true;
}
void removeItems(const QString &tabName)
{
const QString tabFileName = itemFileName(tabName);
QFile::remove(tabFileName);
}
bool moveItems(const QString &oldId, const QString &newId)
{
const QString oldFileName = itemFileName(oldId);
const QString newFileName = itemFileName(newId);
if ( oldFileName != newFileName && QFile::copy(oldFileName, newFileName) ) {
QFile::remove(oldFileName);
return true;
}
log( QString("Failed to move items from \"%1\" (tab \"%2\") to \"%3\" (tab \"%4\")").arg(
oldFileName,
oldId,
newFileName,
newId
), LogError );
return false;
}
void cleanDataFiles(const QStringList &tabNames)
{
QDir dir(itemDataPath());
if ( !dir.exists() )
return;
QStringList files;
for (const QString &tabName : tabNames) {
if ( !itemDataFiles(tabName, &files) ) {
COPYQ_LOG( QStringLiteral("Stopping cleanup due to corrupted file: %1")
.arg(tabName) );
return;
}
}
#if QT_VERSION >= QT_VERSION_CHECK(5,14,0)
const QSet<QString> fileSet(files.constBegin(), files.constEnd());
#else
const QSet<QString> fileSet = files.toSet();
#endif
for ( const auto &i1 : dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot) ) {
QDir d1(i1.absoluteFilePath());
for ( const auto &i2 : d1.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot) ) {
QDir d2(i2.absoluteFilePath());
for ( const auto &i3 : d2.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot) ) {
QDir d3(i3.absoluteFilePath());
for ( const auto &f : d3.entryInfoList(QDir::Files) ) {
const QString path = f.absoluteFilePath();
if ( !fileSet.contains(path) ) {
COPYQ_LOG( QStringLiteral("Cleaning: %1").arg(path) );
QFile::remove(path);
}
}
cleanDataDir(&d3);
}
cleanDataDir(&d2);
}
cleanDataDir(&d1);
}
}
| 6,510
|
C++
|
.cpp
| 179
| 29.703911
| 113
| 0.637057
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,149
|
log.cpp
|
hluk_CopyQ/src/common/log.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "log.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QLockFile>
#include <QFile>
#include <QString>
#include <QtGlobal>
#include <QVariant>
#include <QStandardPaths>
namespace {
QString &logFileNameVariable() {
static QString logFileName;
return logFileName;
}
/// System-wide mutex
class SystemMutex final {
public:
SystemMutex()
: m_lockFile(logFileName() + QLatin1String(".lock"))
{
}
/// Lock mutex (blocking).
bool lock()
{
++m_selfLocked;
return m_selfLocked > 1 || m_lockFile.lock();
}
/// Unlock mutex.
void unlock()
{
--m_selfLocked;
if (m_selfLocked == 0)
m_lockFile.unlock();
}
QString error() const
{
if (m_lockFile.error() == QLockFile::NoError)
return {};
if (m_lockFile.error() == QLockFile::PermissionError)
return QStringLiteral("Insufficient permissions to create lock file");
return QStringLiteral("Unknown error");
}
private:
int m_selfLocked = 0;
QLockFile m_lockFile;
};
const int logFileSize = 512 * 1024;
const int logFileCount = 10;
int getLogLevel()
{
const QByteArray logLevelString = qgetenv("COPYQ_LOG_LEVEL").toUpper();
if ( logLevelString.startsWith("TRAC") )
return LogTrace;
if ( logLevelString.startsWith("DEBUG") )
return LogDebug;
if ( logLevelString.startsWith("NOT") )
return LogNote;
if ( logLevelString.startsWith("WARN") )
return LogWarning;
if ( logLevelString.startsWith("ERR") )
return LogError;
#ifdef COPYQ_DEBUG
return LogDebug;
#else
return LogNote;
#endif
}
QString envString(const char *varName)
{
const QByteArray bytes = qgetenv(varName);
return QString::fromUtf8( bytes.constData(), bytes.size() );
}
QString logFileName(int i)
{
if (i <= 0)
return ::logFileName();
return ::logFileName() + QLatin1String(".") + QString::number(i);
}
void rotateLogFiles()
{
for (int i = logFileCount - 1; i > 0; --i) {
const QString sourceFileName = logFileName(i - 1);
const QString targetFileName = logFileName(i);
QFile::remove(targetFileName);
QFile::rename(sourceFileName, targetFileName);
}
}
bool writeLogFileNoLock(const QByteArray &message)
{
QFile f( ::logFileName() );
if ( !f.open(QIODevice::Append) )
return false;
if ( f.write(message) <= 0 )
return false;
f.close();
if ( f.size() > logFileSize )
rotateLogFiles();
return true;
}
/// Lock guard for SystemMutex.
class SystemMutexLocker final {
public:
/// Locks mutex (it's possible that the mutex won't be locked because of errors).
explicit SystemMutexLocker(SystemMutex &mutex)
: m_mutex(mutex)
, m_locked( m_mutex.lock() )
{
if (!m_locked) {
writeLogFileNoLock(
"Failed to lock logs: " + m_mutex.error().toUtf8());
}
}
/// Unlocks mutex.
~SystemMutexLocker()
{
if (m_locked)
m_mutex.unlock();
}
SystemMutexLocker(const SystemMutexLocker &) = delete;
SystemMutexLocker &operator=(const SystemMutexLocker &) = delete;
private:
SystemMutex &m_mutex;
bool m_locked;
};
SystemMutex &getSessionMutex()
{
static SystemMutex mutex;
return mutex;
}
QString getDefaultLogFilePath()
{
return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
}
QByteArray readLogFile(const QString &fileName, int maxReadSize)
{
QFile f(fileName);
if ( !f.open(QIODevice::ReadOnly) )
return {};
const auto seek = f.size() - maxReadSize;
if (seek > 0)
f.seek(seek);
return f.readAll();
}
bool writeLogFile(const QByteArray &message)
{
SystemMutexLocker lock(getSessionMutex());
return writeLogFileNoLock(message);
}
QByteArray createLogMessage(const QByteArray &label, const QByteArray &text)
{
if ( text.contains('\n') ) {
const QByteArray continuation = '\n' + label + " ";
return label + QByteArray(text).replace('\n', continuation) + '\n';
}
return label + text + '\n';
}
QByteArray createSimpleLogMessage(const QByteArray &text, const LogLevel level)
{
const auto label = logLevelLabel(level) + ": ";
return createLogMessage(label, text);
}
QByteArray createLogMessage(const QByteArray &text, const LogLevel level)
{
const auto timeStamp =
QDateTime::currentDateTime().toString(QStringLiteral(" [yyyy-MM-dd hh:mm:ss.zzz] ")).toLatin1();
const auto label = "CopyQ " + logLevelLabel(level) + timeStamp + logLabel() + ": ";
return createLogMessage(label, text);
}
QString getLogFileName()
{
const QString fileName = envString("COPYQ_LOG_FILE");
if (!fileName.isEmpty())
return QDir::fromNativeSeparators(fileName);
const QString path = getDefaultLogFilePath();
QDir dir(path);
dir.mkpath(QStringLiteral("."));
return path + QStringLiteral("/copyq.log");
}
void logAlways(const QByteArray &msgText, const LogLevel level)
{
const auto msg = createLogMessage(msgText, level);
const bool writtenToLogFile = writeLogFile(msg);
// Log to file and if needed to stderr.
if ( (!writtenToLogFile || level <= LogWarning || hasLogLevel(LogDebug))
&& canUseStandardOutput() )
{
QFile ferr;
ferr.open(stderr, QIODevice::WriteOnly);
const auto simpleMsg = createSimpleLogMessage(msgText, level);
ferr.write(simpleMsg);
}
}
} // namespace
void initLogging()
{
logFileNameVariable() = getLogFileName();
}
const QString &logFileName()
{
if ( logFileNameVariable().isEmpty() )
logFileNameVariable() = getLogFileName();
return logFileNameVariable();
}
QByteArray readLogFile(int maxReadSize)
{
SystemMutexLocker lock(getSessionMutex());
QByteArray content;
for (int i = 0; i < logFileCount; ++i) {
const int toRead = maxReadSize - content.size();
content.prepend( readLogFile(logFileName(i), toRead) );
if ( maxReadSize <= content.size() )
break;
}
return content;
}
bool removeLogFiles()
{
SystemMutexLocker lock(getSessionMutex());
for (int i = 0; i < logFileCount; ++i) {
QFile logFile( logFileName(i) );
if ( logFile.exists() && !logFile.remove() )
return false;
}
return true;
}
bool hasLogLevel(LogLevel level)
{
static const int currentLogLevel = getLogLevel();
return currentLogLevel >= level;
}
QByteArray logLevelLabel(LogLevel level)
{
switch(level) {
case LogWarning:
return QByteArrayLiteral("Warning");
case LogError:
return QByteArrayLiteral("ERROR");
case LogDebug:
return QByteArrayLiteral("DEBUG");
case LogTrace:
return QByteArrayLiteral("TRACE");
case LogNote:
case LogAlways:
return QByteArrayLiteral("Note");
}
Q_ASSERT(false);
return "";
}
void log(const char *text, LogLevel level)
{
if ( hasLogLevel(level) )
logAlways(QByteArray(text), level);
}
void log(const QByteArray &text, LogLevel level)
{
if ( hasLogLevel(level) )
logAlways(text, level);
}
void log(const QString &text, const LogLevel level)
{
if ( hasLogLevel(level) )
logAlways(text.toUtf8(), level);
}
void setLogLabel(const QByteArray &name)
{
const auto id = QCoreApplication::applicationPid();
logLabel() = "<" + name + "-" + QByteArray::number(id) + ">";
}
QByteArray &logLabel()
{
static QByteArray label;
return label;
}
bool canUseStandardOutput()
{
static const bool useOutput = qEnvironmentVariableIsEmpty("COPYQ_NO_OUTPUT");
return useOutput;
}
| 7,828
|
C++
|
.cpp
| 280
| 23.3
| 104
| 0.669071
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,150
|
temporaryfile.cpp
|
hluk_CopyQ/src/common/temporaryfile.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "temporaryfile.h"
#include "common/log.h"
#include <QDir>
#include <QTemporaryFile>
bool openTemporaryFile(QTemporaryFile *file, const QString &suffix)
{
const QString tmpFileName = "CopyQ.XXXXXX" + suffix;
const QString tmpPath = QDir( QDir::tempPath() ).absoluteFilePath(tmpFileName);
file->setFileTemplate(tmpPath);
if ( !file->open() ) {
log( QString("Failed to open temporary file \"%1\" (template \"%2\")")
.arg(file->fileName(), tmpPath),
LogError );
return false;
}
if ( !file->setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner) ) {
log( QString("Failed set permissions to temporary file \"%1\"")
.arg(file->fileName()), LogError );
return false;
}
return true;
}
| 856
|
C++
|
.cpp
| 23
| 31.434783
| 90
| 0.64891
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,151
|
command.cpp
|
hluk_CopyQ/src/common/command.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "command.h"
#include <QDataStream>
bool Command::operator==(const Command &other) const
{
return name == other.name
&& re == other.re
&& wndre == other.wndre
&& matchCmd == other.matchCmd
&& cmd == other.cmd
&& sep == other.sep
&& input == other.input
&& output == other.output
&& wait == other.wait
&& automatic == other.automatic
&& display == other.display
&& inMenu == other.inMenu
&& isGlobalShortcut == other.isGlobalShortcut
&& isScript == other.isScript
&& transform == other.transform
&& remove == other.remove
&& hideWindow == other.hideWindow
&& enable == other.enable
&& icon == other.icon
&& shortcuts == other.shortcuts
&& globalShortcuts == other.globalShortcuts
&& tab == other.tab
&& outputTab == other.outputTab
&& internalId == other.internalId;
}
bool Command::operator!=(const Command &other) const {
return !(*this == other);
}
int Command::type() const
{
auto type =
(automatic ? CommandType::Automatic : 0)
| (display ? CommandType::Display : 0)
| (isGlobalShortcut ? CommandType::GlobalShortcut : 0)
| (inMenu && !name.isEmpty() ? CommandType::Menu : 0);
// Scripts cannot be used in other types of commands.
if (isScript)
type = CommandType::Script;
if (type == CommandType::None)
type = CommandType::Invalid;
if (!enable)
type |= CommandType::Disabled;
return type;
}
QDataStream &operator<<(QDataStream &out, const Command &command)
{
out << command.name
<< command.re
<< command.wndre
<< command.matchCmd
<< command.cmd
<< command.sep
<< command.input
<< command.output
<< command.wait
<< command.automatic
<< command.display
<< command.inMenu
<< command.isGlobalShortcut
<< command.isScript
<< command.transform
<< command.remove
<< command.hideWindow
<< command.enable
<< command.icon
<< command.shortcuts
<< command.globalShortcuts
<< command.tab
<< command.outputTab
<< command.internalId;
Q_ASSERT(out.status() == QDataStream::Ok);
return out;
}
QDataStream &operator>>(QDataStream &in, Command &command)
{
in >> command.name
>> command.re
>> command.wndre
>> command.matchCmd
>> command.cmd
>> command.sep
>> command.input
>> command.output
>> command.wait
>> command.automatic
>> command.display
>> command.inMenu
>> command.isGlobalShortcut
>> command.isScript
>> command.transform
>> command.remove
>> command.hideWindow
>> command.enable
>> command.icon
>> command.shortcuts
>> command.globalShortcuts
>> command.tab
>> command.outputTab
>> command.internalId;
Q_ASSERT(in.status() == QDataStream::Ok);
return in;
}
| 3,167
|
C++
|
.cpp
| 107
| 22.448598
| 65
| 0.58511
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,152
|
textdata.cpp
|
hluk_CopyQ/src/common/textdata.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "textdata.h"
#include "common/mimetypes.h"
#include <QLocale>
#include <QString>
#include <algorithm>
#include <iterator>
namespace {
const QLatin1String mimePluginPrefix(COPYQ_MIME_PREFIX "item");
QString escapeHtmlSpaces(const QString &str)
{
return QString(str)
.replace(' ', QLatin1String(" "))
.replace('\n', QLatin1String("<br />"));
}
bool isPluginFormat(const QString &mime)
{
return mime.startsWith(mimePrivatePrefix) || (
mime.startsWith(mimePluginPrefix)
&& mime.size() > mimePluginPrefix.size()
&& mime[mimePluginPrefix.size()] != '-'
);
}
} // namespace
uint hash(const QVariantMap &data)
{
uint seed = 0;
QtPrivate::QHashCombine hash;
for (auto it = data.constBegin(); it != data.constEnd(); ++it) {
const auto &mime = it.key();
// Skip some special data.
if (mime == mimeWindowTitle || mime == mimeOwner || mime == mimeClipboardMode)
continue;
if ( isPluginFormat(mime) )
continue;
seed = hash(seed, mime);
const auto &value = it.value();
if ( value.type() == QVariant::ByteArray )
seed = hash(seed, value.toByteArray());
else
seed = hash(seed, value.toString());
}
return seed;
}
QString quoteString(const QString &str)
{
return QLocale().quoteString(str);
}
QString escapeHtml(const QString &str)
{
return escapeHtmlSpaces(str.toHtmlEscaped());
}
QString getTextData(const QByteArray &bytes)
{
// QString::fromUtf8(bytes) ends string at first '\0'.
return QString::fromUtf8( bytes.constData(), bytes.size() );
}
QString getTextData(const QVariantMap &data, const QString &mime)
{
const auto it = data.find(mime);
if ( it != data.constEnd() )
return getTextData( it->toByteArray() );
return QString();
}
QString getTextData(const QVariantMap &data)
{
for (const auto &mime : {mimeTextUtf8, mimeText, mimeUriList}) {
const auto it = data.find(mime);
if ( it != data.constEnd() )
return getTextData( it->toByteArray() );
}
return QString();
}
void setTextData(QVariantMap *data, const QString &text, const QString &mime)
{
data->insert(mime, text.toUtf8());
}
void setTextData(QVariantMap *data, const QString &text)
{
setTextData(data, text, mimeText);
data->remove(mimeTextUtf8);
}
QVariantMap createDataMap(const QString &format, const QVariant &value)
{
QVariantMap dataMap;
dataMap.insert(format, value);
return dataMap;
}
QVariantMap createDataMap(const QString &format, const QByteArray &value)
{
return createDataMap( format, QVariant(value) );
}
QVariantMap createDataMap(const QString &format, const QString &value)
{
return createDataMap( format, value.toUtf8() );
}
QString accentsRemoved(const QString &text)
{
if (text.isEmpty())
return {};
QString result = text.normalized(QString::NormalizationForm_D);
const auto newEnd = std::remove_if(
std::begin(result), std::end(result),
[](QChar c){ return c.category() == QChar::Mark_NonSpacing; });
const auto newSize = std::distance(std::begin(result), newEnd);
result.resize(newSize);
return result;
}
| 3,313
|
C++
|
.cpp
| 108
| 26.175926
| 86
| 0.673701
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,153
|
config.cpp
|
hluk_CopyQ/src/common/config.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "config.h"
#include "log.h"
#include "gui/screen.h"
#include <QApplication>
#include <QByteArray>
#include <QDir>
#include <QScreen>
#include <QSettings>
#include <QString>
#include <QVariant>
#include <QWidget>
#include <QWindow>
#define GEOMETRY_LOG(window, message) \
COPYQ_LOG( QStringLiteral("Geometry: Window \"%1\": %2").arg(window->objectName(), message) )
namespace {
const char propertyGeometryLockedUntilHide[] = "CopyQ_geometry_locked_until_hide";
constexpr int windowMinWidth = 50;
constexpr int windowMinHeight = 50;
QSize frameSize(QWidget *widget) {
const QRect frame = widget->frameGeometry();
const QSize size = widget->size();
const int w = qMax(windowMinWidth, qMax(frame.width(), size.width()));
const int h = qMax(windowMinHeight, qMax(frame.height(), size.height()));
return QSize(w, h);
}
QString toString(const QRect &geometry)
{
return QStringLiteral("%1x%2,%3,%4")
.arg(geometry.width())
.arg(geometry.height())
.arg(geometry.x())
.arg(geometry.y());
}
int screenNumber(const QWidget &widget)
{
QWindow *windowHandle = widget.windowHandle();
if (windowHandle) {
QScreen *screen = windowHandle->screen();
if (screen)
return QGuiApplication::screens().indexOf(screen);
}
return -1;
}
QString geometryOptionName(const QWidget &widget)
{
return QStringLiteral("Options/%1_geometry").arg(widget.objectName());
}
QString geometryOptionName(const QWidget &widget, bool openOnCurrentScreen)
{
const QString baseGeometryName = geometryOptionName(widget);
if (!openOnCurrentScreen)
return QStringLiteral("%1_global").arg(baseGeometryName);
const int n = screenNumber(widget);
if (n > 0)
return QStringLiteral("%1_screen_%2").arg(baseGeometryName).arg(n);
return baseGeometryName;
}
QString getGeometryConfigurationFilePath()
{
return getConfigurationFilePath("_geometry.ini");
}
QString resolutionTagForScreen(int i)
{
const QRect screenGeometry = ::screenGeometry(i);
return QStringLiteral("_%1x%2")
.arg(screenGeometry.width())
.arg(screenGeometry.height());
}
QString resolutionTag(const QWidget &widget, bool openOnCurrentScreen)
{
if (openOnCurrentScreen) {
const int i = screenNumber(widget);
if (i == -1)
return QString();
return resolutionTagForScreen(i);
}
QString tag;
for ( int i = 0; i < screenCount(); ++i )
tag.append( resolutionTagForScreen(i) );
return tag;
}
void ensureWindowOnScreen(QWidget *widget)
{
const QSize frame = frameSize(widget);
int x = widget->x();
int y = widget->y();
int w = qMax(windowMinWidth, frame.width());
int h = qMax(windowMinHeight, frame.height());
const QRect availableGeometry = screenAvailableGeometry(*widget);
if ( availableGeometry.isValid() ) {
// Ensure that the window fits the screen, otherwise it would be moved
// to a neighboring screen automatically.
w = qMin(w, availableGeometry.width());
h = qMin(h, availableGeometry.height());
if ( x + w > availableGeometry.right() )
x = availableGeometry.right() - w;
if ( x < availableGeometry.left() )
x = availableGeometry.left();
if ( y + h > availableGeometry.bottom() )
y = availableGeometry.bottom() - h;
if ( y < availableGeometry.top())
y = availableGeometry.top();
}
if ( frame != QSize(w, h) ) {
GEOMETRY_LOG(
widget, QStringLiteral("Resize window: %1x%2 -> %3x%4")
.arg(frame.width())
.arg(frame.height())
.arg(w)
.arg(h) );
widget->resize(w, h);
}
if ( widget->pos() != QPoint(x, y) ) {
GEOMETRY_LOG( widget, QStringLiteral("Move window: %1, %2").arg(x).arg(y) );
widget->move(x, y);
}
}
QString getConfigurationFilePathHelper()
{
const QSettings settings(
QSettings::IniFormat, QSettings::UserScope,
QCoreApplication::organizationName(),
QCoreApplication::applicationName() );
return settings.fileName();
}
} // namespace
bool ensureSettingsDirectoryExists()
{
QDir settingsDir( settingsDirectoryPath() );
if ( !settingsDir.mkpath(QStringLiteral(".")) ) {
log( QStringLiteral("Failed to create the directory for settings: %1")
.arg(settingsDir.path()),
LogError );
return false;
}
return true;
}
const QString &getConfigurationFilePath()
{
static const QString path = getConfigurationFilePathHelper();
return path;
}
QString getConfigurationFilePath(const char *suffix)
{
QString path = getConfigurationFilePath();
// Replace suffix.
const int i = path.lastIndexOf(QLatin1Char('.'));
Q_ASSERT(i != -1);
Q_ASSERT( path.endsWith(QLatin1String(".ini")) );
return path.left(i) + QLatin1String(suffix);
}
const QString &settingsDirectoryPath()
{
static const QString path =
QDir::cleanPath( getConfigurationFilePath() + QLatin1String("/..") );
return path;
}
QVariant geometryOptionValue(const QString &optionName)
{
const QSettings geometrySettings( getGeometryConfigurationFilePath(), QSettings::IniFormat );
return geometrySettings.value(optionName);
}
void setGeometryOptionValue(const QString &optionName, const QVariant &value)
{
QSettings geometrySettings( getGeometryConfigurationFilePath(), QSettings::IniFormat );
geometrySettings.setValue(optionName, value);
}
void restoreWindowGeometry(QWidget *w, bool openOnCurrentScreen)
{
const QString optionName = geometryOptionName(*w, openOnCurrentScreen);
const QString tag = resolutionTag(*w, openOnCurrentScreen);
QByteArray geometry = geometryOptionValue(optionName + tag).toByteArray();
// If geometry for screen resolution doesn't exist, use last saved one.
const bool restoreUntaggedGeometry = geometry.isEmpty();
if (restoreUntaggedGeometry) {
geometry = geometryOptionValue(optionName).toByteArray();
// If geometry for the screen doesn't exist, move window to the middle of the screen.
if (geometry.isEmpty()) {
const QRect availableGeometry = screenAvailableGeometry(*w);
if ( availableGeometry.isValid() ) {
const QPoint position = availableGeometry.center() - w->rect().center();
w->move(position);
}
}
}
const QRect oldGeometry = w->geometry();
if ( !geometry.isEmpty() )
w->restoreGeometry(geometry);
ensureWindowOnScreen(w);
const QRect newGeometry = w->geometry();
GEOMETRY_LOG( w,
QStringLiteral("%5 geometry \"%1%2\": %3 -> %4").arg(
optionName,
restoreUntaggedGeometry ? QString() : tag,
toString(oldGeometry),
toString(newGeometry),
geometry.isEmpty() ? QLatin1String("New") : QLatin1String("Restore")) );
}
void saveWindowGeometry(QWidget *w, bool openOnCurrentScreen)
{
const QString optionName = geometryOptionName(*w, openOnCurrentScreen);
const QString tag = resolutionTag(*w, openOnCurrentScreen);
QSettings geometrySettings( getGeometryConfigurationFilePath(), QSettings::IniFormat );
const auto geometry = w->saveGeometry();
geometrySettings.setValue(optionName + tag, geometry);
geometrySettings.setValue(optionName, geometry);
geometrySettings.setValue(geometryOptionName(*w), geometry);
GEOMETRY_LOG( w, QStringLiteral("Save geometry \"%1%2\": %3")
.arg(optionName, tag, toString(w->geometry())) );
}
QByteArray mainWindowState(const QString &mainWindowObjectName)
{
const QString optionName = QStringLiteral("Options/%1_state").arg(mainWindowObjectName);
return geometryOptionValue(optionName).toByteArray();
}
void saveMainWindowState(const QString &mainWindowObjectName, const QByteArray &state)
{
const QString optionName = QStringLiteral("Options/%1_state").arg(mainWindowObjectName);
setGeometryOptionValue(optionName, state);
}
void moveToCurrentWorkspace(QWidget *w)
{
#ifdef COPYQ_MOVE_TO_WORKSPACE
/* Re-initialize window in window manager so it can popup on current workspace. */
if (w->isVisible()) {
GEOMETRY_LOG( w, QLatin1String("Move to current workspace") );
const bool blockUntilHide = isGeometryGuardBlockedUntilHidden(w);
w->hide();
if (blockUntilHide)
setGeometryGuardBlockedUntilHidden(w, true);
}
#else
Q_UNUSED(w)
#endif
}
void moveWindowOnScreen(QWidget *w, QPoint pos)
{
w->move(pos);
ensureWindowOnScreen(w);
moveToCurrentWorkspace(w);
}
void setGeometryGuardBlockedUntilHidden(QWidget *w, bool blocked)
{
GEOMETRY_LOG( w, QStringLiteral("Geometry blocked until hidden: %1").arg(blocked) );
w->setProperty(propertyGeometryLockedUntilHide, blocked);
}
bool isGeometryGuardBlockedUntilHidden(const QWidget *w)
{
return w->property(propertyGeometryLockedUntilHide).toBool();
}
| 9,183
|
C++
|
.cpp
| 251
| 31.139442
| 97
| 0.689302
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,154
|
tabs.cpp
|
hluk_CopyQ/src/common/tabs.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "tabs.h"
#include <QRegularExpression>
#include <QSettings>
constexpr auto settingsGroupTabs = "Tabs";
constexpr auto optionTabName = "name";
constexpr auto optionIconName = "icon";
constexpr auto optionMaxItemCount = "max_item_count";
constexpr auto optionStoreItems = "store_items";
struct Tabs::PrivateData {
QHash<QString, TabProperties> tabs;
};
Tabs::Tabs()
: m_data(new PrivateData())
{
QSettings settings;
const int size = settings.beginReadArray(settingsGroupTabs);
for(int i = 0; i < size; ++i) {
settings.setArrayIndex(i);
TabProperties properties;
properties.name = settings.value(optionTabName).toString();
properties.iconName = settings.value(optionIconName).toString();
properties.storeItems = settings.value(optionStoreItems, true).toBool();
bool ok;
const int maxItemCount = settings.value(optionMaxItemCount).toInt(&ok);
if (ok)
properties.maxItemCount = maxItemCount;
setTabProperties(properties);
}
}
Tabs::~Tabs() = default;
Tabs::Tabs(const Tabs &other)
: m_data(new PrivateData())
{
m_data->tabs = other.m_data->tabs;
}
Tabs &Tabs::operator=(const Tabs &other)
{
m_data->tabs = other.m_data->tabs;
return *this;
}
void Tabs::setTabProperties(const TabProperties &tabProperties)
{
if ( tabProperties.name.isEmpty() )
return;
m_data->tabs[tabProperties.name] = tabProperties;
}
void Tabs::save(QSettings *settings, const QStringList &tabs)
{
settings->beginWriteArray(settingsGroupTabs, m_data->tabs.size());
int row = 0;
for (auto it = m_data->tabs.constBegin(); it != m_data->tabs.constEnd(); ++it) {
const auto &name = it.key();
const auto &tab = it.value();
const bool isTab = tabs.contains(name);
const bool isTabGroup =
!isTab && tabs.indexOf(QRegularExpression(QString::fromLatin1("^%1/.*").arg(QRegularExpression::escape(name)))) != -1;
if (isTab || isTabGroup) {
settings->setArrayIndex(row++);
settings->setValue(optionTabName, name);
settings->setValue(optionIconName, tab.iconName);
if (isTab) {
settings->setValue(optionMaxItemCount, tab.maxItemCount);
settings->setValue(optionStoreItems, tab.storeItems);
}
}
}
settings->endArray();
}
TabProperties Tabs::tabProperties(const QString &name) const
{
TabProperties tab = m_data->tabs.value(name);
tab.name = name;
return tab;
}
| 2,608
|
C++
|
.cpp
| 75
| 29.2
| 130
| 0.67144
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,155
|
temporarysettings.cpp
|
hluk_CopyQ/src/common/temporarysettings.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "temporarysettings.h"
#include "common/log.h"
#include "common/temporaryfile.h"
#include <QTemporaryFile>
namespace {
QString temporaryFileName(const QByteArray &content)
{
QTemporaryFile tmpfile;
if ( !openTemporaryFile(&tmpfile, ".ini") )
{
log("Failed to create temporary settings file", LogError);
return QString();
}
tmpfile.write(content);
tmpfile.setAutoRemove(false);
return tmpfile.fileName();
}
} // namespace
TemporarySettings::TemporarySettings(const QByteArray &content)
: m_settings(new QSettings(temporaryFileName(content), QSettings::IniFormat))
{
}
TemporarySettings::~TemporarySettings()
{
const QString fileName = m_settings->fileName();
delete m_settings;
m_settings = nullptr;
if (!fileName.isEmpty())
QFile::remove(fileName);
}
QSettings *TemporarySettings::settings()
{
return m_settings;
}
QByteArray TemporarySettings::content()
{
m_settings->sync();
QFile file(m_settings->fileName());
if (!file.open(QIODevice::ReadOnly)) {
log("Failed to open temporary settings file", LogError);
return QByteArray();
}
return file.readAll();
}
| 1,236
|
C++
|
.cpp
| 45
| 23.666667
| 81
| 0.717077
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,156
|
appconfig.cpp
|
hluk_CopyQ/src/common/appconfig.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "appconfig.h"
#include "platform/platformnativeinterface.h"
#include <QObject>
#include <QString>
Config::Config<QString>::Value Config::editor::defaultValue()
{
return platformNativeInterface()->defaultEditorCommand();
}
Config::Config<bool>::Value Config::autostart::defaultValue()
{
return platformNativeInterface()->isAutostartEnabled();
}
QString defaultClipboardTabName()
{
return QObject::tr(
"&clipboard", "Default name of the tab that automatically stores new clipboard content");
}
QVariant AppConfig::option(const QString &name) const
{
return m_settings.value(QStringLiteral("Options/") + name);
}
void AppConfig::setOption(const QString &name, const QVariant &value)
{
if ( option(name) != value )
m_settings.setValue(QStringLiteral("Options/") + name, value);
}
void AppConfig::removeOption(const QString &name)
{
m_settings.remove(QStringLiteral("Options/") + name);
}
| 995
|
C++
|
.cpp
| 31
| 29.258065
| 105
| 0.747644
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,157
|
common.cpp
|
hluk_CopyQ/src/common/common.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "common/common.h"
#include "common/display.h"
#include "common/log.h"
#include "common/mimetypes.h"
#include "common/textdata.h"
#include <QApplication>
#include <QBuffer>
#include <QDropEvent>
#include <QElapsedTimer>
#include <QFont>
#include <QFontMetrics>
#include <QImage>
#include <QImageWriter>
#include <QKeyEvent>
#include <QMimeData>
#include <QMovie>
#include <QObject>
#include <QProcess>
#include <QRegularExpression>
#include <QThread>
#include <QUrl>
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
# include <QTextCodec>
using Encoding = QTextCodec*;
#else
# include <QStringDecoder>
using Encoding = std::optional<QStringConverter::Encoding>;
#endif
#include <algorithm>
#include <memory>
namespace {
const int maxElidedTextLineLength = 512;
int clipboardCopyTimeoutMs()
{
static bool ok = false;
static int ms = qgetenv("COPYQ_CLIPBOARD_COPY_TIMEOUT_MS").toInt(&ok);
return ok ? ms : 5000;
}
const QMimeData *dummyMimeData()
{
static QMimeData mimeData;
return &mimeData;
}
class MimeData final : public QMimeData {
protected:
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
QVariant retrieveData(const QString &mimeType, QMetaType preferredType) const override
#else
QVariant retrieveData(const QString &mimeType, QVariant::Type preferredType) const override
#endif
{
COPYQ_LOG_VERBOSE( QStringLiteral("Providing \"%1\"").arg(mimeType) );
return QMimeData::retrieveData(mimeType, preferredType);
}
};
// Avoids accessing old clipboard/drag'n'drop data.
class ClipboardDataGuard final {
public:
class ElapsedGuard {
public:
explicit ElapsedGuard(const QString &type, const QString &format)
: m_type(type)
, m_format(format)
{
COPYQ_LOG_VERBOSE( QStringLiteral("Accessing [%1:%2]").arg(type, format) );
m_elapsed.start();
}
~ElapsedGuard()
{
const auto t = m_elapsed.elapsed();
if (t > 500)
log( QStringLiteral("ELAPSED %1 ms accessing [%2:%3]").arg(t).arg(m_type, m_format), LogWarning );
}
private:
QString m_type;
QString m_format;
QElapsedTimer m_elapsed;
};
explicit ClipboardDataGuard(const QMimeData &data, const long int *clipboardSequenceNumber = nullptr)
: m_data(&data)
, m_clipboardSequenceNumber(clipboardSequenceNumber)
, m_clipboardSequenceNumberOriginal(clipboardSequenceNumber ? *clipboardSequenceNumber : 0)
{
// This uses simple connection to ensure pointer is not destroyed
// instead of QPointer to work around a possible Qt bug
// (https://bugzilla.redhat.com/show_bug.cgi?id=2320093).
m_connection = QObject::connect(m_data, &QObject::destroyed, [this](){
m_data = nullptr;
log( QByteArrayLiteral("Aborting clipboard cloning: Data deleted"), LogWarning );
});
m_timerExpire.start();
}
~ClipboardDataGuard()
{
QObject::disconnect(m_connection);
}
QStringList formats()
{
ElapsedGuard _(QStringLiteral(), QStringLiteral("formats"));
return mimeData()->formats();
}
bool hasFormat(const QString &mime)
{
ElapsedGuard _(QStringLiteral("hasFormat"), mime);
return mimeData()->hasFormat(mime);
}
QByteArray data(const QString &mime)
{
ElapsedGuard _(QStringLiteral("data"), mime);
return mimeData()->data(mime);
}
QList<QUrl> urls()
{
ElapsedGuard _(QStringLiteral(), QStringLiteral("urls"));
return mimeData()->urls();
}
QString text()
{
ElapsedGuard _(QStringLiteral(), QStringLiteral("text"));
return mimeData()->text();
}
bool hasText()
{
ElapsedGuard _(QStringLiteral(), QStringLiteral("hasText"));
return mimeData()->hasText();
}
QImage getImageData()
{
ElapsedGuard _(QStringLiteral(), QStringLiteral("imageData"));
// NOTE: Application hangs if using multiple sessions and
// calling QMimeData::hasImage() on X11 clipboard.
QImage image = mimeData()->imageData().value<QImage>();
if ( image.isNull() ) {
image.loadFromData( data(QStringLiteral("image/png")), "png" );
if ( image.isNull() ) {
image.loadFromData( data(QStringLiteral("image/bmp")), "bmp" );
}
}
COPYQ_LOG_VERBOSE(
QStringLiteral("Image is %1")
.arg(image.isNull() ? QStringLiteral("invalid") : QStringLiteral("valid")) );
return image;
}
QByteArray getUtf8Data(const QString &format)
{
ElapsedGuard _(QStringLiteral("UTF8"), format);
if (format == mimeUriList) {
QByteArray bytes;
for ( const auto &url : urls() ) {
if ( !bytes.isEmpty() )
bytes += '\n';
bytes += url.toString().toUtf8();
}
return bytes;
}
if ( format == mimeText && !hasFormat(mimeText) )
return text().toUtf8();
if ( format.startsWith(QLatin1String("text/")) )
return dataToText( data(format), format ).toUtf8();
return data(format);
}
bool isExpired() {
if (!m_data)
return true;
if (m_clipboardSequenceNumber && *m_clipboardSequenceNumber != m_clipboardSequenceNumberOriginal) {
m_data = nullptr;
log( QByteArrayLiteral("Aborting clipboard cloning: Clipboard changed again"), LogWarning );
return true;
}
if (m_timerExpire.elapsed() > clipboardCopyTimeoutMs()) {
m_data = nullptr;
log( QByteArrayLiteral("Aborting clipboard cloning: Data access took too long"), LogWarning );
return true;
}
return false;
}
private:
const QMimeData *mimeData()
{
if (isExpired())
return dummyMimeData();
if (m_timerExpire.elapsed() > 100) {
QCoreApplication::processEvents();
if (isExpired())
return dummyMimeData();
}
return m_data;
}
const QMimeData *m_data;
QElapsedTimer m_timerExpire;
const long int *m_clipboardSequenceNumber;
long int m_clipboardSequenceNumberOriginal;
QMetaObject::Connection m_connection;
};
QString getImageFormatFromMime(const QString &mime)
{
static const QString imageMimePrefix = QStringLiteral("image/");
return mime.startsWith(imageMimePrefix) ? mime.mid(imageMimePrefix.length()) : QString();
}
/**
* Sometimes only Qt internal image data are available in clipboard,
* so this tries to convert the image data (if available) to given format.
*/
void cloneImageData(
const QImage &image, const QString &format,
const QString &mime, QVariantMap *dataMap)
{
if (image.isNull())
return;
// Omit converting unsupported formats (takes too much time and still fails).
if ( !QImageWriter::supportedImageFormats().contains(format.toUtf8()) )
return;
QBuffer buffer;
bool saved = image.save(&buffer, format.toUtf8().constData());
COPYQ_LOG( QStringLiteral("Converting image to \"%1\" format: %2")
.arg(format,
saved ? QStringLiteral("Done") : QStringLiteral("Failed")) );
if (saved)
dataMap->insert(mime, buffer.buffer());
}
/**
* Allow cloning images only with reasonable size.
*/
bool canCloneImageData(const QImage &image)
{
return !image.isNull()
&& image.height() <= 4096
&& image.width() <= 4096;
}
bool setImageData(
QByteArray &bytes, const char *imageFormat, const std::unique_ptr<QMimeData> &mimeData)
{
// Omit converting animated images to static ones.
QBuffer buffer(&bytes);
const QMovie animatedImage(&buffer, imageFormat);
if ( animatedImage.frameCount() > 1 )
return false;
const QImage image = QImage::fromData(bytes, imageFormat);
if ( image.isNull() )
return false;
mimeData->setImageData(image);
return true;
}
bool setImageData(
const QVariantMap &data, const QString &mime, const char *imageFormat, const std::unique_ptr<QMimeData> &mimeData)
{
QByteArray imageData = data.value(mime).toByteArray();
return !imageData.isEmpty()
&& setImageData(imageData, imageFormat, mimeData);
}
Encoding encodingForName(const char *name)
{
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
return QTextCodec::codecForName(name);
#else
return QStringConverter::encodingForName(name);
#endif
}
Encoding encodingForText(const QByteArray &bytes)
{
// Guess unicode codec for text if BOM is missing.
if (bytes.size() >= 2 && bytes.size() % 2 == 0) {
if (bytes.size() >= 4 && bytes.size() % 4 == 0) {
if (bytes.at(0) == 0 && bytes.at(1) == 0)
return encodingForName("utf-32be");
if (bytes.at(2) == 0 && bytes.at(3) == 0)
return encodingForName("utf-32le");
}
if (bytes.at(0) == 0)
return encodingForName("utf-16be");
if (bytes.at(1) == 0)
return encodingForName("utf-16le");
}
return encodingForName("utf-8");
}
bool findFormatsWithPrefix(bool hasPrefix, const QString &prefix, const QVariantMap &data)
{
for (auto it = data.constBegin(); it != data.constEnd(); ++it) {
if ( it.key().startsWith(prefix) == hasPrefix )
return hasPrefix;
}
return !hasPrefix;
}
bool isBinaryImageFormat(const QString &format)
{
return format.startsWith(QStringLiteral("image/"))
&& !format.contains(QStringLiteral("xml"))
&& !format.contains(QStringLiteral("svg"));
}
QVariantMap cloneData(ClipboardDataGuard &data, QStringList &formats)
{
QVariantMap newdata;
/*
Some apps provide images even when copying huge spreadsheet, this can
block those apps while generating and providing the data.
This code removes ignores any image data if text is available.
Images in SVG and other XML formats are expected to be relatively small
so these doesn't have to be ignored.
*/
if ( formats.contains(mimeText) && data.hasText() ) {
const auto first = std::remove_if(
std::begin(formats), std::end(formats), isBinaryImageFormat);
formats.erase(first, std::end(formats));
}
QStringList imageFormats;
for (const auto &mime : formats) {
if (isBinaryImageFormat(mime)) {
imageFormats.append(mime);
} else {
const QByteArray bytes = data.getUtf8Data(mime);
if ( bytes.isEmpty() )
imageFormats.append(mime);
else
newdata.insert(mime, bytes);
}
}
// Retrieve images last since this can take a while.
if ( !imageFormats.isEmpty() ) {
const QImage image = data.getImageData();
if ( canCloneImageData(image) ) {
for (const auto &mime : imageFormats) {
const QString format = getImageFormatFromMime(mime);
if ( !format.isEmpty() )
cloneImageData(image, format, mime, &newdata);
}
}
}
if (data.isExpired())
return {};
// Drop duplicate UTF-8 text format.
if ( newdata.contains(mimeTextUtf8) && newdata[mimeTextUtf8] == newdata.value(mimeText) )
newdata.remove(mimeTextUtf8);
return newdata;
}
} // namespace
QVariantMap cloneData(const QMimeData &rawData, QStringList formats, const long int *clipboardSequenceNumber)
{
ClipboardDataGuard data(rawData, clipboardSequenceNumber);
return cloneData(data, formats);
}
QVariantMap cloneData(const QMimeData &rawData)
{
ClipboardDataGuard data(rawData);
static const QSet<QString> ignoredFormats({
mimeOwner,
mimeClipboardMode,
mimeCurrentTab,
mimeSelectedItems,
mimeCurrentItem,
mimeShortcut,
mimeOutputTab,
});
const QStringList availableFormats = data.formats();
QStringList formats;
bool skipBinaryImages = formats.contains(mimeText) && data.hasText();
if (!skipBinaryImages && availableFormats.contains(QStringLiteral("image/png")) ) {
formats.append(QStringLiteral("image/png"));
if ( availableFormats.contains(QStringLiteral("image/webp")) )
formats.append(QStringLiteral("image/webp"));
if ( availableFormats.contains(QStringLiteral("image/gif")) )
formats.append(QStringLiteral("image/gif"));
skipBinaryImages = true;
}
for (const auto &mime : availableFormats) {
// ignore uppercase mimetypes (e.g. UTF8_STRING, TARGETS, TIMESTAMP)
// and specific internal types
if ( mime.isEmpty() || !mime[0].isLower() || ignoredFormats.contains(mime) )
continue;
// ignore redundant image formats
if ( skipBinaryImages && isBinaryImageFormat(mime) )
continue;
formats.append(mime);
}
if ( !formats.contains(mimeText) ) {
const QString textPrefix(mimeText + QStringLiteral(";"));
const auto first = std::remove_if(
std::begin(formats), std::end(formats), [&](const QString &format){
return format.startsWith(textPrefix);
}
);
if (first != std::end(formats)) {
formats.erase(first, std::end(formats));
formats.append(mimeText);
}
}
return cloneData(data, formats);
}
QMimeData* createMimeData(const QVariantMap &data)
{
std::unique_ptr<QMimeData> newClipboardData(new MimeData);
bool hasImage =
setImageData(data, QStringLiteral("image/png"), "png", newClipboardData)
|| setImageData(data, QStringLiteral("image/bmp"), "bmp", newClipboardData)
|| setImageData(data, QStringLiteral("application/x-qt-image"), nullptr, newClipboardData)
;
for (auto it = data.constBegin(); it != data.constEnd(); ++it) {
if ( it.key() == mimeClipboardMode )
continue;
QByteArray bytes = it.value().toByteArray();
newClipboardData->setData( it.key(), bytes );
if (!hasImage) {
const QString imageFormat = getImageFormatFromMime(it.key());
if ( !imageFormat.isEmpty()
&& setImageData(bytes, imageFormat.toUtf8().constData(), newClipboardData) )
{
hasImage = true;
}
}
}
if ( !data.contains(mimeOwner) ) {
const auto owner = makeClipboardOwnerData();
if ( !owner.isEmpty() )
newClipboardData->setData( mimeOwner, owner );
}
return newClipboardData.release();
}
bool anySessionOwnsClipboardData(const QVariantMap &data)
{
return data.contains(mimeOwner);
}
QString elideText(const QString &text, const QFont &font, const QString &format,
bool escapeAmpersands, int maxWidthPixels, int maxLines)
{
if ( text.isEmpty() )
return QString();
if (maxWidthPixels <= 0)
maxWidthPixels = smallIconSize() * 20;
QStringList lines = text.split('\n');
int firstLine = -1;
int lastLine = -1;
int commonIndent = text.size();
static const QRegularExpression reNonSpace("\\S");
for (int i = 0; i < lines.size(); ++i) {
const auto &line = lines[i];
const int lineIndent = line.indexOf(reNonSpace);
if (lineIndent == -1)
continue;
if (firstLine == -1)
firstLine = i;
lastLine = i;
if (lineIndent < commonIndent)
commonIndent = lineIndent;
if (firstLine - lastLine + 1 >= maxLines)
break;
}
if (lastLine == -1)
return QLatin1String("...");
// If there are too many lines, append triple dot.
if (lastLine + 1 != lines.size())
lines[lastLine].append("...");
lines = lines.mid(firstLine, lastLine - firstLine + 1);
QFontMetrics fm(font);
#if QT_VERSION >= QT_VERSION_CHECK(5,11,0)
const int formatWidth = format.isEmpty() ? 0 : fm.horizontalAdvance(format.arg(QString()));
#else
const int formatWidth = format.isEmpty() ? 0 : fm.width(format.arg(QString()));
#endif
// Remove redundant spaces from single line text.
if (lines.size() == 1) {
lines[0] = lines[0].simplified();
commonIndent = 0;
}
// Remove common indentation each line and elide text if too long.
for (auto &line : lines) {
line = line.mid(commonIndent);
// Make eliding huge text faster.
if (line.size() > maxElidedTextLineLength)
line = line.left(maxElidedTextLineLength) + "...";
line = fm.elidedText(line, Qt::ElideMiddle, maxWidthPixels - formatWidth);
}
// If empty lines are at beginning, prepend triple dot.
if (firstLine != 0) {
if (lines.size() == 1)
lines.first().prepend("...");
else
lines.prepend("...");
}
QString result = lines.join("\n");
// Escape all ampersands.
if (escapeAmpersands)
result.replace( QLatin1Char('&'), QLatin1String("&&") );
return format.isEmpty() ? result : format.arg(result);
}
QString textLabelForData(const QVariantMap &data, const QFont &font, const QString &format,
bool escapeAmpersands, int maxWidthPixels, int maxLines)
{
QString label;
const QString notes = data.value(mimeItemNotes).toString();
if ( data.contains(mimeHidden) || data.contains(mimeSecret) ) {
label = QObject::tr("<HIDDEN>", "Label for hidden/secret clipboard content");
} else if ( data.contains(mimeText) || data.contains(mimeUriList) ) {
const QString text = getTextData(data);
const int n = text.count(QChar('\n')) + 1;
if (n > 1)
label = QObject::tr("%1 (%n lines)", "Label for multi-line text in clipboard", n);
else
label = QLatin1String("%1");
if (!format.isEmpty())
label = format.arg(label);
const QString textWithNotes = notes.isEmpty() ? text : notes + ": " + text;
return elideText(textWithNotes, font, label, escapeAmpersands, maxWidthPixels, maxLines);
} else if ( findFormatsWithPrefix(true, "image/", data) ) {
label = QObject::tr("<IMAGE>", "Label for image in clipboard");
} else if ( data.contains(mimeItems) ) {
label = QObject::tr("<ITEMS>", "Label for copied items in clipboard");
} else if ( findFormatsWithPrefix(false, COPYQ_MIME_PREFIX, data) ) {
label = QObject::tr("<EMPTY>", "Label for empty clipboard");
} else {
label = QObject::tr("<DATA>", "Label for data in clipboard");
}
if (!notes.isEmpty()) {
label = elideText(notes, font, QString(), escapeAmpersands, maxWidthPixels, maxLines)
+ ": " + label;
}
if (!format.isEmpty())
label = format.arg(label);
return label;
}
QString textLabelForData(const QVariantMap &data)
{
return textLabelForData(data, QFont(), QString());
}
void renameToUnique(QString *name, const QStringList &names)
{
const QString baseName = *name;
int i = 0;
while ( names.contains(*name) )
*name = baseName + " (" + QString::number(++i) + ')';
}
QString dataToText(const QByteArray &bytes, const QString &mime)
{
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
auto codec = (mime == mimeHtml)
? QTextCodec::codecForHtml(bytes, nullptr)
: QTextCodec::codecForUtfText(bytes, nullptr);
if (!codec)
codec = encodingForText(bytes);
return codec->toUnicode(bytes);
#else
auto encoding = (mime == mimeHtml)
? QStringConverter::encodingForHtml(bytes)
: QStringConverter::encodingForData(bytes);
if (!encoding)
encoding = encodingForText(bytes);
return QStringDecoder(*encoding).decode(bytes);
#endif
}
bool isClipboardData(const QVariantMap &data)
{
return data.value(mimeClipboardMode).toByteArray().isEmpty();
}
bool handleViKey(QKeyEvent *event, QObject *eventReceiver)
{
int key = event->key();
Qt::KeyboardModifiers mods = event->modifiers();
switch ( key ) {
case Qt::Key_G:
key = mods & Qt::ShiftModifier ? Qt::Key_End : Qt::Key_Home;
mods = mods & ~Qt::ShiftModifier;
break;
case Qt::Key_J:
key = Qt::Key_Down;
break;
case Qt::Key_K:
key = Qt::Key_Up;
break;
case Qt::Key_L:
key = Qt::Key_Return;
break;
case Qt::Key_F:
case Qt::Key_D:
case Qt::Key_B:
case Qt::Key_U:
if (mods & Qt::ControlModifier) {
key = (key == Qt::Key_F || key == Qt::Key_D) ? Qt::Key_PageDown : Qt::Key_PageUp;
mods = mods & ~Qt::ControlModifier;
} else {
return false;
}
break;
case Qt::Key_X:
key = Qt::Key_Delete;
break;
case Qt::Key_BracketLeft:
if (mods & Qt::ControlModifier) {
key = Qt::Key_Escape;
mods = mods & ~Qt::ControlModifier;
} else {
return false;
}
break;
default:
return false;
}
QKeyEvent event2(QEvent::KeyPress, key, mods, event->text());
QCoreApplication::sendEvent(eventReceiver, &event2);
event->accept();
return true;
}
bool handleEmacsKey(QKeyEvent *event, QObject *eventReceiver)
{
int key = event->key();
Qt::KeyboardModifiers mods = event->modifiers();
switch ( key ) {
case Qt::Key_V:
if (mods & Qt::ControlModifier) {
key = Qt::Key_PageDown;
mods = mods & ~Qt::ControlModifier;
break;
}
if (mods & Qt::AltModifier) {
key = Qt::Key_PageUp;
mods = mods & ~Qt::AltModifier;
break;
}
return false;
case Qt::Key_N:
if (mods & Qt::ControlModifier) {
key = Qt::Key_Down;
mods = mods & ~Qt::ControlModifier;
break;
}
return false;
case Qt::Key_P:
if (mods & Qt::ControlModifier) {
key = Qt::Key_Up;
mods = mods & ~Qt::ControlModifier;
break;
}
return false;
case Qt::Key_Less:
if ((mods & Qt::AltModifier)) {
key = Qt::Key_Home;
mods = mods & ~(Qt::ShiftModifier | Qt::AltModifier);
break;
}
return false;
case Qt::Key_Greater:
if ((mods & Qt::AltModifier)) {
key = Qt::Key_End;
mods = mods & ~(Qt::ShiftModifier | Qt::AltModifier);
break;
}
return false;
case Qt::Key_G:
if (mods & Qt::ControlModifier) {
key = Qt::Key_Escape;
mods = mods & ~Qt::ControlModifier;
break;
}
return false;
default:
return false;
}
QKeyEvent event2(QEvent::KeyPress, key, mods, event->text());
QCoreApplication::sendEvent(eventReceiver, &event2);
event->accept();
return true;
}
bool canDropToTab(const QDropEvent &event)
{
const auto &data = *event.mimeData();
return data.hasFormat(mimeItems) || data.hasText() || data.hasImage() || data.hasUrls();
}
void acceptDrag(QDropEvent *event)
{
// Default drop action in item list and tab bar/tree should be "move."
if ( event->possibleActions().testFlag(Qt::MoveAction)
&& event->mimeData()->hasFormat(mimeOwner)
#if QT_VERSION < QT_VERSION_CHECK(5,12,0)
// WORKAROUND: Test currently pressed modifiers instead of the ones in event (QTBUG-57168).
&& !QApplication::queryKeyboardModifiers().testFlag(Qt::ControlModifier)
#else
&& !event->keyboardModifiers().testFlag(Qt::ControlModifier)
#endif
)
{
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
}
QByteArray makeClipboardOwnerData()
{
static const QVariant owner = qApp->property("CopyQ_session_name");
if ( !owner.isValid() )
return QByteArray();
static int id = 0;
return owner.toString().toUtf8() + " " + logLabel() + "/" + QByteArray::number(++id);
}
QString cloneText(const QMimeData &data)
{
const auto text = dataToText( data.data(mimeText), mimeText );
return text.isEmpty() ? data.text() : text;
}
| 24,540
|
C++
|
.cpp
| 697
| 28.176471
| 118
| 0.62404
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,158
|
settings.cpp
|
hluk_CopyQ/src/common/settings.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "settings.h"
#include <QCoreApplication>
Settings::Settings()
: QSettings(
QSettings::defaultFormat(),
QSettings::UserScope,
QCoreApplication::organizationName(),
QCoreApplication::applicationName() )
{
}
Settings::Settings(const QString &path)
: QSettings(path, QSettings::IniFormat)
{
}
| 395
|
C++
|
.cpp
| 15
| 21.866667
| 47
| 0.699468
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,159
|
option.cpp
|
hluk_CopyQ/src/common/option.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "option.h"
#include <QObject>
namespace {
QString getToolTip(const QObject &object)
{
return object.property("toolTip").toString();
}
QString toolTip(const QObject &object)
{
const QString toolTip = getToolTip(object);
if ( toolTip.isEmpty() && object.parent() )
return getToolTip( *object.parent() );
return toolTip;
}
} // namespace
Option::Option()
: m_default_value()
, m_value()
, m_property_name(nullptr)
, m_obj(nullptr)
{}
Option::Option(const QVariant &default_value, const char *property_name,
QObject *obj)
: m_default_value(default_value)
, m_value(m_default_value)
, m_property_name(property_name)
, m_obj(obj)
{
if (m_obj)
m_obj->setProperty(m_property_name, m_default_value);
}
Option::Option(const QVariant &default_value, const char *description)
: m_default_value(default_value)
, m_value(m_default_value)
, m_description(description)
{
}
QVariant Option::value() const
{
return m_obj != nullptr ? m_obj->property(m_property_name) : m_value;
}
bool Option::setValue(const QVariant &value)
{
if (m_obj != nullptr) {
m_obj->setProperty(m_property_name, value);
return m_obj->property(m_property_name) == value;
}
m_value = value;
return true;
}
void Option::reset()
{
setValue(m_default_value);
}
QString Option::tooltip() const
{
if (m_obj) {
const QString tooltip = toolTip(*m_obj);
if (tooltip.isEmpty()) {
const QString text = m_obj->property("text").toString();
Q_ASSERT(!text.isEmpty());
return text;
}
return tooltip;
}
Q_ASSERT(m_description);
return m_description ? QString::fromUtf8(m_description) : QString();
}
| 1,829
|
C++
|
.cpp
| 69
| 22.086957
| 73
| 0.652897
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,160
|
display.cpp
|
hluk_CopyQ/src/common/display.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "display.h"
#include "gui/screen.h"
#include <QApplication>
#include <QPoint>
#include <QScreen>
#include <QStyle>
#include <QWidget>
#include <QWindow>
namespace {
QScreen *screenForWidget(QWidget *w)
{
if (w) {
#if QT_VERSION >= QT_VERSION_CHECK(5,14,0)
if ( w->screen() )
return w->screen();
#endif
const int i = screenNumberAt(w->pos());
const auto screens = QGuiApplication::screens();
if (0 <= i && i < screens.size())
return screens[i];
}
return QGuiApplication::primaryScreen();
}
} // namespace
int smallIconSize()
{
return QApplication::style()->pixelMetric(QStyle::PM_SmallIconSize);
}
QPoint toScreen(QPoint pos, QWidget *w)
{
QWindow *window = w->windowHandle();
w->move(pos);
const QRect availableGeometry = screenAvailableGeometry(*w);
if ( !availableGeometry.isValid() )
return pos;
const QSize size = window ? window->size() : w->size();
return QPoint(
qMax(availableGeometry.left(), qMin(pos.x(), availableGeometry.right() - size.width())),
qMax(availableGeometry.top(), qMin(pos.y(), availableGeometry.bottom() - size.height()))
);
}
int pointsToPixels(int points, QWidget *w)
{
QScreen *screen = screenForWidget(w);
return static_cast<int>(points * screen->physicalDotsPerInchX() / 72.0);
}
| 1,438
|
C++
|
.cpp
| 47
| 25.914894
| 104
| 0.655298
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,161
|
globalshortcutcommands.cpp
|
hluk_CopyQ/src/common/globalshortcutcommands.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "globalshortcutcommands.h"
#include "common/command.h"
#include <QCoreApplication>
#include <QLocale>
#include <QVector>
#ifdef COPYQ_GLOBAL_SHORTCUTS
# include "common/shortcuts.h"
# include "gui/icons.h"
namespace {
constexpr auto commandScreenshot = R"(
var imageData = screenshotSelect()
write('image/png', imageData)
copy('image/png', imageData)
)";
constexpr auto commandPasteDateTimeTemplate = R"(
// http://doc.qt.io/qt-5/qdatetime.html#toString
var format = '%1'
var dateTime = dateString(format)
copy(dateTime)
copySelection(dateTime)
paste()
)";
class AddCommandDialog final
{
Q_DECLARE_TR_FUNCTIONS(AddCommandDialog)
};
QString commandPasteDateTime()
{
const auto format = QLocale::system().dateTimeFormat(QLocale::LongFormat)
.replace("\\", "\\\\")
.replace("'", "\\'")
.replace("\n", "\\n");
return QString(commandPasteDateTimeTemplate).arg(format);
}
Command createGlobalShortcut(const QString &name, const QString &script, IconId icon, const QString &internalId)
{
Command c;
c.internalId = internalId;
c.name = name;
c.cmd = "copyq: " + script;
c.icon = QString(QChar(icon));
c.isGlobalShortcut = true;
return c;
}
} // namespace
QVector<Command> globalShortcutCommands()
{
return {
createGlobalShortcut( AddCommandDialog::tr("Show/hide main window"), "toggle()", IconRectangleList, "copyq_global_toggle"),
createGlobalShortcut( AddCommandDialog::tr("Show the tray menu"), "menu()", IconInbox, "copyq_global_menu"),
createGlobalShortcut( AddCommandDialog::tr("Show main window under mouse cursor"), "showAt()", IconRectangleList, "copyq_global_show_under_mouse"),
createGlobalShortcut( AddCommandDialog::tr("Edit clipboard"), "edit(-1)", IconPenToSquare, "copyq_global_edit_clipboard"),
createGlobalShortcut( AddCommandDialog::tr("Edit first item"), "edit(0)", IconPenToSquare, "copyq_global_edit_first_item"),
createGlobalShortcut( AddCommandDialog::tr("Copy second item"), "select(1)", IconCopy, "copyq_global_copy_second_item"),
createGlobalShortcut( AddCommandDialog::tr("Show action dialog"), "action()", IconGear, "copyq_global_show_action_dialog"),
createGlobalShortcut( AddCommandDialog::tr("Create new item"), "edit()", IconAsterisk, "copyq_global_create_new_item"),
createGlobalShortcut( AddCommandDialog::tr("Copy next item"), "next()", IconArrowDown, "copyq_global_copy_next"),
createGlobalShortcut( AddCommandDialog::tr("Copy previous item"), "previous()", IconArrowUp, "copyq_global_copy_previous"),
createGlobalShortcut( AddCommandDialog::tr("Paste clipboard as plain text"), pasteAsPlainTextScript("clipboard()"), IconPaste, "copyq_global_paste_clipboard_plain"),
createGlobalShortcut( AddCommandDialog::tr("Disable clipboard storing"), "disable()", IconEyeSlash, "copyq_global_disable_clipboard_store"),
createGlobalShortcut( AddCommandDialog::tr("Enable clipboard storing"), "enable()", IconEye, "copyq_global_enable_clipboard_store"),
createGlobalShortcut( AddCommandDialog::tr("Paste and copy next"), "paste(); next()", IconCircleArrowDown, "copyq_global_paste_copy_next"),
createGlobalShortcut( AddCommandDialog::tr("Paste and copy previous"), "paste(); previous()", IconCircleArrowUp, "copyq_global_paste_copy_previous"),
createGlobalShortcut( AddCommandDialog::tr("Take screenshot"), commandScreenshot, IconCamera, "copyq_global_screenshot"),
createGlobalShortcut( AddCommandDialog::tr("Paste current date and time"), commandPasteDateTime(), IconClock , "copyq_global_paste_datetime"),
};
}
#else
QVector<Command> globalShortcutCommands()
{
return {};
}
#endif
QString pasteAsPlainTextScript(const QString &what)
{
return "\n"
"var text = " + what + "\n"
"copy(text)\n"
"copySelection(text)\n"
"paste()";
}
| 3,991
|
C++
|
.cpp
| 82
| 44.182927
| 173
| 0.719641
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,162
|
sanitize_text_document.cpp
|
hluk_CopyQ/src/common/sanitize_text_document.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "sanitize_text_document.h"
#include <QTextBlock>
#include <QTextCursor>
#include <QTextDocument>
#ifdef Q_OS_MAC
# include <QFontDatabase>
# include <algorithm>
#endif
namespace {
constexpr int maxFontPointSize = 128;
constexpr int maxFontPixelSize = maxFontPointSize * 4 / 3;
/// Sanitize font sizes to prevent app freeze.
bool sanitizeFont(QFont *font)
{
const int pixelSize = font->pixelSize();
const int pointSize = font->pointSize();
if (-maxFontPixelSize > pixelSize || pixelSize > maxFontPixelSize) {
font->setPixelSize(maxFontPixelSize);
return true;
}
if (-maxFontPointSize > pointSize || pointSize > maxFontPointSize) {
font->setPointSize(maxFontPointSize);
return true;
}
return false;
}
} // namespace
void sanitizeTextDocument(QTextDocument *document)
{
QTextCursor tc(document);
#ifdef Q_OS_MAC
QFontDatabase fontDatabase;
#endif
for (auto block = document->begin(); block != document->end(); block = block.next()) {
for (auto it = block.begin(); !it.atEnd(); ++it) {
const QTextFragment fragment = it.fragment();
QTextCharFormat charFormat = fragment.charFormat();
bool sanitized = false;
#ifdef Q_OS_MAC
// Prevent showing font download dialog on macOS.
const QStringList fontFamilies = charFormat.fontFamilies().toStringList();
if ( !fontFamilies.isEmpty() &&
!std::any_of(fontFamilies.constBegin(), fontFamilies.constEnd(),
[&](const QString &fontFamily){ return fontDatabase.hasFamily(fontFamily); }) )
{
charFormat.setFontFamilies({});
sanitized = true;
}
#endif
QFont font = charFormat.font();
if ( sanitizeFont(&font) ) {
charFormat.setFont(font);
sanitized = true;
}
if (sanitized) {
tc.setPosition( fragment.position() );
tc.setPosition( fragment.position() + fragment.length(), QTextCursor::KeepAnchor );
tc.setCharFormat(charFormat);
}
}
}
}
| 2,240
|
C++
|
.cpp
| 63
| 27.984127
| 100
| 0.628413
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,163
|
predefinedcommands.cpp
|
hluk_CopyQ/src/common/predefinedcommands.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "predefinedcommands.h"
#include "common/command.h"
#include "common/globalshortcutcommands.h"
#include "common/mimetypes.h"
#include "common/shortcuts.h"
#include "common/textdata.h"
#include "gui/icons.h"
#include "platform/platformnativeinterface.h"
#include <QCoreApplication>
namespace {
Command *newCommand(QVector<Command> *commands)
{
commands->append(Command());
return &commands->last();
}
class AddCommandDialog final
{
Q_DECLARE_TR_FUNCTIONS(AddCommandDialog)
};
} // namespace
QVector<Command> predefinedCommands()
{
const QRegularExpression reURL("^(https?|ftps?|file)://");
const QRegularExpression reNotURL("^(?!(http|ftp)s?://)");
QVector<Command> commands = globalShortcutCommands();
Command *c;
commands.prepend(Command());
c = &commands.first();
c->name = AddCommandDialog::tr("New command");
c->icon = QString(QChar(IconFile));
c->input = c->output = QString();
c->wait = c->automatic = c->remove = false;
c->sep = QLatin1String("\\n");
c = newCommand(&commands);
c->name = AddCommandDialog::tr("Ignore items with no or single character");
c->icon = QString(QChar(IconCircleExclamation));
c->cmd = R"(function hasEmptyOrSingleCharText() {
if (dataFormats().includes(mimeText)) {
var text = str(data(mimeText));
if (text.match(/^\s*.?\s*$/)) {
serverLog('Ignoring text with single or no character');
return true;
}
}
return false;
}
var onClipboardChanged_ = onClipboardChanged;
onClipboardChanged = function() {
if (!hasEmptyOrSingleCharText()) {
onClipboardChanged_();
}
}
var synchronizeFromSelection_ = synchronizeFromSelection;
synchronizeFromSelection = function() {
if (!hasEmptyOrSingleCharText()) {
synchronizeFromSelection_();
}
}
var synchronizeToSelection_ = synchronizeToSelection;
synchronizeToSelection = function() {
if (!hasEmptyOrSingleCharText()) {
synchronizeToSelection_();
}
}
)";
c->isScript = true;
c = newCommand(&commands);
c->name = AddCommandDialog::tr("Open in &Browser");
c->re = reURL;
c->icon = QString(QChar(IconGlobe));
c->cmd = QStringLiteral("copyq open %1");
c->hideWindow = true;
c->inMenu = true;
c = newCommand(&commands);
c->name = AddCommandDialog::tr("Paste as Plain Text");
c->input = mimeText;
c->icon = QString(QChar(IconPaste));
c->cmd = QStringLiteral("copyq:") + pasteAsPlainTextScript("input()");
c->hideWindow = true;
c->inMenu = true;
c = newCommand(&commands);
c->name = AddCommandDialog::tr("Autoplay videos");
c->re = QRegularExpression("^http://.*\\.(mp4|avi|mkv|wmv|flv|ogv)$");
c->icon = QString(QChar(IconCirclePlay));
c->cmd = QStringLiteral("copyq open %1");
c->automatic = true;
c->hideWindow = true;
c->inMenu = true;
c = newCommand(&commands);
c->name = AddCommandDialog::tr("Copy URL (web address) to other tab");
c->re = reURL;
c->icon = QString(QChar(IconCopy));
c->tab = QStringLiteral("&web");
c->automatic = true;
c = newCommand(&commands);
c->name = AddCommandDialog::tr("Create thumbnail (needs ImageMagick)");
c->icon = QString(QChar(IconImage));
c->cmd = QStringLiteral("convert - -resize 92x92 png:-");
c->input = QStringLiteral("image/png");
c->output = QStringLiteral("image/png");
c->inMenu = true;
c = newCommand(&commands);
c->name = AddCommandDialog::tr("Create QR Code from URL (needs qrencode)");
c->re = reURL;
c->icon = QString(QChar(IconQrcode));
c->cmd = QStringLiteral("qrencode -o - -t PNG -s 6");
c->input = mimeText;
c->output = QStringLiteral("image/png");
c->inMenu = true;
const auto todoTab = AddCommandDialog::tr("Tasks", "Tab name for some predefined commands");
const auto todoTabQuoted = quoteString(todoTab);
c = newCommand(&commands);
c->name = AddCommandDialog::tr("Add to %1 tab", "%1 is quoted Tasks tab name")
.arg(todoTabQuoted);
c->icon = QString(QChar(IconShare));
c->tab = todoTab;
c->input = mimeText;
c->inMenu = true;
c = newCommand(&commands);
c->name = AddCommandDialog::tr("Move to %1 tab", "%1 is quoted Tasks tab name")
.arg(todoTabQuoted);
c->icon = QString(QChar(IconShare));
c->tab = todoTab;
c->remove = true;
c->inMenu = true;
c = newCommand(&commands);
c->name = AddCommandDialog::tr("Ignore copied files");
c->re = reNotURL;
c->icon = QString(QChar(IconCircleExclamation));
c->input = mimeUriList;
c->remove = true;
c->automatic = true;
if ( platformNativeInterface()->canGetWindowTitle() ) {
c = newCommand(&commands);
c->name = AddCommandDialog::tr("Ignore *\"Password\"* window");
c->wndre = QRegularExpression(AddCommandDialog::tr("Password"));
c->icon = QString(QChar(IconAsterisk));
c->remove = true;
c->automatic = true;
c->cmd = QStringLiteral("copyq ignore");
}
c = newCommand(&commands);
c->name = AddCommandDialog::tr("Move to Trash");
c->icon = QString(QChar(IconTrash));
c->inMenu = true;
c->tab = AddCommandDialog::tr("(trash)");
c->remove = true;
c = newCommand(&commands);
c->name = AddCommandDialog::tr("Clear Current Tab");
c->icon = QString(QChar(IconBroom));
c->inMenu = true;
c->cmd = QStringLiteral("copyq: ItemSelection(selectedTab()).selectRemovable().removeAll()");
c->matchCmd = QStringLiteral("copyq: tab(selectedTab()); if (size() == 0) fail()");
return commands;
}
| 5,723
|
C++
|
.cpp
| 156
| 31.762821
| 97
| 0.652103
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,164
|
server.cpp
|
hluk_CopyQ/src/common/server.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "server.h"
#include "common/common.h"
#include "common/config.h"
#include "common/clientsocket.h"
#include "common/client_server.h"
#include "common/log.h"
#include <QDir>
#include <QEventLoop>
#include <QLocalServer>
#include <QLocalSocket>
#include <QLockFile>
namespace {
bool serverIsRunning(const QString &serverName)
{
QLocalSocket socket;
socket.connectToServer(serverName);
return socket.waitForConnected(-1);
}
QString lockFilePath()
{
const QString lockFilePath = getConfigurationFilePath(".lock");
// Ensure parent dir exists.
const QString path = QDir::cleanPath( lockFilePath + QLatin1String("/..") );
QDir dir(path);
dir.mkpath(QStringLiteral("."));
return lockFilePath;
}
} // namespace
struct Server::PrivateData {
QLocalServer server;
QLockFile lockFile = lockFilePath();
int socketCount = 0;
QEventLoop *loop = nullptr;
};
Server::Server(const QString &name, QObject *parent)
: QObject(parent)
, m_data(new PrivateData)
{
if ( m_data->lockFile.tryLock() && !serverIsRunning(name) ) {
QLocalServer::removeServer(name);
if ( !m_data->server.listen(name) ) {
log( QStringLiteral("Failed to create server \"%1\": %2")
.arg(m_data->server.fullServerName(), m_data->server.errorString()),
LogError);
}
} else if (m_data->lockFile.error() == QLockFile::LockFailedError) {
COPYQ_LOG( QStringLiteral("Another process holds lock file: %1")
.arg(lockFilePath()) );
} else if (m_data->lockFile.error() == QLockFile::PermissionError) {
log( QStringLiteral("Insufficient permissions to create lock file: %1")
.arg(lockFilePath()), LogError );
} else if (m_data->lockFile.error() == QLockFile::UnknownError) {
log( QStringLiteral("Failed to lock file: %1")
.arg(lockFilePath()), LogError );
}
}
Server::~Server()
{
// Postpone destroying server, otherwise it crashes when re-creating server.
m_data->server.deleteLater();
}
void Server::start()
{
connect( &m_data->server, &QLocalServer::newConnection,
this, &Server::onNewConnection );
while (m_data->server.hasPendingConnections())
onNewConnection();
}
bool Server::isListening() const
{
return m_data->server.isListening();
}
void Server::close()
{
m_data->server.close();
if (m_data->socketCount > 0) {
COPYQ_LOG( QStringLiteral("Waiting for %1 sockets to disconnect").arg(m_data->socketCount) );
QEventLoop loop;
m_data->loop = &loop;
loop.exec(QEventLoop::ExcludeUserInputEvents);
m_data->loop = nullptr;
}
m_data->lockFile.unlock();
}
void Server::onNewConnection()
{
QLocalSocket* socket = m_data->server.nextPendingConnection();
if (!socket) {
log("No pending client connections!", LogError);
} else if ( socket->state() != QLocalSocket::ConnectedState ) {
log("Client is not connected!", LogError);
socket->deleteLater();
} else {
++m_data->socketCount;
connect( socket, &QLocalSocket::disconnected,
this, &Server::onSocketDestroyed );
auto clientSocket = std::make_shared<ClientSocket>(socket);
emit newConnection(clientSocket);
}
}
void Server::onSocketDestroyed()
{
Q_ASSERT(m_data->socketCount > 0);
--m_data->socketCount;
if (m_data->loop)
m_data->loop->quit();
}
| 3,537
|
C++
|
.cpp
| 108
| 27.574074
| 101
| 0.661579
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,165
|
clientsocket.cpp
|
hluk_CopyQ/src/common/clientsocket.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "clientsocket.h"
#include "common/client_server.h"
#include "common/log.h"
#include "common/sleeptimer.h"
#include <QDataStream>
#define SOCKET_LOG(text) \
COPYQ_LOG_VERBOSE( QString("Socket %1: %2").arg(m_socketId).arg(text) )
namespace {
ClientSocketId lastSocketId = 0;
const quint32 protocolMagicNumber = 0x0C090701;
const quint32 protocolVersion = 1;
template <typename T>
int doStreamDataSize(T value)
{
QByteArray bytes;
{
QDataStream dataStream(&bytes, QIODevice::WriteOnly);
dataStream.setVersion(QDataStream::Qt_5_0);
dataStream << value;
}
return bytes.length();
}
template <typename T>
int streamDataSize(T value)
{
static int size = doStreamDataSize<T>(value);
return size;
}
int headerDataSize()
{
QByteArray bytes;
{
QDataStream dataStream(&bytes, QIODevice::WriteOnly);
dataStream.setVersion(QDataStream::Qt_5_0);
dataStream << protocolMagicNumber << protocolVersion;
}
return bytes.length();
}
template <typename T>
bool readValue(T *value, QByteArray *message)
{
QDataStream stream(*message);
stream.setVersion(QDataStream::Qt_5_0);
stream >> *value;
message->remove(0, streamDataSize(*value));
return stream.status() == QDataStream::Ok;
}
bool writeMessage(QLocalSocket *socket, const QByteArray &msg)
{
COPYQ_LOG_VERBOSE( QString("Write message (%1 bytes).").arg(msg.size()) );
QDataStream out(socket);
out.setVersion(QDataStream::Qt_5_0);
// length is serialized as a quint32, followed by msg
const auto length = static_cast<quint32>(msg.length());
out << protocolMagicNumber << protocolVersion;
out.writeBytes( msg.constData(), length );
if (out.status() != QDataStream::Ok) {
COPYQ_LOG("Cannot write message!");
return false;
}
COPYQ_LOG_VERBOSE("Message written.");
return true;
}
} //namespace
LocalSocketGuard::LocalSocketGuard(QLocalSocket *socket)
: m_socket(socket)
{
}
LocalSocketGuard::~LocalSocketGuard()
{
if (m_socket) {
if (m_socket->state() == QLocalSocket::UnconnectedState)
m_socket->deleteLater();
else
m_socket->disconnectFromServer();
}
}
ClientSocket::ClientSocket()
: QObject()
, m_socket(nullptr)
, m_socketId(++lastSocketId)
, m_closed(true)
{
}
ClientSocket::ClientSocket(const QString &serverName, QObject *parent)
: QObject(parent)
, m_socket(new QLocalSocket)
, m_socketId(++lastSocketId)
, m_closed(false)
{
m_socket->connectToServer(serverName);
// Try to connect again in case the server just started.
if ( m_socket->state() == QLocalSocket::UnconnectedState ) {
COPYQ_LOG("Waiting for server to start");
SleepTimer t(1000);
do {
m_socket->connectToServer(serverName);
} while ( m_socket->state() == QLocalSocket::UnconnectedState && t.sleep() );
}
}
ClientSocket::ClientSocket(QLocalSocket *socket, QObject *parent)
: QObject(parent)
, m_socket(socket)
, m_socketId(++lastSocketId)
, m_closed(false)
{
}
ClientSocket::~ClientSocket()
{
SOCKET_LOG("Destroying socket.");
close();
}
bool ClientSocket::start()
{
if ( !m_socket || !m_socket->waitForConnected(4000) )
{
emit connectionFailed(id());
return false;
}
SOCKET_LOG("Creating socket.");
connect( m_socket.get(), &QLocalSocket::stateChanged,
this, &ClientSocket::onStateChanged );
#if QT_VERSION >= QT_VERSION_CHECK(5,15,0)
connect( m_socket.get(), &QLocalSocket::errorOccurred,
#else
connect( m_socket.get(), static_cast<void (QLocalSocket::*)(QLocalSocket::LocalSocketError)>(&QLocalSocket::error),
#endif
this, &ClientSocket::onError );
connect( m_socket.get(), &QLocalSocket::readyRead,
this, &ClientSocket::onReadyRead );
onStateChanged(m_socket->state());
onReadyRead();
return true;
}
void ClientSocket::sendMessage(const QByteArray &message, int messageCode)
{
SOCKET_LOG( QString("Sending message to client (exit code: %1).").arg(messageCode) );
if (!m_socket) {
SOCKET_LOG("Cannot send message to client. Socket is already deleted.");
} else if (m_closed) {
SOCKET_LOG("Client disconnected!");
} else {
QByteArray msg;
QDataStream out(&msg, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_0);
out << static_cast<qint32>(messageCode);
out.writeRawData( message.constData(), message.length() );
if ( writeMessage(m_socket, msg) )
SOCKET_LOG("Message sent to client.");
else
SOCKET_LOG("Failed to send message to client!");
}
}
void ClientSocket::close()
{
if (m_socket) {
SOCKET_LOG("Disconnecting socket.");
m_socket->disconnectFromServer();
}
}
void ClientSocket::onReadyRead()
{
if (!m_socket) {
SOCKET_LOG("Cannot read message from client. Socket is already deleted.");
return;
}
const qint64 available = m_socket->bytesAvailable();
m_message.append( m_socket->read(available) );
while ( !m_message.isEmpty() ) {
if (!m_hasMessageLength) {
const int preambleSize = headerDataSize() + streamDataSize(m_messageLength);
if ( m_message.length() < preambleSize )
break;
{
QDataStream stream(m_message);
stream.setVersion(QDataStream::Qt_5_0);
quint32 magicNumber;
quint32 version;
stream >> magicNumber >> version >> m_messageLength;
if ( stream.status() != QDataStream::Ok ) {
error("Failed to read message length from client!");
return;
}
if (magicNumber != protocolMagicNumber) {
error("Unexpected message magic number from client!");
return;
}
if (version != protocolVersion) {
error("Unexpected message version from client!");
return;
}
}
m_message.remove(0, preambleSize);
m_hasMessageLength = true;
}
const auto length = static_cast<int>(m_messageLength);
if ( m_message.length() < length )
break;
QByteArray msg = m_message.mid(0, length);
qint32 messageCode;
if ( !readValue(&messageCode, &msg) ) {
error("Failed to read message code from client!");
return;
}
m_hasMessageLength = false;
m_message = m_message.mid(length);
emit messageReceived(msg, messageCode, id());
}
}
void ClientSocket::onError(QLocalSocket::LocalSocketError error)
{
if (error == QLocalSocket::SocketTimeoutError)
return;
if (error == QLocalSocket::PeerClosedError
|| (error == QLocalSocket::ConnectionError
&& m_socket->errorString().startsWith("QLocalSocketPrivate::completeAsyncRead")) )
{
SOCKET_LOG("Disconnected from client.");
} else {
log( m_socket->errorString(), LogError );
}
onStateChanged(QLocalSocket::UnconnectedState);
}
void ClientSocket::onStateChanged(QLocalSocket::LocalSocketState state)
{
if (!m_closed) {
m_closed = state == QLocalSocket::UnconnectedState;
if (m_closed) {
if (m_hasMessageLength)
log("ERROR: Socket disconnected before receiving message", LogError);
emit disconnected(id());
}
}
}
void ClientSocket::error(const QString &errorMessage)
{
log(errorMessage, LogError);
if (m_socket)
m_socket->abort();
onStateChanged(QLocalSocket::UnconnectedState);
}
| 7,885
|
C++
|
.cpp
| 242
| 26.057851
| 119
| 0.637956
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,166
|
actionoutput.cpp
|
hluk_CopyQ/src/common/actionoutput.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "actionoutput.h"
#include "common/action.h"
#include "common/contenttype.h"
#include "common/mimetypes.h"
#include "common/textdata.h"
#include "gui/clipboardbrowser.h"
#include "gui/mainwindow.h"
#include "item/serialize.h"
#include <QObject>
#include <QPersistentModelIndex>
namespace {
template <typename ActionOutput>
void connectActionOutput(Action *action, ActionOutput *actionOutput)
{
QObject::connect( action, &Action::actionOutput,
actionOutput, &ActionOutput::onActionOutput );
QObject::connect( action, &Action::actionFinished,
actionOutput, &ActionOutput::onActionFinished );
action->setReadOutput(true);
}
class ActionOutputItems final : public QObject
{
public:
ActionOutputItems(
MainWindow *wnd,
Action *action,
const QString &outputItemFormat,
const QString &outputTabName,
const QRegularExpression &itemSeparator)
: QObject(action)
, m_wnd(wnd)
, m_outputFormat(outputItemFormat)
, m_tab(outputTabName)
, m_sep(itemSeparator)
{
connectActionOutput(action, this);
}
void onActionOutput(const QByteArray &output)
{
m_lastOutput.append( getTextData(output) );
auto items = m_lastOutput.split(m_sep);
m_lastOutput = items.takeLast();
if ( !items.isEmpty() )
addItems(items);
}
void onActionFinished(Action *)
{
if ( !m_lastOutput.isEmpty() )
addItems(QStringList() << m_lastOutput);
}
private:
void addItems(const QStringList &items)
{
ClipboardBrowser *c = m_tab.isEmpty() ? m_wnd->browser() : m_wnd->tab(m_tab);
for (const auto &item : items)
c->add( createDataMap(m_outputFormat, item) );
}
MainWindow *m_wnd;
QString m_outputFormat;
QString m_tab;
QRegularExpression m_sep;
QString m_lastOutput;
};
class ActionOutputItem final : public QObject
{
public:
ActionOutputItem(
MainWindow *wnd,
Action *action,
const QString &outputItemFormat,
const QString &outputTabName)
: QObject(action)
, m_wnd(wnd)
, m_outputFormat(outputItemFormat)
, m_tab(outputTabName)
{
connectActionOutput(action, this);
}
void onActionOutput(const QByteArray &output)
{
m_output.append(output);
}
void onActionFinished(Action *)
{
if ( m_output.isEmpty() )
return;
ClipboardBrowser *c = m_tab.isEmpty() ? m_wnd->browser() : m_wnd->tab(m_tab);
c->add( createDataMap(m_outputFormat, m_output) );
}
private:
MainWindow *m_wnd;
QString m_outputFormat;
QString m_tab;
QByteArray m_output;
};
class ActionOutputIndex final : public QObject
{
public:
ActionOutputIndex(
MainWindow *wnd,
Action *action,
const QString &outputItemFormat,
const QModelIndex &index)
: QObject(action)
, m_wnd(wnd)
, m_outputFormat(outputItemFormat)
, m_index(index)
{
connectActionOutput(action, this);
}
void onActionOutput(const QByteArray &output)
{
m_output.append(output);
changeItem();
}
void onActionFinished(Action *action)
{
changeItem();
auto removeFormats = action->inputFormats();
if ( !removeFormats.isEmpty() ) {
ClipboardBrowser *c = m_wnd->browserForItem(m_index);
if (c) {
removeFormats.removeAll(m_outputFormat);
if ( !removeFormats.isEmpty() )
c->model()->setData(m_index, removeFormats, contentType::removeFormats);
}
}
}
private:
void changeItem()
{
ClipboardBrowser *c = m_wnd->browserForItem(m_index);
if (c == nullptr)
return;
QVariantMap dataMap;
if (m_outputFormat == mimeItems)
deserializeData(&dataMap, m_output);
else
dataMap.insert(m_outputFormat, m_output);
c->model()->setData(m_index, dataMap, contentType::updateData);
}
MainWindow *m_wnd;
QString m_outputFormat;
QPersistentModelIndex m_index;
QByteArray m_output;
};
} // namespace
void actionOutput(
MainWindow *wnd,
Action *action,
const QString &outputItemFormat,
const QString &outputTabName,
const QRegularExpression &itemSeparator
)
{
new ActionOutputItems(wnd, action, outputItemFormat, outputTabName, itemSeparator);
}
void actionOutput(
MainWindow *wnd,
Action *action,
const QString &outputItemFormat,
const QString &outputTabName
)
{
new ActionOutputItem(wnd, action, outputItemFormat, outputTabName);
}
void actionOutput(
MainWindow *wnd,
Action *action,
const QString &outputItemFormat,
const QModelIndex &index
)
{
new ActionOutputIndex(wnd, action, outputItemFormat, index);
}
| 5,146
|
C++
|
.cpp
| 176
| 22.284091
| 92
| 0.634359
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,167
|
commandstore.cpp
|
hluk_CopyQ/src/common/commandstore.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "commandstore.h"
#include "common/command.h"
#include "common/common.h"
#include "common/config.h"
#include "common/mimetypes.h"
#include "common/settings.h"
#include "common/temporarysettings.h"
#include "common/textdata.h"
#include <QSettings>
#include <QString>
namespace {
const QLatin1String falseString("false");
const QLatin1String trueString("true");
void normalizeLineBreaks(QString &cmd)
{
if (cmd.startsWith("\n ")) {
cmd.remove(0, 5);
cmd.replace("\n ", "\n");
} else if (cmd.startsWith("\r\n ")) {
cmd.remove(0, 6);
cmd.replace("\r\n ", "\n");
}
}
void loadCommand(const QSettings &settings, Commands *commands)
{
Command c;
c.enable = settings.value(QStringLiteral("Enable"), true).toBool();
c.name = settings.value(QStringLiteral("Name")).toString();
c.re = QRegularExpression( settings.value(QStringLiteral("Match")).toString() );
c.wndre = QRegularExpression( settings.value(QStringLiteral("Window")).toString() );
c.matchCmd = settings.value(QStringLiteral("MatchCommand")).toString();
c.cmd = settings.value(QStringLiteral("Command")).toString();
c.sep = settings.value(QStringLiteral("Separator")).toString();
c.input = settings.value(QStringLiteral("Input")).toString();
if (c.input == falseString || c.input == trueString)
c.input = c.input == trueString ? mimeText : QLatin1String();
c.output = settings.value(QStringLiteral("Output")).toString();
if (c.output == falseString || c.output == trueString)
c.output = c.output == trueString ? mimeText : QLatin1String();
c.wait = settings.value(QStringLiteral("Wait")).toBool();
c.automatic = settings.value(QStringLiteral("Automatic")).toBool();
c.display = settings.value(QStringLiteral("Display")).toBool();
c.transform = settings.value(QStringLiteral("Transform")).toBool();
c.hideWindow = settings.value(QStringLiteral("HideWindow")).toBool();
c.icon = settings.value(QStringLiteral("Icon")).toString();
c.shortcuts = settings.value(QStringLiteral("Shortcut")).toStringList();
c.globalShortcuts = settings.value(QStringLiteral("GlobalShortcut")).toStringList();
c.tab = settings.value(QStringLiteral("Tab")).toString();
c.outputTab = settings.value(QStringLiteral("OutputTab")).toString();
c.internalId = settings.value(QStringLiteral("InternalId")).toString();
c.inMenu = settings.value(QStringLiteral("InMenu")).toBool();
c.isScript = settings.value(QStringLiteral("IsScript")).toBool();
const auto globalShortcutsOption = settings.value(QStringLiteral("IsGlobalShortcut"));
if ( globalShortcutsOption.isValid() ) {
c.isGlobalShortcut = globalShortcutsOption.toBool();
} else {
// Backwards compatibility with v3.1.2 and below.
if ( c.globalShortcuts.contains(QLatin1String("DISABLED")) )
c.globalShortcuts.clear();
c.isGlobalShortcut = !c.globalShortcuts.isEmpty();
}
if (settings.value(QStringLiteral("Ignore")).toBool())
c.remove = c.automatic = true;
else
c.remove = settings.value(QStringLiteral("Remove")).toBool();
commands->append(c);
}
void saveValue(const QString &key, const QRegularExpression &re, QSettings *settings)
{
settings->setValue(key, re.pattern());
}
void saveValue(const QString &key, const QVariant &value, QSettings *settings)
{
settings->setValue(key, value);
}
/// Save only modified command properties.
template <typename Member>
void saveNewValue(const QString &key, const Command &command, const Member &member, QSettings *settings)
{
if (command.*member != Command().*member)
saveValue(key, command.*member, settings);
}
void saveCommand(const Command &c, QSettings *settings)
{
saveNewValue(QStringLiteral("Name"), c, &Command::name, settings);
saveNewValue(QStringLiteral("Match"), c, &Command::re, settings);
saveNewValue(QStringLiteral("Window"), c, &Command::wndre, settings);
saveNewValue(QStringLiteral("MatchCommand"), c, &Command::matchCmd, settings);
saveNewValue(QStringLiteral("Command"), c, &Command::cmd, settings);
saveNewValue(QStringLiteral("Input"), c, &Command::input, settings);
saveNewValue(QStringLiteral("Output"), c, &Command::output, settings);
// Separator for new command is set to '\n' for convenience.
// But this value shouldn't be saved if output format is not set.
if ( c.sep != QLatin1String("\\n") || !c.output.isEmpty() )
saveNewValue(QStringLiteral("Separator"), c, &Command::sep, settings);
saveNewValue(QStringLiteral("Wait"), c, &Command::wait, settings);
saveNewValue(QStringLiteral("Automatic"), c, &Command::automatic, settings);
saveNewValue(QStringLiteral("Display"), c, &Command::display, settings);
saveNewValue(QStringLiteral("InMenu"), c, &Command::inMenu, settings);
saveNewValue(QStringLiteral("IsGlobalShortcut"), c, &Command::isGlobalShortcut, settings);
saveNewValue(QStringLiteral("IsScript"), c, &Command::isScript, settings);
saveNewValue(QStringLiteral("Transform"), c, &Command::transform, settings);
saveNewValue(QStringLiteral("Remove"), c, &Command::remove, settings);
saveNewValue(QStringLiteral("HideWindow"), c, &Command::hideWindow, settings);
saveNewValue(QStringLiteral("Enable"), c, &Command::enable, settings);
saveNewValue(QStringLiteral("Icon"), c, &Command::icon, settings);
saveNewValue(QStringLiteral("Shortcut"), c, &Command::shortcuts, settings);
saveNewValue(QStringLiteral("GlobalShortcut"), c, &Command::globalShortcuts, settings);
saveNewValue(QStringLiteral("Tab"), c, &Command::tab, settings);
saveNewValue(QStringLiteral("OutputTab"), c, &Command::outputTab, settings);
saveNewValue(QStringLiteral("InternalId"), c, &Command::internalId, settings);
}
Commands importCommands(QSettings *settings)
{
auto commands = loadCommands(settings);
for (auto &command : commands) {
normalizeLineBreaks(command.cmd);
normalizeLineBreaks(command.matchCmd);
}
return commands;
}
} // namespace
Commands loadAllCommands()
{
const QString commandConfigPath = getConfigurationFilePath("-commands.ini");
return importCommandsFromFile(commandConfigPath);
}
void saveCommands(const Commands &commands)
{
Settings settings(getConfigurationFilePath("-commands.ini"));
saveCommands(commands, &settings);
}
Commands loadCommands(QSettings *settings)
{
Commands commands;
const QStringList groups = settings->childGroups();
if ( groups.contains("Command") ) {
settings->beginGroup("Command");
loadCommand(*settings, &commands);
settings->endGroup();
}
const int size = settings->beginReadArray("Commands");
// Allow undefined "size" for the array in settings.
if (size == 0) {
for (int i = 0; ; ++i) {
settings->setArrayIndex(i);
if ( settings->childKeys().isEmpty() )
break;
loadCommand(*settings, &commands);
}
} else {
for (int i = 0; i < size; ++i) {
settings->setArrayIndex(i);
loadCommand(*settings, &commands);
}
}
settings->endArray();
return commands;
}
void saveCommands(const Commands &commands, QSettings *settings)
{
settings->remove("Commands");
settings->remove("Command");
if (commands.size() == 1) {
settings->beginGroup("Command");
saveCommand(commands[0], settings);
settings->endGroup();
} else {
settings->beginWriteArray("Commands");
int i = 0;
for (const auto &c : commands) {
settings->setArrayIndex(i++);
saveCommand(c, settings);
}
settings->endArray();
}
}
Commands importCommandsFromFile(const QString &filePath)
{
QSettings commandsSettings(filePath, QSettings::IniFormat);
return importCommands(&commandsSettings);
}
Commands importCommandsFromText(const QString &commands)
{
TemporarySettings temporarySettings(commands.toUtf8());
return importCommands( temporarySettings.settings() );
}
QString exportCommands(const Commands &commands)
{
TemporarySettings temporarySettings;
saveCommands( commands, temporarySettings.settings() );
// Replace ugly '\n' with indented lines.
const QString data = getTextData( temporarySettings.content() );
QString commandData;
QRegularExpression re(R"(^(\d+\\)?(Command|MatchCommand)="?)");
for (const auto &line : data.split('\n')) {
const auto m = re.match(line);
if (m.hasMatch()) {
int i = m.capturedLength();
commandData.append(line.left(i));
const bool addQuotes = !commandData.endsWith('"');
if (addQuotes)
commandData.append('"');
commandData.append('\n');
const QLatin1String indent(" ");
bool escape = false;
for (; i < line.size(); ++i) {
const QChar c = line[i];
if (escape) {
escape = false;
if (c == 'n') {
commandData.append('\n');
} else {
if ( commandData.endsWith('\n') )
commandData.append(indent);
commandData.append('\\');
commandData.append(c);
}
} else if (c == '\\') {
escape = !escape;
} else {
if ( commandData.endsWith('\n') )
commandData.append(indent);
commandData.append(c);
}
}
if (addQuotes)
commandData.append('"');
} else {
commandData.append(line);
}
commandData.append('\n');
}
return commandData.trimmed();
}
| 10,030
|
C++
|
.cpp
| 236
| 35.639831
| 104
| 0.657638
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,168
|
mimetypes.cpp
|
hluk_CopyQ/src/common/mimetypes.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "mimetypes.h"
#include <QLatin1String>
const QLatin1String mimePrivatePrefix(COPYQ_MIME_PRIVATE_PREFIX);
const QLatin1String mimeText("text/plain");
const QLatin1String mimeTextUtf8("text/plain;charset=utf-8");
const QLatin1String mimeHtml("text/html");
const QLatin1String mimeUriList("text/uri-list");
const QLatin1String mimeWindowTitle(COPYQ_MIME_PREFIX "owner-window-title");
const QLatin1String mimeItems(COPYQ_MIME_PREFIX "item");
const QLatin1String mimeItemNotes(COPYQ_MIME_PREFIX "item-notes");
const QLatin1String mimeIcon(COPYQ_MIME_PREFIX "item-icon");
const QLatin1String mimeOwner(COPYQ_MIME_PREFIX "owner");
const QLatin1String mimeClipboardMode(COPYQ_MIME_PREFIX "clipboard-mode");
const QLatin1String mimeCurrentTab(COPYQ_MIME_PREFIX "current-tab");
const QLatin1String mimeSelectedItems(COPYQ_MIME_PREFIX "selected-items");
const QLatin1String mimeCurrentItem(COPYQ_MIME_PREFIX "current-item");
const QLatin1String mimeHidden(COPYQ_MIME_PREFIX "hidden");
const QLatin1String mimeShortcut(COPYQ_MIME_PREFIX "shortcut");
const QLatin1String mimeColor(COPYQ_MIME_PREFIX "color");
const QLatin1String mimeOutputTab(COPYQ_MIME_PREFIX "output-tab");
const QLatin1String mimeDisplayItemInMenu(COPYQ_MIME_PREFIX "display-item-in-menu");
const QLatin1String mimeSecret(COPYQ_MIME_PREFIX "secret");
| 1,365
|
C++
|
.cpp
| 23
| 58.217391
| 84
| 0.831217
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,169
|
action.cpp
|
hluk_CopyQ/src/common/action.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "action.h"
#include "common/log.h"
#include "common/mimetypes.h"
#include "common/processsignals.h"
#include "common/timer.h"
#include "item/serialize.h"
#include <QCoreApplication>
#include <QEventLoop>
#include <QPointer>
#include <QProcessEnvironment>
#include <QRegularExpression>
#include <QTimer>
namespace {
void startProcess(QProcess *process, const QStringList &args, QIODevice::OpenModeFlag mode)
{
QString executable = args.value(0);
// Replace "copyq" command with full application path.
if (executable == "copyq")
executable = QCoreApplication::applicationFilePath();
process->start(executable, args.mid(1), mode);
}
template <typename Entry, typename Container>
void appendAndClearNonEmpty(Entry &entry, Container &container)
{
if ( !entry.isEmpty() ) {
container.append(entry);
entry.clear();
}
}
bool getScriptFromLabel(const char *labelStr, const QString &cmd, int i, QString *script)
{
const QLatin1String label(labelStr);
#if QT_VERSION < QT_VERSION_CHECK(5,10,0)
const auto mid = cmd.midRef(i, label.size());
#else
const auto mid = QStringView(cmd).mid(i, label.size());
#endif
if (mid == label) {
*script = cmd.mid(i + label.size());
return true;
}
return false;
}
QList< QList<QStringList> > parseCommands(const QString &cmd, const QStringList &capturedTexts)
{
QList< QList<QStringList> > lines;
QList<QStringList> commands;
QStringList command;
QString script;
QString arg;
QChar quote;
bool escape = false;
bool percent = false;
// Ignore escape sequences if command starts with an unescaped Windows path.
const QRegularExpression reUnescapedWindowsPath(R"(^\s*['"]?[a-zA-Z]:\\[^\\])");
const bool allowEscape = !cmd.contains(reUnescapedWindowsPath);
for (int i = 0; i < cmd.size(); ++i) {
const QChar &c = cmd[i];
if (percent) {
if (c == '1' || (c >= '2' && c <= '9' && capturedTexts.size() > 1)) {
arg.resize( arg.size() - 1 );
arg.append( capturedTexts.value(c.digitValue() - 1) );
continue;
}
}
percent = !escape && c == '%';
if (escape) {
escape = false;
if (c == 'n') {
arg.append('\n');
} else if (c == 't') {
arg.append('\t');
} else if (c == '\n') {
// Ignore escaped new line character.
} else {
arg.append(c);
}
} else if (allowEscape && c == '\\') {
escape = true;
} else if (!quote.isNull()) {
if (quote == c) {
quote = QChar();
command.append(arg);
arg.clear();
} else {
arg.append(c);
}
} else if (c == '\'' || c == '"') {
quote = c;
} else if (c == '|') {
appendAndClearNonEmpty(arg, command);
appendAndClearNonEmpty(command, commands);
} else if (c == '\n' || c == ';') {
appendAndClearNonEmpty(arg, command);
appendAndClearNonEmpty(command, commands);
appendAndClearNonEmpty(commands, lines);
} else if ( c.isSpace() ) {
if (!arg.isEmpty()) {
command.append(arg);
arg.clear();
}
} else if ( c == ':' && i + 1 < cmd.size() && cmd[i+1] == '\n' ) {
// If there is unescaped colon at the end of a line,
// treat the rest of the command as single argument.
appendAndClearNonEmpty(arg, command);
arg = cmd.mid(i + 2);
break;
} else {
if ( arg.isEmpty() && command.isEmpty() ) {
// Treat command as script if known label is present.
if ( getScriptFromLabel("copyq:", cmd, i, &script) )
command << "copyq" << "eval" << "--" << script;
else if ( getScriptFromLabel("sh:", cmd, i, &script) )
command << "sh" << "-c" << "--" << script << "--";
else if ( getScriptFromLabel("bash:", cmd, i, &script) )
command << "bash" << "-c" << "--" << script << "--";
else if ( getScriptFromLabel("perl:", cmd, i, &script) )
command << "perl" << "-e" << script << "--";
else if ( getScriptFromLabel("python:", cmd, i, &script) )
command << "python" << "-c" << script;
else if ( getScriptFromLabel("ruby:", cmd, i, &script) )
command << "ruby" << "-e" << script << "--";
if ( !script.isEmpty() ) {
command.append( capturedTexts.mid(1) );
commands.append(command);
lines.append(commands);
return lines;
}
}
arg.append(c);
}
}
appendAndClearNonEmpty(arg, command);
appendAndClearNonEmpty(command, commands);
appendAndClearNonEmpty(commands, lines);
return lines;
}
template <typename Iterator>
void pipeThroughProcesses(Iterator begin, Iterator end)
{
auto it1 = begin;
for (auto it2 = it1 + 1; it2 != end; it1 = it2++) {
(*it1)->setStandardOutputProcess(*it2);
connectProcessFinished(*it2, *it1, &QProcess::terminate);
}
}
} // namespace
void terminateProcess(QProcess *p)
{
if (p->state() == QProcess::NotRunning)
return;
p->terminate();
if ( p->state() != QProcess::NotRunning && !p->waitForFinished(5000) ) {
p->kill();
p->waitForFinished(5000);
}
}
Action::Action(QObject *parent)
: QObject(parent)
, m_failed(false)
, m_currentLine(-1)
, m_exitCode(0)
{
}
Action::~Action()
{
closeSubCommands();
}
QString Action::commandLine() const
{
QString text;
for ( const auto &line : m_cmds ) {
for ( const auto &args : line ) {
if ( !text.isEmpty() )
text.append(QChar('|'));
text.append(args.join(" "));
}
text.append('\n');
}
return text.trimmed();
}
void Action::setCommand(const QString &command, const QStringList &arguments)
{
m_cmds = parseCommands(command, arguments);
}
void Action::setCommand(const QStringList &arguments)
{
m_cmds.clear();
m_cmds.append(QList<QStringList>() << arguments);
}
void Action::setInputWithFormat(const QVariantMap &data, const QString &inputFormat)
{
if (inputFormat == mimeItems) {
m_input = serializeData(data);
m_inputFormats = data.keys();
} else {
m_input = data.value(inputFormat).toByteArray();
m_inputFormats = QStringList(inputFormat);
}
}
void Action::start()
{
closeSubCommands();
if ( m_currentLine + 1 >= m_cmds.size() ) {
finish();
return;
}
++m_currentLine;
const QList<QStringList> &cmds = m_cmds[m_currentLine];
Q_ASSERT( !cmds.isEmpty() );
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
if (m_id != -1)
env.insert("COPYQ_ACTION_ID", QString::number(m_id));
if ( !m_name.isEmpty() )
env.insert("COPYQ_ACTION_NAME", m_name);
for (int i = 0; i < cmds.size(); ++i) {
auto process = new QProcess(this);
m_processes.push_back(process);
process->setProcessEnvironment(env);
if ( !m_workingDirectoryPath.isEmpty() )
process->setWorkingDirectory(m_workingDirectoryPath);
connectProcessError(process, this, &Action::onSubProcessError);
connect( process, &QProcess::readyReadStandardError,
this, &Action::onSubProcessErrorOutput );
}
pipeThroughProcesses(m_processes.constBegin(), m_processes.constEnd());
QProcess *lastProcess = m_processes.back();
connect( lastProcess, &QProcess::started,
this, &Action::onSubProcessStarted );
connectProcessFinished( lastProcess, this, &Action::onSubProcessFinished );
connect( lastProcess, &QProcess::readyReadStandardOutput,
this, &Action::onSubProcessOutput );
// Writing directly to stdin of a process on Windows can hang the app.
QProcess *firstProcess = m_processes.front();
connect( firstProcess, &QProcess::started,
this, &Action::writeInput, Qt::QueuedConnection );
connect( firstProcess, &QProcess::bytesWritten,
this, &Action::onBytesWritten, Qt::QueuedConnection );
const bool needWrite = !m_input.isEmpty();
if (m_processes.size() == 1) {
const auto mode =
(needWrite && m_readOutput) ? QIODevice::ReadWrite
: needWrite ? QIODevice::WriteOnly
: m_readOutput ? QIODevice::ReadOnly
: QIODevice::NotOpen;
startProcess(firstProcess, cmds.first(), mode);
} else {
auto it = m_processes.begin();
auto cmdIt = cmds.constBegin();
startProcess(*it, *cmdIt, needWrite ? QIODevice::ReadWrite : QIODevice::ReadOnly);
for (++it, ++cmdIt; it != m_processes.end() - 1; ++it, ++cmdIt)
startProcess(*it, *cmdIt, QIODevice::ReadWrite);
startProcess(lastProcess, cmds.last(), m_readOutput ? QIODevice::ReadWrite : QIODevice::WriteOnly);
}
}
bool Action::waitForFinished(int msecs)
{
if ( !isRunning() )
return true;
QPointer<QObject> self(this);
QEventLoop loop;
QTimer t;
connect(this, &Action::actionFinished, &loop, &QEventLoop::quit);
if (msecs >= 0) {
connect(&t, &QTimer::timeout, &loop, &QEventLoop::quit);
t.setSingleShot(true);
t.start(msecs);
}
loop.exec(QEventLoop::AllEvents);
// Loop stopped because application is exiting?
while ( self && isRunning() && (msecs < 0 || t.isActive()) )
QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents, 10);
return !self || !isRunning();
}
bool Action::isRunning() const
{
return !m_processes.empty() && m_processes.back()->state() != QProcess::NotRunning;
}
void Action::setData(const QVariantMap &data)
{
m_data = data;
}
const QVariantMap &Action::data() const
{
return m_data;
}
void Action::appendOutput(const QByteArray &output)
{
if ( !output.isEmpty() )
emit actionOutput(output);
}
void Action::appendErrorOutput(const QByteArray &errorOutput)
{
m_errorOutput.append(errorOutput);
}
void Action::onSubProcessError(int error)
{
QProcess *p = qobject_cast<QProcess*>(sender());
Q_ASSERT(p);
// Ignore write-to-process error, process can ignore the input.
if (error != QProcess::WriteError) {
if (!m_errorString.isEmpty())
m_errorString.append("\n");
m_errorString.append( p->errorString() );
m_failed = true;
}
if ( !isRunning() )
finish();
}
void Action::onSubProcessStarted()
{
if (m_currentLine == 0)
emit actionStarted(this);
}
void Action::onSubProcessFinished()
{
onSubProcessOutput();
start();
}
void Action::onSubProcessOutput()
{
if ( m_processes.empty() )
return;
QProcess *p = m_processes.back();
if ( p->isReadable() )
appendOutput( p->readAll() );
}
void Action::onSubProcessErrorOutput()
{
QProcess *p = qobject_cast<QProcess*>(sender());
Q_ASSERT(p);
if ( p->isReadable() )
appendErrorOutput( p->readAllStandardError() );
}
void Action::writeInput()
{
if (m_processes.empty())
return;
QProcess *p = m_processes.front();
if (m_input.isEmpty())
p->closeWriteChannel();
else
p->write(m_input);
}
void Action::onBytesWritten()
{
if ( !m_processes.empty() )
m_processes.front()->closeWriteChannel();
}
void Action::terminate()
{
if (m_processes.empty())
return;
for (auto p : m_processes)
p->terminate();
waitForFinished(5000);
for (auto p : m_processes)
terminateProcess(p);
}
void Action::closeSubCommands()
{
terminate();
if (m_processes.empty())
return;
QProcess *last = m_processes.back();
m_exitCode = last->exitCode();
m_failed = m_failed || last->exitStatus() != QProcess::NormalExit;
for (auto p : m_processes)
p->deleteLater();
m_processes.clear();
}
void Action::finish()
{
closeSubCommands();
emit actionFinished(this);
}
| 12,501
|
C++
|
.cpp
| 377
| 26.251989
| 107
| 0.59376
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,170
|
client_server.cpp
|
hluk_CopyQ/src/common/client_server.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "common/client_server.h"
#include "common/config.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QString>
#include <QStringList>
#include <QtGlobal>
QString clipboardServerName()
{
// applicationName changes case depending on whether this is a GUI app
// or a console app on OS X.
const QString appName = QCoreApplication::applicationName().toLower();
#ifdef Q_OS_UNIX
const QString socketPath = settingsDirectoryPath();
QDir(socketPath).mkpath(".");
// On Unix, files for local socket are created in temporary path which can be
// overridden by environment variable. This can lead to having multiple
// instances that can write simultaneously to same settings and data files.
// It's ugly but creating socket files in settings directory should fix this.
return socketPath + "/." + appName + "_s";
#else
return appName + "_" + qgetenv("USERNAME") + "_s";
#endif
}
| 993
|
C++
|
.cpp
| 26
| 35.307692
| 81
| 0.734927
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,171
|
actiontablemodel.cpp
|
hluk_CopyQ/src/common/actiontablemodel.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "actiontablemodel.h"
#include "common/action.h"
#include "common/actionhandlerenums.h"
#include <QColor>
#include <algorithm>
namespace {
constexpr auto dateTimeFormat = "yyyy-MM-dd HH:mm:ss.zzz";
QString actionStateToString(ActionState state)
{
switch (state) {
case ActionState::Error: return "Error";
case ActionState::Finished: return "Finished";
case ActionState::Running: return "Running";
case ActionState::Starting: return "Starting";
}
return QString();
}
int actionStateOrder(ActionState state)
{
switch (state) {
case ActionState::Error: return 1;
case ActionState::Finished: return 0;
case ActionState::Running: return 2;
case ActionState::Starting: return 3;
}
return -1;
}
} // namespace
ActionTableModel::ActionTableModel(QObject *parent)
: QAbstractTableModel(parent)
{
}
void ActionTableModel::setMaxRowCount(uint rows)
{
if (m_maxRowCount == rows)
return;
m_maxRowCount = rows;
limitItems();
}
int ActionTableModel::actionAboutToStart(Action *action)
{
ActionData actionData;
actionData.id = m_actions.empty() ? 1 : m_actions[m_actions.size() - 1].id + 1;
actionData.name = action->name();
if ( actionData.name.isEmpty() )
actionData.name = action->commandLine();
actionData.finished = -1;
limitItems();
beginInsertRows(QModelIndex(), actionCount(), actionCount());
m_actions.push_back(actionData);
endInsertRows();
return actionData.id;
}
void ActionTableModel::actionStarted(Action *action)
{
const int row = rowFor(action);
actionData(row).started = QDateTime::currentDateTime();
for (const int column : { ActionHandlerColumn::started, ActionHandlerColumn::status }) {
const auto index = this->index(row, column);
emit dataChanged(index, index);
}
}
void ActionTableModel::actionFailed(Action *action, const QString &error)
{
const int row = rowFor(action);
actionData(row).error = error;
for (const int column : { ActionHandlerColumn::error, ActionHandlerColumn::status }) {
const auto index = this->index(row, column);
emit dataChanged(index, index);
}
}
void ActionTableModel::actionFinished(Action *action)
{
const int row = rowFor(action);
ActionData &data = actionData(row);
data.finished = data.started.msecsTo(QDateTime::currentDateTime());
for (const int column : { ActionHandlerColumn::finished, ActionHandlerColumn::status }) {
const auto index = this->index(row, column);
emit dataChanged(index, index);
}
}
void ActionTableModel::actionFinished(const QString &name)
{
ActionData actionData;
actionData.id = m_actions.empty() ? 1 : m_actions.end()->id + 1;
actionData.name = name;
actionData.started = QDateTime::currentDateTime();
actionData.finished = 0;
limitItems();
beginInsertRows(QModelIndex(), actionCount(), actionCount());
m_actions.push_back(actionData);
endInsertRows();
}
QVariant ActionTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
switch (section) {
case ActionHandlerColumn::id:
return "ID";
case ActionHandlerColumn::name:
return "Name";
case ActionHandlerColumn::status:
return "Status";
case ActionHandlerColumn::started:
return "Started";
case ActionHandlerColumn::finished:
return "Finished";
case ActionHandlerColumn::error:
return "Error";
}
}
return QVariant();
}
int ActionTableModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return actionCount();
}
int ActionTableModel::columnCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return ActionHandlerColumn::count;
}
QVariant ActionTableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (role == Qt::DisplayRole || role == Qt::EditRole) {
const int row = index.row();
const int column = index.column();
const ActionData &data = actionData(row);
switch (column) {
case ActionHandlerColumn::id:
return row;
case ActionHandlerColumn::name:
return data.name;
case ActionHandlerColumn::status:
return actionStateToString(actionState(data));
case ActionHandlerColumn::started:
return data.started.toString(dateTimeFormat);
case ActionHandlerColumn::finished:
return data.finished == -1 ? QString() : data.started.addMSecs(data.finished).toString(dateTimeFormat);
case ActionHandlerColumn::error:
return data.error;
}
} else if (role == Qt::ToolTipRole) {
const int row = index.row();
const int column = index.column();
const ActionData &data = actionData(row);
if (column == ActionHandlerColumn::name)
return data.name;
if (column == ActionHandlerColumn::error)
return data.error;
} else if (role == Qt::DecorationRole) {
const int column = index.column();
if (column == ActionHandlerColumn::status) {
const int row = index.row();
const ActionData &data = actionData(row);
switch (actionState(data)) {
case ActionState::Error: return QColor(0xe56950);
case ActionState::Running: return QColor(0xcce550);
case ActionState::Starting: return QColor(0xe5b350);
case ActionState::Finished: break;
}
}
} else if (role >= Qt::UserRole) {
if (role == ActionHandlerRole::sort) {
const int row = index.row();
const int column = index.column();
const ActionData &data = actionData(row);
switch (column) {
case ActionHandlerColumn::id:
return data.id;
case ActionHandlerColumn::name:
return data.name;
case ActionHandlerColumn::status:
return actionStateOrder(actionState(data));
case ActionHandlerColumn::started:
return data.started;
case ActionHandlerColumn::finished:
return data.finished;
case ActionHandlerColumn::error:
return data.error;
}
} else if (role == ActionHandlerRole::status) {
const int row = index.row();
const ActionData &data = actionData(row);
return static_cast<int>(actionState(data));
} else if (role == ActionHandlerRole::id) {
const int row = index.row();
const ActionData &data = actionData(row);
return data.id;
}
}
return QVariant();
}
ActionState ActionTableModel::actionState(const ActionTableModel::ActionData &data)
{
if ( !data.error.isEmpty() )
return ActionState::Error;
if ( data.finished != -1 )
return ActionState::Finished;
if ( data.started.isValid() )
return ActionState::Running;
return ActionState::Starting;
}
int ActionTableModel::rowFor(const Action *action) const
{
const auto found = std::lower_bound(
std::begin(m_actions), std::end(m_actions), action->id(),
[](const ActionData &data, int id) {
return data.id < id;
});
const auto row = std::distance(std::begin(m_actions), found);
return static_cast<int>(row);
}
void ActionTableModel::limitItems()
{
if (m_actions.size() < m_maxRowCount * 4 / 3)
return;
while (m_actions.size() >= m_maxRowCount) {
const auto found = std::find_if(
std::begin(m_actions), std::end(m_actions),
[](const ActionData &data) {
const auto state = actionState(data);
return state == ActionState::Finished || state == ActionState::Error;
});
if ( found == std::end(m_actions) )
break;
const auto row = static_cast<int>( std::distance(std::begin(m_actions), found) );
beginRemoveRows(QModelIndex(), row, row);
m_actions.erase(found);
endRemoveRows();
}
}
| 8,457
|
C++
|
.cpp
| 238
| 28.344538
| 115
| 0.639452
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,172
|
messagehandlerforqt.cpp
|
hluk_CopyQ/src/common/messagehandlerforqt.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "messagehandlerforqt.h"
#include "common/log.h"
#include <QString>
#include <QtGlobal>
#include <exception>
namespace {
class ExceptionQtFatal final : public std::exception {
public:
explicit ExceptionQtFatal(const QByteArray &message)
: m_message(message)
{
}
const char* what() const noexcept override
{
return m_message.constData();
}
private:
QByteArray m_message;
};
void messageHandlerForQt5(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QString message = msg;
if (context.file && context.file[0]) {
message.append(
QStringLiteral(" (%1:%2, %3)")
.arg(context.file, QString::number(context.line), context.function));
}
const QString format = QStringLiteral("[%1] %3: %2");
const QLatin1String category(context.category);
switch (type) {
case QtDebugMsg:
log( format.arg(category, message, QStringLiteral("QtDebug")), LogDebug);
break;
case QtInfoMsg:
log( format.arg(category, message, QStringLiteral("QtInfo")), LogDebug);
break;
case QtWarningMsg:
log( format.arg(category, message, QStringLiteral("QtWarning")), LogWarning);
break;
case QtCriticalMsg:
log( format.arg(category, message, QStringLiteral("QtCritical")), LogError);
break;
case QtFatalMsg:
log( format.arg(category, message, QStringLiteral("QtFatal")), LogError);
throw ExceptionQtFatal( message.toUtf8() );
}
}
} // namespace
void installMessageHandlerForQt()
{
qInstallMessageHandler(messageHandlerForQt5);
}
| 1,688
|
C++
|
.cpp
| 53
| 26.622642
| 96
| 0.685151
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,173
|
shortcuts.cpp
|
hluk_CopyQ/src/common/shortcuts.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "shortcuts.h"
#include <QKeySequence>
#include <QObject>
#include <QString>
namespace {
int indexOfKeyHint(const QString &name)
{
bool amp = false;
int i = 0;
for (const auto &c : name) {
if (c == '&')
amp = !amp;
else if (amp)
return i - 1;
++i;
}
return -1;
}
} // namespace
QString shortcutToRemove()
{
#ifdef Q_OS_MAC
return QObject::tr("Backspace", "Key to remove item or MIME on OS X");
#else
return QObject::tr("Delete", "Key to remove item or MIME");
#endif
}
QString portableShortcutText(const QKeySequence &shortcut)
{
// WORKAROUND: Qt has convert some keys to upper case which
// breaks some shortcuts on some keyboard layouts.
return shortcut.toString(QKeySequence::PortableText).toLower();
}
QString toPortableShortcutText(const QString &shortcutNativeText)
{
return portableShortcutText(
QKeySequence(shortcutNativeText, QKeySequence::NativeText));
}
bool hasKeyHint(const QString &name)
{
return indexOfKeyHint(name) != -1;
}
QString &removeKeyHint(QString *name)
{
const int i = indexOfKeyHint(*name);
return i == -1 ? *name : name->remove(i, 1);
}
| 1,264
|
C++
|
.cpp
| 48
| 22.583333
| 76
| 0.677741
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,174
|
scriptablesettings.cpp
|
hluk_CopyQ/src/scriptable/scriptablesettings.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "scriptablesettings.h"
ScriptableSettings::ScriptableSettings()
: QObject()
, m_settings()
{
}
ScriptableSettings::ScriptableSettings(const QString &fileName)
: QObject()
, m_settings(fileName, QSettings::IniFormat)
{
}
| 293
|
C++
|
.cpp
| 12
| 21.833333
| 63
| 0.751799
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,175
|
scriptabledir.cpp
|
hluk_CopyQ/src/scriptable/scriptabledir.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "scriptabledir.h"
#include <QJSEngine>
ScriptableDir::ScriptableDir(const QString &path)
: m_path(path)
{
}
ScriptableDir::~ScriptableDir()
{
delete m_self;
}
QJSValue ScriptableDir::absoluteFilePath(const QJSValue &fileName)
{
return self()->absoluteFilePath(fileName.toString());
}
QJSValue ScriptableDir::absolutePath()
{
return self()->absolutePath();
}
QJSValue ScriptableDir::canonicalPath()
{
return self()->canonicalPath();
}
bool ScriptableDir::cd(const QJSValue &dirName)
{
return self()->cd(dirName.toString());
}
bool ScriptableDir::cdUp()
{
return self()->cdUp();
}
uint ScriptableDir::count()
{
return self()->count();
}
QJSValue ScriptableDir::dirName()
{
return self()->dirName();
}
QStringList ScriptableDir::entryList(const QStringList &nameFilters)
{
return self()->entryList(nameFilters);
}
bool ScriptableDir::exists(const QJSValue &name)
{
return self()->exists(name.toString());
}
bool ScriptableDir::exists()
{
return self()->exists();
}
QJSValue ScriptableDir::filePath(const QJSValue &fileName)
{
return self()->filePath(fileName.toString());
}
bool ScriptableDir::isAbsolute()
{
return self()->isAbsolute();
}
bool ScriptableDir::isReadable()
{
return self()->isReadable();
}
bool ScriptableDir::isRelative()
{
return self()->isRelative();
}
bool ScriptableDir::isRoot()
{
return self()->isRoot();
}
bool ScriptableDir::makeAbsolute()
{
return self()->makeAbsolute();
}
bool ScriptableDir::mkdir(const QJSValue &dirName)
{
return self()->mkdir(dirName.toString());
}
bool ScriptableDir::mkpath(const QJSValue &dirPath)
{
return self()->mkpath(dirPath.toString());
}
QStringList ScriptableDir::nameFilters()
{
return self()->nameFilters();
}
QJSValue ScriptableDir::path()
{
return self()->path();
}
void ScriptableDir::refresh()
{
self()->refresh();
}
QJSValue ScriptableDir::relativeFilePath(const QJSValue &fileName)
{
return self()->relativeFilePath(fileName.toString());
}
bool ScriptableDir::remove(const QJSValue &fileName)
{
return self()->remove(fileName.toString());
}
bool ScriptableDir::rename(const QJSValue &oldName, const QJSValue &newName)
{
return self()->rename(oldName.toString(), newName.toString());
}
bool ScriptableDir::rmdir(const QJSValue &dirName)
{
return self()->rmdir(dirName.toString());
}
bool ScriptableDir::rmpath(const QJSValue &dirPath)
{
return self()->rmpath(dirPath.toString());
}
void ScriptableDir::setNameFilters(const QStringList &nameFilters)
{
self()->setNameFilters(nameFilters);
}
void ScriptableDir::setPath(const QJSValue &path)
{
self()->setPath(path.toString());
}
void ScriptableDir::addSearchPath(const QJSValue &prefix, const QJSValue &path)
{
QDir::addSearchPath(prefix.toString(), path.toString());
}
QJSValue ScriptableDir::cleanPath(const QJSValue &path)
{
return QDir::cleanPath(path.toString());
}
QJSValue ScriptableDir::currentPath()
{
return QDir::currentPath();
}
QJSValue ScriptableDir::fromNativeSeparators(const QJSValue &pathName)
{
return QDir::fromNativeSeparators(pathName.toString());
}
QJSValue ScriptableDir::home()
{
return newDir(QDir::home());
}
QJSValue ScriptableDir::homePath()
{
return QDir::homePath();
}
bool ScriptableDir::isAbsolutePath(const QJSValue &path)
{
return QDir::isAbsolutePath(path.toString());
}
bool ScriptableDir::isRelativePath(const QJSValue &path)
{
return QDir::isRelativePath(path.toString());
}
bool ScriptableDir::match(const QJSValue &filter, const QJSValue &fileName)
{
return QDir::match(filter.toString(), fileName.toString());
}
bool ScriptableDir::match(const QStringList &filters, const QJSValue &fileName)
{
return QDir::match(filters, fileName.toString());
}
QJSValue ScriptableDir::root()
{
return newDir(QDir::root());
}
QJSValue ScriptableDir::rootPath()
{
return QDir::rootPath();
}
QStringList ScriptableDir::searchPaths(const QJSValue &prefix)
{
return QDir::searchPaths(prefix.toString());
}
QJSValue ScriptableDir::separator()
{
return QString(QDir::separator());
}
bool ScriptableDir::setCurrent(const QJSValue &path)
{
return QDir::setCurrent(path.toString());
}
void ScriptableDir::setSearchPaths(const QJSValue &prefix, const QStringList &searchPaths)
{
QDir::setSearchPaths(prefix.toString(), searchPaths);
}
QJSValue ScriptableDir::temp()
{
return newDir(QDir::temp());
}
QJSValue ScriptableDir::tempPath()
{
return QDir::tempPath();
}
QJSValue ScriptableDir::toNativeSeparators(const QJSValue &pathName)
{
return QDir::toNativeSeparators(pathName.toString());
}
QDir *ScriptableDir::self()
{
if (!m_self)
m_self = new QDir(m_path);
return m_self;
}
QJSEngine *ScriptableDir::engine() const
{
return qjsEngine(this);
}
QJSValue ScriptableDir::newDir(const QDir &dir) const
{
return engine()->newQObject( new ScriptableDir(dir.absolutePath()) );
}
| 5,030
|
C++
|
.cpp
| 213
| 21.328638
| 90
| 0.750787
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,176
|
commandhelp.cpp
|
hluk_CopyQ/src/scriptable/commandhelp.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "commandhelp.h"
#include "common/common.h"
#include "scriptable/scriptable.h"
constexpr int helpTextColumn = 23;
CommandHelp::CommandHelp()
: cmd()
, desc()
, args()
{
}
CommandHelp::CommandHelp(const char *command, const QString &description)
: cmd(command)
, desc(description)
, args()
{
}
CommandHelp &CommandHelp::addArg(const QString &arg)
{
args.append(' ');
args.append(arg);
return *this;
}
QString CommandHelp::toString() const
{
if (cmd.isNull())
return "\n";
const auto cmdArgs = cmd + args;
if ( cmdArgs.size() > helpTextColumn - 2 || desc.contains('\n') ) {
const auto indent = QString(' ').repeated(6);
return QString::fromLatin1(" %1\n%2").arg(cmdArgs, indent)
+ QString(desc)
.replace('\n', "\n" + indent) + "\n";
}
return QString::fromLatin1(" %1 ").arg(cmdArgs, -helpTextColumn)
+ QString(desc)
.replace('\n', "\n" + QString(' ')
.repeated(6 + helpTextColumn)) + "\n";
}
QList<CommandHelp> commandHelp()
{
return QList<CommandHelp>()
<< CommandHelp("show",
Scriptable::tr("Show main window and optionally open tab with given name."))
.addArg("[" + Scriptable::tr("NAME") + "]")
<< CommandHelp("hide",
Scriptable::tr("Hide main window."))
<< CommandHelp("toggle",
Scriptable::tr("Show or hide main window."))
<< CommandHelp("menu",
Scriptable::tr("Open context menu."))
<< CommandHelp("exit",
Scriptable::tr("Exit server."))
<< CommandHelp("disable, enable",
Scriptable::tr("Disable or enable clipboard content storing."))
<< CommandHelp()
<< CommandHelp("clipboard",
Scriptable::tr("Print clipboard content."))
.addArg("[" + Scriptable::tr("MIME") + "]")
#ifdef HAS_MOUSE_SELECTIONS
<< CommandHelp("selection",
Scriptable::tr("Print X11 selection content."))
.addArg("[" + Scriptable::tr("MIME") + "]")
#endif
<< CommandHelp("paste",
Scriptable::tr("Paste clipboard to current window\n"
"(may not work with some applications)."))
<< CommandHelp("copy",
Scriptable::tr("Copy clipboard from current window\n"
"(may not work with some applications)."))
<< CommandHelp("copy", Scriptable::tr("Set clipboard text."))
.addArg(Scriptable::tr("TEXT"))
<< CommandHelp("copy", Scriptable::tr("Set clipboard content."))
.addArg(Scriptable::tr("MIME"))
.addArg(Scriptable::tr("DATA"))
.addArg("[" + Scriptable::tr("MIME") + " " + Scriptable::tr("DATA") + "]...")
<< CommandHelp()
<< CommandHelp("count",
Scriptable::tr("Print amount of items in current tab."))
<< CommandHelp("select",
Scriptable::tr("Copy item in the row to clipboard."))
.addArg("[" + Scriptable::tr("ROW") + "=0]")
<< CommandHelp("next",
Scriptable::tr("Copy next item from current tab to clipboard."))
<< CommandHelp("previous",
Scriptable::tr("Copy previous item from current tab to clipboard."))
<< CommandHelp("add",
Scriptable::tr("Add text into clipboard."))
.addArg(Scriptable::tr("TEXT") + "...")
<< CommandHelp("insert",
Scriptable::tr("Insert text into given row."))
.addArg(Scriptable::tr("ROW"))
.addArg(Scriptable::tr("TEXT"))
<< CommandHelp("remove",
Scriptable::tr("Remove items in given rows."))
.addArg("[" + Scriptable::tr("ROWS") + "=0...]")
<< CommandHelp("edit",
Scriptable::tr("Edit items or edit new one.\n"
"Value -1 is for current text in clipboard."))
.addArg("[" + Scriptable::tr("ROW") + "=-1...]")
<< CommandHelp()
<< CommandHelp("separator",
Scriptable::tr("Set separator for items on output."))
.addArg(Scriptable::tr("SEPARATOR"))
<< CommandHelp("read",
Scriptable::tr("Print raw data of clipboard or item in row."))
.addArg("[" + Scriptable::tr("MIME") + "|" + Scriptable::tr("ROW") + "]...")
<< CommandHelp("write", Scriptable::tr("Write raw data to given row."))
.addArg("[" + Scriptable::tr("ROW") + "=0]")
.addArg(Scriptable::tr("MIME"))
.addArg(Scriptable::tr("DATA"))
.addArg("[" + Scriptable::tr("MIME") + " " + Scriptable::tr("DATA") + "]...")
<< CommandHelp()
<< CommandHelp("action",
Scriptable::tr("Show action dialog."))
.addArg("[" + Scriptable::tr("ROWS") + "=0...]")
<< CommandHelp("action",
Scriptable::tr("Run PROGRAM on item text in the rows.\n"
"Use %1 in PROGRAM to pass text as argument."))
.addArg("[" + Scriptable::tr("ROWS") + "=0...]")
.addArg("[" + Scriptable::tr("PROGRAM") + " [" + Scriptable::tr("SEPARATOR") + "=\\n]]")
<< CommandHelp("popup",
Scriptable::tr("Show tray popup message for TIME milliseconds."))
.addArg(Scriptable::tr("TITLE"))
.addArg(Scriptable::tr("MESSAGE"))
.addArg("[" + Scriptable::tr("TIME") + "=8000]")
<< CommandHelp()
<< CommandHelp("tab",
Scriptable::tr("List available tab names."))
<< CommandHelp("tab",
Scriptable::tr("Run command on tab with given name.\n"
"Tab is created if it doesn't exist.\n"
"Default is the first tab."))
.addArg(Scriptable::tr("NAME"))
.addArg("[" + Scriptable::tr("COMMAND") + "]")
<< CommandHelp("removetab",
Scriptable::tr("Remove tab."))
.addArg(Scriptable::tr("NAME"))
<< CommandHelp("renametab",
Scriptable::tr("Rename tab."))
.addArg(Scriptable::tr("NAME"))
.addArg(Scriptable::tr("NEW_NAME"))
<< CommandHelp()
<< CommandHelp("exporttab",
Scriptable::tr("Export items to file."))
.addArg(Scriptable::tr("FILE_NAME"))
<< CommandHelp("importtab",
Scriptable::tr("Import items from file."))
.addArg(Scriptable::tr("FILE_NAME"))
<< CommandHelp()
<< CommandHelp("config",
Scriptable::tr("List all options."))
<< CommandHelp("config",
Scriptable::tr("Get option value."))
.addArg(Scriptable::tr("OPTION"))
<< CommandHelp("config",
Scriptable::tr("Set option value."))
.addArg(Scriptable::tr("OPTION"))
.addArg(Scriptable::tr("VALUE"))
<< CommandHelp()
<< CommandHelp("eval, -e", Scriptable::tr("Evaluate script."))
.addArg("[" + Scriptable::tr("SCRIPT") + "]")
.addArg("[" + Scriptable::tr("ARGUMENTS") + "]...")
<< CommandHelp("session, -s, --session",
Scriptable::tr("Starts or connects to application instance with given session name."))
.addArg(Scriptable::tr("SESSION"))
<< CommandHelp("help, -h, --help",
Scriptable::tr("Print help for COMMAND or all commands."))
.addArg("[" + Scriptable::tr("COMMAND") + "]...")
<< CommandHelp("version, -v, --version",
Scriptable::tr("Print version of program and libraries."))
#ifdef HAS_TESTS
<< CommandHelp("tests, --tests",
Scriptable::tr("Run application tests (append --help argument for more info)."))
#endif
<< CommandHelp("--start-server",
Scriptable::tr("Start server in background before running a command."))
.addArg("[" + Scriptable::tr("COMMAND") + "]")
;
}
| 9,018
|
C++
|
.cpp
| 180
| 34.377778
| 113
| 0.482782
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,177
|
scriptabletemporaryfile.cpp
|
hluk_CopyQ/src/scriptable/scriptabletemporaryfile.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "scriptabletemporaryfile.h"
#include <QTemporaryFile>
Q_DECLARE_METATYPE(QTemporaryFile*)
ScriptableTemporaryFile::ScriptableTemporaryFile(const QString &path)
: ScriptableFile(path)
{
}
bool ScriptableTemporaryFile::autoRemove()
{
return tmpFile()->autoRemove();
}
QString ScriptableTemporaryFile::fileTemplate()
{
return tmpFile()->fileTemplate();
}
void ScriptableTemporaryFile::setAutoRemove(bool autoRemove)
{
tmpFile()->setAutoRemove(autoRemove);
}
void ScriptableTemporaryFile::setFileTemplate(const QJSValue &name)
{
tmpFile()->setFileTemplate(name.toString());
}
QFile *ScriptableTemporaryFile::self()
{
return tmpFile();
}
QTemporaryFile *ScriptableTemporaryFile::tmpFile()
{
if (m_self)
return m_self;
m_self = new QTemporaryFile(this);
setFile(m_self);
return m_self;
}
| 895
|
C++
|
.cpp
| 36
| 22.222222
| 69
| 0.772406
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,178
|
scriptableitemselection.cpp
|
hluk_CopyQ/src/scriptable/scriptableitemselection.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "scriptableitemselection.h"
#include "scriptableproxy.h"
#include "scriptable/scriptablebytearray.h"
#include "scriptable/scriptvaluefactory.h"
#include <QJSEngine>
ScriptableItemSelection::ScriptableItemSelection(const QString &tabName)
: m_tabName(tabName)
{
}
ScriptableItemSelection::~ScriptableItemSelection()
{
if (m_proxy)
m_proxy->destroySelection(m_id);
}
QJSValue ScriptableItemSelection::length()
{
return m_proxy->selectionGetSize(m_id);
}
QJSValue ScriptableItemSelection::tab()
{
return m_proxy->selectionGetTabName(m_id);
}
QJSValue ScriptableItemSelection::valueOf()
{
return toString();
}
QJSValue ScriptableItemSelection::str()
{
return toString();
}
QString ScriptableItemSelection::toString()
{
const auto rows = m_proxy->selectionGetRows(m_id);
const auto tabName = m_proxy->selectionGetTabName(m_id);
QString rowString;
auto it1 = rows.constBegin();
while (it1 != rows.constEnd()) {
auto it2 = std::adjacent_find(it1, rows.constEnd(), [](int lhs, int rhs) {
return lhs + 1 != rhs;
});
if (it2 == rows.constEnd())
--it2;
if (it1 == it2)
rowString.append(QStringLiteral("%1,").arg(*it1));
else if (it1 + 1 == it2)
rowString.append(QStringLiteral("%1,%2,").arg(*it1).arg(*it2));
else
rowString.append(QStringLiteral("%1..%2,").arg(*it1).arg(*it2));
it1 = it2 + 1;
}
rowString.chop(1);
return QStringLiteral("ItemSelection(tab=\"%1\", rows=[%2])")
.arg(tabName, rowString);
}
QJSValue ScriptableItemSelection::selectAll()
{
m_proxy->selectionSelectAll(m_id);
return m_self;
}
QJSValue ScriptableItemSelection::select(const QJSValue &re, const QString &mimeFormat)
{
const QVariant regexp = re.isRegExp()
? fromScriptValue<QRegularExpression>(re, qjsEngine(this))
: QVariant();
m_proxy->selectionSelect(m_id, regexp, mimeFormat);
return m_self;
}
QJSValue ScriptableItemSelection::selectRemovable()
{
m_proxy->selectionSelectRemovable(m_id);
return m_self;
}
QJSValue ScriptableItemSelection::invert()
{
m_proxy->selectionInvert(m_id);
return m_self;
}
QJSValue ScriptableItemSelection::deselectIndexes(const QJSValue &indexes)
{
const auto indexes2 = fromScriptValue<QVector<int>>(indexes, qjsEngine(this));
m_proxy->selectionDeselectIndexes(m_id, indexes2);
return m_self;
}
QJSValue ScriptableItemSelection::deselectSelection(const QJSValue &selection)
{
const auto other = qobject_cast<ScriptableItemSelection*>(selection.toQObject());
m_proxy->selectionDeselectSelection(m_id, other->m_id);
return m_self;
}
QJSValue ScriptableItemSelection::current()
{
m_proxy->selectionGetCurrent(m_id);
return m_self;
}
QJSValue ScriptableItemSelection::removeAll()
{
m_proxy->selectionRemoveAll(m_id);
return m_self;
}
QJSValue ScriptableItemSelection::copy()
{
const int newId = m_proxy->selectionCopy(m_id);
auto cloneQObj = new ScriptableItemSelection(m_tabName);
const QJSValue clone = qjsEngine(this)->newQObject(cloneQObj);
cloneQObj->m_proxy = m_proxy;
cloneQObj->m_id = newId;
cloneQObj->m_self = clone;
return clone;
}
QJSValue ScriptableItemSelection::rows()
{
const auto rows = m_proxy->selectionGetRows(m_id);
QJSValue array = qjsEngine(this)->newArray(rows.size());
for ( int i = 0; i < rows.size(); ++i )
array.setProperty( static_cast<quint32>(i), QJSValue(rows[i]) );
return array;
}
QJSValue ScriptableItemSelection::itemAtIndex(int index)
{
const auto item = m_proxy->selectionGetItemIndex(m_id, index);
return toScriptValue(item, qjsEngine(this));
}
QJSValue ScriptableItemSelection::setItemAtIndex(int index, const QJSValue &item)
{
const QVariantMap data = fromScriptValue<QVariantMap>(item, qjsEngine(this));
m_proxy->selectionSetItemIndex(m_id, index, data);
return m_self;
}
QJSValue ScriptableItemSelection::items()
{
const QVariantList dataList = m_proxy->selectionGetItemsData(m_id);
return toScriptValue(dataList, qjsEngine(this));
}
QJSValue ScriptableItemSelection::setItems(const QJSValue &items)
{
const QVariantList dataList = fromScriptValue<QVariantList>(items, qjsEngine(this));
m_proxy->selectionSetItemsData(m_id, dataList);
return m_self;
}
QJSValue ScriptableItemSelection::itemsFormat(const QJSValue &format)
{
const QVariantList dataList = m_proxy->selectionGetItemsFormat(m_id, ::toString(format));
return toScriptValue(dataList, qjsEngine(this));
}
QJSValue ScriptableItemSelection::setItemsFormat(const QJSValue &format, const QJSValue &value)
{
const QVariant variant = value.isUndefined() ? QVariant() : QVariant(toByteArray(value));
m_proxy->selectionSetItemsFormat(m_id, ::toString(format), variant);
return m_self;
}
QJSValue ScriptableItemSelection::move(int row)
{
m_proxy->selectionMove(m_id, row);
return m_self;
}
QJSValue ScriptableItemSelection::sort(QJSValue compareFn)
{
const int size = m_proxy->selectionGetSize(m_id);
QVector<int> indexes;
indexes.reserve(size);
for (int i = 0; i < size; ++i)
indexes.append(i);
std::sort( indexes.begin(), indexes.end(), [&](int lhs, int rhs) {
return compareFn.call({lhs, rhs}).toBool();
} );
m_proxy->selectionSort(m_id, indexes);
return m_self;
}
void ScriptableItemSelection::init(const QJSValue &self, ScriptableProxy *proxy, const QString ¤tTabName)
{
m_self = self;
m_proxy = proxy;
connect(m_proxy, &QObject::destroyed, this, [this](){ m_proxy = nullptr; });
if ( m_tabName.isEmpty() )
m_tabName = currentTabName;
m_id = m_proxy->createSelection(m_tabName);
}
| 5,849
|
C++
|
.cpp
| 178
| 28.97191
| 111
| 0.717758
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,179
|
scriptablefile.cpp
|
hluk_CopyQ/src/scriptable/scriptablefile.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "scriptablefile.h"
#include "scriptable/scriptablebytearray.h"
#include <QDir>
#include <QFile>
#include <QJSEngine>
#include <QJSValue>
Q_DECLARE_METATYPE(QByteArray*)
Q_DECLARE_METATYPE(QFile*)
ScriptableFile::ScriptableFile(const QString &path)
: m_path(path)
{
}
bool ScriptableFile::open()
{
return self()->open(QIODevice::ReadWrite);
}
bool ScriptableFile::openReadOnly()
{
return self()->open(QIODevice::ReadOnly);
}
bool ScriptableFile::openWriteOnly()
{
return self()->open(QIODevice::WriteOnly);
}
bool ScriptableFile::openAppend()
{
return self()->open(QIODevice::Append);
}
void ScriptableFile::close()
{
self()->close();
}
QJSValue ScriptableFile::read(qint64 maxSize)
{
return newByteArray(self()->read(maxSize));
}
QJSValue ScriptableFile::readLine(qint64 maxSize)
{
return newByteArray(self()->readLine(maxSize));
}
QJSValue ScriptableFile::readAll()
{
return newByteArray(self()->readAll());
}
qint64 ScriptableFile::write(const QJSValue &value)
{
return self()->write(toByteArray(value));
}
bool ScriptableFile::atEnd()
{
return self()->atEnd();
}
qint64 ScriptableFile::bytesAvailable()
{
return self()->bytesAvailable();
}
qint64 ScriptableFile::bytesToWrite()
{
return self()->bytesToWrite();
}
bool ScriptableFile::canReadLine()
{
return self()->canReadLine();
}
QJSValue ScriptableFile::errorString()
{
return self()->errorString();
}
bool ScriptableFile::isOpen()
{
return self()->isOpen();
}
bool ScriptableFile::isReadable()
{
return self()->isReadable();
}
bool ScriptableFile::isWritable()
{
return self()->isWritable();
}
QJSValue ScriptableFile::peek(qint64 maxSize)
{
return newByteArray(self()->peek(maxSize));
}
qint64 ScriptableFile::pos()
{
return self()->pos();
}
bool ScriptableFile::reset()
{
return self()->reset();
}
bool ScriptableFile::seek(qint64 pos)
{
return self()->seek(pos);
}
void ScriptableFile::setTextModeEnabled(bool enabled)
{
self()->setTextModeEnabled(enabled);
}
qint64 ScriptableFile::size()
{
return self()->size();
}
QJSValue ScriptableFile::fileName()
{
return self()->fileName();
}
bool ScriptableFile::exists()
{
return self()->exists();
}
bool ScriptableFile::flush()
{
return self()->flush();
}
bool ScriptableFile::remove()
{
return self()->remove();
}
QFile *ScriptableFile::self()
{
if (m_self)
return m_self;
setFile( new QFile(this) );
return m_self;
}
void ScriptableFile::setFile(QFile *file)
{
Q_ASSERT(m_self == nullptr);
m_self = file;
if ( !m_path.isNull() ) {
m_self->setFileName(m_path);
}
}
QJSEngine *ScriptableFile::engine() const
{
return qjsEngine(this);
}
QJSValue ScriptableFile::newByteArray(const QByteArray &bytes)
{
return engine()->newQObject( new ScriptableByteArray(bytes) );
}
| 2,926
|
C++
|
.cpp
| 144
| 17.916667
| 66
| 0.723032
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,180
|
scriptable.cpp
|
hluk_CopyQ/src/scriptable/scriptable.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "scriptable.h"
#include "app/clipboardmonitor.h"
#include "common/action.h"
#include "common/command.h"
#include "common/commandstatus.h"
#include "common/commandstore.h"
#include "common/common.h"
#include "common/log.h"
#include "common/sleeptimer.h"
#include "common/version.h"
#include "common/textdata.h"
#include "gui/clipboardspy.h"
#include "gui/icons.h"
#include "item/itemfactory.h"
#include "item/serialize.h"
#include "platform/platformclipboard.h"
#include "platform/platformwindow.h"
#include "scriptable/commandhelp.h"
#include "scriptable/scriptablebytearray.h"
#include "scriptable/scriptabledir.h"
#include "scriptable/scriptablefile.h"
#include "scriptable/scriptableitemselection.h"
#include "scriptable/scriptableproxy.h"
#include "scriptable/scriptablesettings.h"
#include "scriptable/scriptabletemporaryfile.h"
#include "scriptable/scriptoverrides.h"
#include "scriptable/scriptvaluefactory.h"
#include <QApplication>
#include <QCryptographicHash>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QMap>
#include <QMimeData>
#include <QMetaProperty>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QPoint>
#include <QRegularExpression>
#include <QJSEngine>
#include <QJSValueIterator>
#include <QSettings>
#include <QSysInfo>
#include <QUrl>
#include <QVector>
#include <QThread>
#include <QTimer>
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
# include <QTextCodec>
#else
# include <QStringDecoder>
# include <QStringEncoder>
#endif
#ifdef WITH_NATIVE_NOTIFICATIONS
# include <knotifications_version.h>
#endif
Q_DECLARE_METATYPE(QByteArray*)
Q_DECLARE_METATYPE(QFile*)
namespace {
const QLatin1String mimeIgnore(COPYQ_MIME_PREFIX "ignore");
class PerformanceLogger {
public:
explicit PerformanceLogger(const QString &label)
: m_label(label)
{
m_timer.start();
}
~PerformanceLogger()
{
const qint64 ms = m_timer.elapsed();
if (ms >= 5000)
log(ms, LogWarning);
else if (ms >= 500)
log(ms, LogNote);
else if (ms >= 150)
log(ms, LogDebug);
else
log(ms, LogTrace);
}
private:
void log(qint64 ms, LogLevel level) const
{
if ( !hasLogLevel(level) )
return;
::log( QStringLiteral("%1: %2")
.arg(m_label, "Finished in %1 ms")
.arg(ms), level );
}
QString m_label;
QElapsedTimer m_timer;
};
QString helpHead()
{
return Scriptable::tr("Usage: copyq [%1]").arg(Scriptable::tr("COMMAND")) + "\n\n"
+ Scriptable::tr("Starts server if no command is specified.") + "\n"
+ Scriptable::tr(" COMMANDs:");
}
QString helpTail()
{
return Scriptable::tr("NOTES:") + "\n"
+ Scriptable::tr(" - Use dash argument (-) to read data from standard input.") + "\n"
+ Scriptable::tr(" - Use double-dash argument (--) to read all following arguments without\n"
" expanding escape sequences (i.e. \\n, \\t and others).") + "\n"
+ Scriptable::tr(" - Use ? for MIME to print available MIME types (default is \"text/plain\").");
}
QString argumentError()
{
return Scriptable::tr("Invalid number of arguments!");
}
QString exceptionBacktrace(const QJSValue &exception, const QStringList &stack = {})
{
const auto backtraceValue = exception.property("stack");
auto backtrace = backtraceValue.isUndefined() ? QStringList() : backtraceValue.toString().split("\n");
for (int i = backtrace.size() - 1; i >= 0; --i) {
if ( backtrace[i] == QLatin1String("@:1") )
backtrace.removeAt(i);
}
for (const auto &frame : stack)
backtrace.append(frame);
if ( backtrace.isEmpty() )
return {};
return QStringLiteral("\n\n--- backtrace ---\n%1\n--- end backtrace ---")
.arg(backtrace.join(QLatin1String("\n")));
}
QJSValue evaluateStrict(QJSEngine *engine, const QString &script)
{
const auto v = engine->evaluate(script);
if ( v.isError() ) {
const auto scriptText = QStringLiteral("--- SCRIPT BEGIN ---\n%1\n--- SCRIPT END ---").arg(script);
log( QStringLiteral("Exception during evaluate: %1%2\n\n%3")
.arg(v.toString(), exceptionBacktrace(v), scriptText), LogError );
}
return v;
}
QJSValue addScriptableClass(const QMetaObject *metaObject, const QString &name, QJSEngine *engine)
{
auto cls = engine->newQMetaObject(metaObject);
auto fn = engine->globalObject().property(name);
Q_ASSERT(fn.isCallable());
fn.setProperty(QStringLiteral("prototype"), cls);
return cls;
}
QByteArray serializeScriptValue(const QJSValue &value, Scriptable *scriptable)
{
QByteArray data;
const QByteArray *bytes = getByteArray(value);
if (bytes != nullptr) {
data = *bytes;
} else if ( value.isArray() || value.toVariant().type() == QVariant::StringList ) {
const quint32 len = value.property("length").toUInt();
for (quint32 i = 0; i < len; ++i)
data += serializeScriptValue(value.property(i), scriptable);
} else if ( !value.isUndefined() ) {
data = value.toString().toUtf8() + '\n';
}
return data;
}
QString parseCommandLineArgument(const QString &arg)
{
QString result;
bool escape = false;
for (const auto &c : arg) {
if (escape) {
escape = false;
if (c == 'n')
result.append('\n');
else if (c == 't')
result.append('\t');
else if (c == '\\')
result.append('\\');
else
result.append(c);
} else if (c == '\\') {
escape = true;
} else {
result.append(c);
}
}
return result;
}
bool isInternalDataFormat(const QString &format)
{
return format == mimeWindowTitle
|| format == mimeItems
|| format == mimeOwner
|| format == mimeClipboardMode
|| format == mimeCurrentTab
|| format == mimeSelectedItems
|| format == mimeCurrentItem
|| format == mimeShortcut
|| format == mimeOutputTab
|| format == mimeSecret;
}
QVariantMap copyWithoutInternalData(const QVariantMap &data) {
QVariantMap newData;
for (auto it = data.constBegin(); it != data.constEnd(); ++it) {
const auto &format = it.key();
if ( !isInternalDataFormat(format) )
newData.insert(format, it.value());
}
return newData;
}
QJSValue checksumForArgument(Scriptable *scriptable, QCryptographicHash::Algorithm method)
{
const auto data = scriptable->makeByteArray(scriptable->argument(0));
const QByteArray hash = QCryptographicHash::hash(data, method).toHex();
return QLatin1String(hash);
}
QString scriptToLabel(const QString &script)
{
constexpr auto maxScriptSize = 30;
if (maxScriptSize < script.size())
return script.left(maxScriptSize).simplified() + QLatin1String("...");
return script;
}
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
QTextCodec *codecFromNameOrThrow(const QJSValue &codecName, Scriptable *scriptable)
{
const auto codec = QTextCodec::codecForName( scriptable->makeByteArray(codecName) );
if (!codec) {
QString codecs;
for (const auto &availableCodecName : QTextCodec::availableCodecs())
codecs.append( "\n" + QLatin1String(availableCodecName) );
scriptable->throwError("Available codecs are:" + codecs);
}
return codec;
}
QJSValue toUnicode(const QByteArray &bytes, const QJSValue &codecName, Scriptable *scriptable)
{
const auto codec = codecFromNameOrThrow(codecName, scriptable);
if (!codec)
return QJSValue();
return codec->toUnicode(bytes);
}
QJSValue toUnicode(const QByteArray &bytes, Scriptable *scriptable)
{
const auto codec = QTextCodec::codecForUtfText(bytes, nullptr);
if (!codec)
return scriptable->throwError("Failed to detect encoding");
return codec->toUnicode(bytes);
}
QJSValue fromUnicode(const QString &text, const QJSValue &codecName, Scriptable *scriptable)
{
const auto codec = codecFromNameOrThrow(codecName, scriptable);
if (!codec)
return QJSValue();
return scriptable->newByteArray( codec->fromUnicode(text) );
}
#else
std::optional<QStringConverter::Encoding> encodingFromNameOrThrow(const QJSValue &codecName, Scriptable *scriptable)
{
const auto encoding = QStringConverter::encodingForName( scriptable->makeByteArray(codecName) );
if (!encoding)
scriptable->throwError("Unknown encoding name");
return encoding;
}
QJSValue toUnicode(const QByteArray &bytes, const QJSValue &codecName, Scriptable *scriptable)
{
const auto encoding = encodingFromNameOrThrow(codecName, scriptable);
if (!encoding)
return QJSValue();
const QString text = QStringDecoder(*encoding).decode(bytes);
return text;
}
QJSValue toUnicode(const QByteArray &bytes, Scriptable *scriptable)
{
const auto encoding = QStringConverter::encodingForData(bytes);
if (!encoding)
return scriptable->throwError("Failed to detect encoding");
const QString text = QStringDecoder(*encoding).decode(bytes);
return text;
}
QJSValue fromUnicode(const QString &text, const QJSValue &codecName, Scriptable *scriptable)
{
const auto encoding = encodingFromNameOrThrow(codecName, scriptable);
if (!encoding)
return QJSValue();
const QStringConverter::Flags flags = *encoding == QStringConverter::Utf8
? QStringConverter::Flag::Default
: (QStringConverter::Flag::Default | QStringConverter::Flag::WriteBom);
return scriptable->newByteArray(
QStringEncoder(*encoding, flags).encode(text) );
}
#endif
bool isGuiApplication()
{
return qobject_cast<QGuiApplication*>(qApp);
}
bool isOverridden(const QJSValue &globalObject, const QString &property)
{
return globalObject.property(property).property(QStringLiteral("_copyq")).toString() != property;
}
} // namespace
Scriptable::Scriptable(
QJSEngine *engine,
ScriptableProxy *proxy,
ItemFactory *factory,
QObject *parent)
: QObject(parent)
, m_proxy(proxy)
, m_engine(engine)
, m_factory(factory)
, m_inputSeparator("\n")
, m_input()
{
m_engine->installExtensions(QJSEngine::ConsoleExtension);
QJSValue globalObject = m_engine->globalObject();
globalObject.setProperty(QStringLiteral("global"), globalObject);
m_safeCall = evaluateStrict(m_engine, QStringLiteral(
"(function() {"
"try {return this.apply(global, arguments);}"
"catch(e) {_copyqUncaughtException = e; throw e;}"
"})"
));
m_safeEval = evaluateStrict(m_engine, QStringLiteral(
"(function(){"
"var _eval = eval;"
"return function(script) {"
"try {return _eval(script);}"
"catch(e) {_copyqUncaughtException = e; throw e;}"
"}"
"})()"
));
m_createFn = evaluateStrict(m_engine, QStringLiteral(
"(function(from, name) {"
"var f = function() {"
"_copyqArguments = arguments;"
"var v = from[name]();"
"_copyqArguments = null;"
"if (_copyqHasUncaughtException) throw _copyqUncaughtException;"
"return v;"
"};"
"f._copyq = name;"
"return f;"
"})"
));
m_createFnB = evaluateStrict(m_engine, QStringLiteral(
"(function(from, name) {"
"var f = function() {"
"_copyqArguments = arguments;"
"var v = from[name]();"
"_copyqArguments = null;"
"if (_copyqHasUncaughtException) throw _copyqUncaughtException;"
"return ByteArray(v);"
"};"
"f._copyq = 1;"
"return f;"
"})"
));
m_createProperty = evaluateStrict(m_engine, QStringLiteral(
"(function(obj, name, from) {"
"Object.defineProperty(obj, name, {"
"get: function(){return from[name];},"
"set: function(arg){from[name] = arg},"
"});"
"})"
));
installObject(this, &Scriptable::staticMetaObject, globalObject);
m_byteArrayPrototype = addScriptableClass(
&ScriptableByteArray::staticMetaObject, QStringLiteral("ByteArray"), m_engine);
m_filePrototype = addScriptableClass(
&ScriptableFile::staticMetaObject, QStringLiteral("File"), m_engine);
m_temporaryFilePrototype = addScriptableClass(
&ScriptableTemporaryFile::staticMetaObject, QStringLiteral("TemporaryFile"), m_engine);
m_dirPrototype = addScriptableClass(
&ScriptableDir::staticMetaObject, QStringLiteral("Dir"), m_engine);
m_itemSelectionPrototype = addScriptableClass(
&ScriptableItemSelection::staticMetaObject, QStringLiteral("ItemSelection"), m_engine);
m_settingsPrototype = addScriptableClass(
&ScriptableSettings::staticMetaObject, QStringLiteral("Settings"), m_engine);
}
QJSValue Scriptable::argumentsArray() const
{
return m_engine->globalObject().property("_copyqArguments");
}
int Scriptable::argumentCount() const
{
return argumentsArray().property("length").toInt();
}
QJSValue Scriptable::argument(int index) const
{
return argumentsArray().property(static_cast<quint32>(index) );
}
QJSValue Scriptable::newByteArray(const QByteArray &bytes) const
{
return newQObject(new ScriptableByteArray(bytes), m_byteArrayPrototype);
}
QJSValue Scriptable::newByteArray(ScriptableByteArray *ba) const
{
return newQObject(ba, m_byteArrayPrototype);
}
QByteArray Scriptable::fromString(const QString &value) const
{
QByteArray bytes = value.toUtf8();
#ifdef COPYQ_OS_WIN
bytes.replace('\n', "\r\n");
#endif
return bytes;
}
QVariant Scriptable::toVariant(const QJSValue &value)
{
return fromScriptValue<QVariant>(value, m_engine);
}
bool Scriptable::toInt(const QJSValue &value, int *number) const
{
bool ok;
*number = toString(value).toInt(&ok);
return ok;
}
QVariantMap Scriptable::toDataMap(const QJSValue &value) const
{
if ( value.isVariant() )
return value.toVariant().toMap();
QVariantMap dataMap;
QJSValueIterator it(value);
while (it.hasNext()) {
it.next();
dataMap.insert( it.name(), makeByteArray(it.value()) );
}
return dataMap;
}
QJSValue Scriptable::fromDataMap(const QVariantMap &dataMap) const
{
return toScriptValue(dataMap, m_engine);
}
QByteArray Scriptable::makeByteArray(const QJSValue &value) const
{
const QByteArray *data = getByteArray(value);
if (data)
return *data;
const QVariant variant = value.toVariant();
if (variant.type() == QVariant::ByteArray)
return variant.toByteArray();
return fromString(value.toString());
}
bool Scriptable::toItemData(const QJSValue &value, const QString &mime, QVariantMap *data) const
{
if (value.isUndefined()) {
data->insert( mime, QVariant() );
return true;
}
const QByteArray *itemData = getByteArray(value);
if (mime == mimeItems)
return itemData && deserializeData(data, *itemData);
data->insert( mime, itemData ? *itemData : toString(value).toUtf8() );
return true;
}
QJSValue Scriptable::getInputSeparator() const
{
return m_inputSeparator;
}
void Scriptable::setInputSeparator(const QJSValue &separator)
{
m_inputSeparator = toString(separator);
}
QString Scriptable::getCurrentPath() const
{
return QDir::currentPath();
}
void Scriptable::setCurrentPath(const QString &path)
{
QDir::setCurrent(path);
}
QString Scriptable::getAbsoluteFilePath(const QString &fileName) const
{
return QDir::isRelativePath(fileName) ? getCurrentPath() + '/' + fileName
: fileName;
}
QString Scriptable::arg(int i, const QString &defaultValue)
{
return i < argumentCount() ? toString(argument(i)) : defaultValue;
}
QJSValue Scriptable::throwError(const QString &errorMessage)
{
// QJSEngine::throwError() is available in Qt 5.12.
QJSValue throwFn = evaluateStrict(m_engine, QStringLiteral(
"(function(text) {throw new Error(text);})"
));
const auto exc = throwFn.call({errorMessage});
#if QT_VERSION >= QT_VERSION_CHECK(5,12,0)
m_engine->throwError(QJSValue::GenericError, errorMessage);
return exc;
#else
setUncaughtException(exc);
return m_uncaughtException;
#endif
}
QJSValue Scriptable::throwSaveError(const QString &filePath)
{
return throwError( tr("Cannot save to file \"%1\"!").arg(filePath) );
}
QJSValue Scriptable::throwImportError(const QString &filePath)
{
return throwError( tr("Cannot import file \"%1\"!").arg(filePath) );
}
bool Scriptable::hasUncaughtException() const
{
return m_hasUncaughtException;
}
void Scriptable::clearExceptions()
{
m_hasUncaughtException = false;
m_uncaughtException = QJSValue();
m_uncaughtExceptionStack.clear();
}
void Scriptable::setUncaughtException(const QJSValue &exc)
{
if (m_hasUncaughtException)
return;
m_uncaughtException = exc;
m_hasUncaughtException = true;
m_uncaughtExceptionStack = m_stack;
}
QJSValue Scriptable::getPlugins()
{
// Load plugins on demand.
if ( m_plugins.isUndefined() && m_factory ) {
#if QT_VERSION >= QT_VERSION_CHECK(5,10,0)
m_plugins = m_engine->newQObject(new ScriptablePlugins(this, m_factory));
m_engine->globalObject().setProperty(QStringLiteral("_copyqPlugins"), m_plugins);
m_plugins = evaluateStrict(m_engine, QStringLiteral(
"new Proxy({}, { get: function(_, name, _) { return _copyqPlugins.load(name); } });"
));
#else
m_plugins = m_engine->newObject();
m_engine->globalObject().setProperty(QStringLiteral("_copyqPlugins"), m_plugins);
for (const ItemLoaderPtr &loader : m_factory->loaders()) {
const auto obj = loader->scriptableObject();
if (!obj)
continue;
auto plugin = m_engine->newObject();
m_plugins.setProperty(loader->id(), plugin);
installObject(obj, obj->metaObject(), plugin);
obj->setScriptable(this);
obj->start();
}
#endif
}
return m_plugins;
}
QJSValue Scriptable::call(const QString &label, QJSValue *fn, const QVariantList &arguments)
{
QJSValueList fnArgs;
fnArgs.reserve( arguments.size() );
for (const auto &argument : arguments)
fnArgs.append( toScriptValue(argument, m_engine) );
return call(label, fn, fnArgs);
}
QJSValue Scriptable::call(const QString &label, QJSValue *fn, const QJSValueList &arguments)
{
m_stack.prepend(label);
COPYQ_LOG_VERBOSE( QStringLiteral("Stack push: %1").arg(m_stack.join('|')) );
const auto v = m_safeCall.callWithInstance(*fn, arguments);
m_stack.pop_front();
COPYQ_LOG_VERBOSE( QStringLiteral("Stack pop: %1").arg(m_stack.join('|')) );
return v;
}
QJSValue Scriptable::ByteArray() const
{
const auto arg = argument(0);
if (arg.isUndefined())
return newByteArray(new ScriptableByteArray());
if (arg.isNumber())
return newByteArray(new ScriptableByteArray(arg.toInt()));
const auto obj = arg.toQObject();
if (obj) {
const auto ba = qobject_cast<ScriptableByteArray*>(obj);
if (ba)
return newByteArray(new ScriptableByteArray(*ba));
}
return newByteArray(new ScriptableByteArray(makeByteArray(arg)));
}
QJSValue Scriptable::File() const
{
const auto arg = argument(0);
const auto path = arg.isUndefined() ? QString() : toString(arg);
return newQObject(new ScriptableFile(path), m_filePrototype);
}
QJSValue Scriptable::TemporaryFile() const
{
const auto arg = argument(0);
const auto path = arg.isUndefined() ? QString() : toString(arg);
return newQObject(new ScriptableTemporaryFile(path), m_temporaryFilePrototype);
}
QJSValue Scriptable::Dir() const
{
const auto arg = argument(0);
const auto path = arg.isUndefined() ? QString() : toString(arg);
return newQObject(new ScriptableDir(path), m_dirPrototype);
}
QJSValue Scriptable::ItemSelection() const
{
const auto arg = argument(0);
const auto tabName = arg.isUndefined() ? QString() : toString(arg);
auto sel = new ScriptableItemSelection(tabName);
auto obj = newQObject(sel, m_itemSelectionPrototype);
sel->init(obj, m_proxy, m_tabName);
return obj;
}
QJSValue Scriptable::Settings() const
{
const auto arg = argument(0);
if (arg.isUndefined())
return newQObject(new ScriptableSettings(), m_settingsPrototype);
return newQObject(new ScriptableSettings(toString(arg)), m_settingsPrototype);
}
QJSValue Scriptable::version()
{
m_skipArguments = 0;
return tr("CopyQ Clipboard Manager") + " " + versionString + "\n"
+ "Qt: " QT_VERSION_STR "\n"
#ifdef WITH_NATIVE_NOTIFICATIONS
+ "KNotifications: " KNOTIFICATIONS_VERSION_STRING "\n"
#endif
+ "Compiler: "
#if defined(Q_CC_GNU)
"GCC"
#elif defined(Q_CC_CLANG)
"Clang"
#elif defined(Q_CC_MINGW)
"MinGW"
#elif defined(Q_CC_MSVC)
"MSVC"
#else
"???"
#endif
+ "\n"
+ "Arch: " + QSysInfo::buildAbi() + "\n"
+ "OS: " + QSysInfo::prettyProductName() + "\n"
;
}
QJSValue Scriptable::help()
{
m_skipArguments = -1;
QString helpString;
if ( argumentCount() == 0 ) {
helpString.append(helpHead() + "\n");
for (const auto &hlp : commandHelp())
helpString.append(hlp.toString());
helpString.append("\n" + helpTail() + "\n\n" + tr("CopyQ Clipboard Manager")
+ " " + versionString + "\n");
} else {
for (int i = 0; i < argumentCount(); ++i) {
const QString &cmd = toString(argument(i));
for (const auto &helpItem : commandHelp()) {
if ( helpItem.cmd.contains(cmd) )
helpString.append(helpItem.toString());
}
}
if ( helpString.isEmpty() ) {
return throwError( tr("Command not found!") );
}
}
return helpString;
}
void Scriptable::show()
{
m_skipArguments = 1;
if ( argumentCount() == 0 )
m_proxy->showWindow();
else
m_proxy->showBrowser( toString(argument(0)) );
}
void Scriptable::showAt()
{
QRect rect(-1, -1, 0, 0);
int n;
int i = 0;
if ( toInt(argument(i), &n) ) {
rect.setX(n);
++i;
if ( toInt(argument(i), &n) ) {
rect.setY(n);
++i;
if ( toInt(argument(i), &n) ) {
rect.setWidth(n);
++i;
if ( toInt(argument(i), &n) ) {
rect.setHeight(n);
++i;
}
}
}
}
m_skipArguments = i;
const auto tabName = arg(i++);
if ( tabName.isEmpty() )
m_proxy->showWindowAt(rect);
else
m_proxy->showBrowserAt(tabName, rect);
}
void Scriptable::hide()
{
m_skipArguments = 0;
m_proxy->close();
}
QJSValue Scriptable::toggle()
{
m_skipArguments = 0;
return m_proxy->toggleVisible();
}
QJSValue Scriptable::menu()
{
m_skipArguments = 4;
if (argumentCount() == 0) {
m_proxy->toggleCurrentMenu();
} else {
const auto tabName = toString(argument(0));
int maxItemCount = -1;
if (argumentCount() >= 2) {
const auto value = argument(1);
if ( !toInt(value, &maxItemCount) || maxItemCount <= 0 ) {
return throwError("Argument maxItemCount must be positive number");
}
}
int x = -1;
int y = -1;
if (argumentCount() >= 3) {
const auto xValue = argument(2);
const auto yValue = argument(3);
if ( !toInt(xValue, &x) || !toInt(yValue, &y) ) {
return throwError("Coordinates must be numbers");
}
}
m_proxy->toggleMenu( tabName, maxItemCount, QPoint(x, y) );
}
return QJSValue();
}
void Scriptable::exit()
{
m_skipArguments = 0;
QByteArray message = fromString( tr("Terminating server.\n") );
print(message);
m_proxy->exit();
}
void Scriptable::disable()
{
m_skipArguments = 0;
m_proxy->disableMonitoring(true);
}
void Scriptable::enable()
{
m_skipArguments = 0;
m_proxy->disableMonitoring(false);
}
QJSValue Scriptable::monitoring()
{
m_skipArguments = 0;
return m_proxy->isMonitoringEnabled();
}
QJSValue Scriptable::visible()
{
m_skipArguments = 0;
return m_proxy->isMainWindowVisible();
}
QJSValue Scriptable::focused()
{
m_skipArguments = 0;
return m_proxy->isMainWindowFocused();
}
QJSValue Scriptable::focusPrevious()
{
m_skipArguments = 0;
if ( !m_proxy->focusPrevious() )
return throwError("Failed to focus previous window");
return QJSValue();
}
QJSValue Scriptable::preview()
{
m_skipArguments = 1;
return m_proxy->preview( toVariant(argument(0)) );
}
QJSValue Scriptable::filter()
{
m_skipArguments = 1;
if (argumentCount() == 0)
return m_proxy->filter();
m_proxy->filter(arg(0));
return QJSValue();
}
void Scriptable::ignore()
{
m_skipArguments = 0;
m_data[mimeIgnore] = QByteArray();
}
QJSValue Scriptable::clipboard()
{
m_skipArguments = 1;
const QString &mime = arg(0, mimeText);
return newByteArray( getClipboardData(mime) );
}
QJSValue Scriptable::selection()
{
m_skipArguments = 1;
#ifdef HAS_MOUSE_SELECTIONS
const QString &mime = arg(0, mimeText);
return newByteArray( getClipboardData(mime, ClipboardMode::Selection) );
#else
return QJSValue();
#endif
}
QJSValue Scriptable::hasClipboardFormat()
{
m_skipArguments = 1;
const QString &mime = arg(0);
return hasClipboardFormat(mime, ClipboardMode::Clipboard);
}
QJSValue Scriptable::hasSelectionFormat()
{
m_skipArguments = 1;
#ifdef HAS_MOUSE_SELECTIONS
const QString &mime = arg(0);
return hasClipboardFormat(mime, ClipboardMode::Selection);
#else
return false;
#endif
}
QJSValue Scriptable::isClipboard()
{
return isClipboardData(m_data);
}
QJSValue Scriptable::copy()
{
m_skipArguments = -1;
return copy(ClipboardMode::Clipboard);
}
QJSValue Scriptable::copySelection()
{
m_skipArguments = -1;
#ifdef HAS_MOUSE_SELECTIONS
return copy(ClipboardMode::Selection);
#else
return QJSValue();
#endif
}
QJSValue Scriptable::paste()
{
m_skipArguments = 0;
if ( !m_proxy->pasteToCurrentWindow() )
return throwError( QStringLiteral("Failed to paste clipboard") );
const QString option = QStringLiteral("script_paste_delay_ms");
const auto values = m_proxy->config({option}).toMap();
const int msec = values.value(option).toInt();
COPYQ_LOG( QStringLiteral("Delay after paste: %1ms").arg(msec) );
if (msec > 0)
interruptibleSleep(msec);
return QJSValue();
}
QJSValue Scriptable::tab()
{
m_skipArguments = 1;
const QString &name = arg(0);
if ( name.isNull() )
return toScriptValue( m_proxy->tabs(), m_engine );
m_tabName = name;
return QJSValue();
}
QJSValue Scriptable::removeTab()
{
m_skipArguments = 1;
const QString &name = arg(0);
if ( const QString error = m_proxy->removeTab(name); !error.isEmpty() )
return throwError(error);
return QJSValue();
}
QJSValue Scriptable::renameTab()
{
m_skipArguments = 2;
const QString &name = arg(0);
const QString &newName = arg(1);
if ( const QString error = m_proxy->renameTab(newName, name); !error.isEmpty() )
return throwError(error);
return QJSValue();
}
QJSValue Scriptable::tabIcon()
{
m_skipArguments = 2;
if (argumentCount() == 1)
return m_proxy->tabIcon(arg(0));
if (argumentCount() < 2)
return throwError(argumentError());
m_proxy->setTabIcon(arg(0), arg(1));
return QJSValue();
}
QJSValue Scriptable::unload()
{
const auto tabs = arguments();
const QStringList unloaded = m_proxy->unloadTabs(tabs.isEmpty() ? m_proxy->tabs() : tabs);
return toScriptValue(unloaded, m_engine);
}
void Scriptable::forceUnload()
{
const auto tabs = arguments();
m_proxy->forceUnloadTabs(tabs.isEmpty() ? m_proxy->tabs() : tabs);
}
QJSValue Scriptable::length()
{
m_skipArguments = 0;
return m_proxy->browserLength(m_tabName);
}
QJSValue Scriptable::select()
{
m_skipArguments = 1;
QJSValue value = argument(0);
int row;
if ( !toInt(value, &row) )
return throwError(argumentError());
m_proxy->browserMoveToClipboard(m_tabName, row);
return QJSValue();
}
void Scriptable::next()
{
m_skipArguments = 0;
nextToClipboard(1);
}
void Scriptable::previous()
{
m_skipArguments = 0;
nextToClipboard(-1);
}
void Scriptable::add()
{
insert(0, 0, argumentCount());
}
void Scriptable::insert()
{
insert(argumentCount());
}
QJSValue Scriptable::remove()
{
auto rows = getRows();
m_skipArguments = rows.size();
if ( rows.empty() )
rows.append(0);
if ( const auto error = m_proxy->browserRemoveRows(m_tabName, rows); !error.isEmpty() )
return throwError(error);
return QJSValue();
}
QJSValue Scriptable::move()
{
m_skipArguments = 1;
int row;
if ( !toInt(argument(0), &row) ) {
return throwError(argumentError());
}
m_proxy->browserMoveSelected(row);
return QJSValue();
}
void Scriptable::edit()
{
m_skipArguments = -1;
QByteArray content;
int row = -1;
int editRow = -1;
bool changeClipboard = true;
const int len = argumentCount();
for ( int i = 0; i < len; ++i ) {
const QJSValue value = argument(i);
if (i > 0)
content.append(m_inputSeparator.toUtf8());
if ( toInt(value, &row) ) {
editRow = (i == 0) ? row : -1;
changeClipboard = i == 0 && row < 0;
const QByteArray bytes = row >= 0 ? m_proxy->browserItemData(m_tabName, row, mimeText)
: getClipboardData(mimeText);
content.append(bytes);
} else {
content.append( toByteArray(value) );
}
}
editContent(editRow, mimeText, content, changeClipboard);
}
QJSValue Scriptable::editItem()
{
m_skipArguments = 3;
int editRow;
if ( !toInt(argument(0), &editRow) )
return throwError(argumentError());
const auto format = arg(1, mimeText);
const bool changeClipboard = editRow < 0;
QByteArray content;
if ( argumentCount() > 2 )
content = makeByteArray(argument(2));
else if (editRow >= 0)
content = m_proxy->browserItemData(m_tabName, editRow, format);
else
content = getClipboardData(format);
editContent(editRow, format, content, changeClipboard);
return {};
}
QJSValue Scriptable::read()
{
m_skipArguments = -1;
QByteArray result;
QString mime(mimeText);
QJSValue value;
bool used = false;
for ( int i = 0; i < argumentCount(); ++i ) {
value = argument(i);
int row;
if ( toInt(value, &row) ) {
if (used)
result.append( m_inputSeparator.toUtf8() );
used = true;
result.append( row >= 0 ? m_proxy->browserItemData(m_tabName, row, mime)
: getClipboardData(mime) );
} else {
mime = toString(value);
}
}
if (!used)
result.append( getClipboardData(mime) );
return newByteArray(result);
}
QJSValue Scriptable::write()
{
m_skipArguments = -1;
return changeItem(true);
}
QJSValue Scriptable::change()
{
m_skipArguments = -1;
return changeItem(false);
}
void Scriptable::separator()
{
setInputSeparator( toString(argument(0)) );
m_skipArguments = 1;
}
void Scriptable::action()
{
QString text;
bool anyRows = false;
int i;
QJSValue value;
for ( i = 0; i < argumentCount(); ++i ) {
value = argument(i);
int row;
if (!toInt(value, &row))
break;
if (anyRows)
text.append(m_inputSeparator);
else
anyRows = true;
text.append( getTextData(m_proxy->browserItemData(m_tabName, row, mimeText)) );
}
QString cmd = toString(value);
m_skipArguments = i + 2;
if (!anyRows) {
text = getTextData( getClipboardData(mimeText) );
}
const QVariantMap data = createDataMap(mimeText, text);
if (i < argumentCount()) {
Command command;
command.cmd = cmd;
command.output = mimeText;
command.input = mimeText;
command.wait = false;
command.outputTab = m_proxy->tab(m_tabName);
command.sep = ((i + 1) < argumentCount()) ? toString( argument(i + 1) )
: QString('\n');
m_proxy->action(data, command);
} else {
m_proxy->openActionDialog(data);
}
}
void Scriptable::popup()
{
m_skipArguments = 3;
const QString title = arg(0);
const QString message = arg(1);
int msec;
if ( !toInt(argument(2), &msec) )
msec = 8000;
m_proxy->showMessage(title, message, QString(), msec);
}
QJSValue Scriptable::notification()
{
m_skipArguments = -1;
QString title;
QString message;
int msec = -1;
QString icon;
QString notificationId;
NotificationButtonList buttons;
for ( int i = 0; i < argumentCount(); ++i ) {
const auto name = arg(i++);
if ( name == QLatin1String(".title") ) {
title = arg(i);
} else if ( name == QLatin1String(".message") ) {
message = arg(i);
} else if ( name == QLatin1String(".time") ) {
if ( !toInt(argument(i), &msec) ) {
return throwError("Expected number after .time argument");
}
} else if ( name == QLatin1String(".id") ) {
notificationId = arg(i);
} else if ( name == QLatin1String(".icon") ) {
icon = arg(i);
} else if ( name == QLatin1String(".button") ) {
NotificationButton button;
button.name = arg(i);
button.script = arg(++i);
button.data = makeByteArray( argument(++i) );
buttons.items.append(button);
} else {
return throwError("Unknown argument: " + name);
}
}
m_proxy->showMessage(title, message, icon, msec, notificationId, buttons);
return QJSValue();
}
QJSValue Scriptable::exportTab()
{
m_skipArguments = 1;
const auto filePath = arg(0);
if ( filePath.isNull() )
return throwError(argumentError());
if ( !m_proxy->saveTab(m_tabName, getAbsoluteFilePath(filePath)) )
return throwSaveError(filePath);
return QJSValue();
}
QJSValue Scriptable::importTab()
{
m_skipArguments = 1;
const auto filePath = arg(0);
if ( filePath.isNull() )
return throwError(argumentError());
if ( !m_proxy->loadTab(getAbsoluteFilePath(filePath)) )
return throwImportError(filePath);
return QJSValue();
}
QJSValue Scriptable::importData()
{
m_skipArguments = 1;
const auto filePath = arg(0);
if ( filePath.isNull() )
return throwError(argumentError());
if ( !m_proxy->importData(getAbsoluteFilePath(filePath)) )
return throwImportError(filePath);
return QJSValue();
}
QJSValue Scriptable::exportData()
{
m_skipArguments = 1;
const auto filePath = arg(0);
if ( filePath.isNull() )
return throwError(argumentError());
if ( !m_proxy->exportData(getAbsoluteFilePath(filePath)) )
return throwSaveError(filePath);
return QJSValue();
}
QJSValue Scriptable::config()
{
m_skipArguments = -1;
const QVariantList nameValueInput = argumentsAsVariants();
if (nameValueInput.isEmpty())
return m_proxy->configDescription();
const auto result = m_proxy->config(nameValueInput);
if ( result.type() == QVariant::String )
return result.toString();
if ( result.type() == QVariant::StringList ) {
QString errors;
const auto unknownOptions = result.toStringList();
for (const auto &name : unknownOptions) {
if ( !errors.isEmpty() )
errors.append('\n');
errors.append( tr("Invalid option \"%1\"!").arg(name) );
}
return throwError(errors);
}
const auto nameValue = result.toMap();
if ( nameValue.size() == 1 ) {
const auto value = nameValue.constBegin().value();
return value.type() == QVariant::StringList || value.type() == QVariant::List
? toScriptValue(value, m_engine)
: toScriptValue(value.toString(), m_engine);
}
QStringList output;
for (auto it = nameValue.constBegin(); it != nameValue.constEnd(); ++it) {
const auto name = it.key();
const auto value = it.value();
const auto textValue =
value.type() == QVariant::StringList || value.type() == QVariant::List
? value.toStringList().join(',')
: value.toString();
output.append( name + "=" + textValue );
}
return toScriptValue(output, m_engine);
}
QJSValue Scriptable::toggleConfig()
{
m_skipArguments = 1;
const auto optionName = arg(0);
if ( optionName.isEmpty() )
return throwError(argumentError());
const auto result = m_proxy->toggleConfig(optionName);
if ( result.type() != QVariant::Bool ) {
return throwError( QStringLiteral("Invalid boolean option \"%1\"!").arg(optionName) );
}
return result.toBool();
}
QJSValue Scriptable::info()
{
m_skipArguments = 1;
using InfoMap = QMap<QString, QString>;
InfoMap info;
info.insert("config", QSettings().fileName());
info.insert("exe", QCoreApplication::applicationFilePath());
info.insert("log", logFileName());
info.insert("data", itemDataPath());
info.insert("plugins",
#ifdef COPYQ_PLUGIN_PREFIX
COPYQ_PLUGIN_PREFIX
#else
m_proxy ? m_proxy->pluginsPath() : pluginsPath()
#endif
);
info.insert("themes",
#ifdef COPYQ_THEME_PREFIX
COPYQ_THEME_PREFIX
#else
m_proxy ? m_proxy->themesPath() : themesPath()
#endif
);
info.insert("translations",
#ifdef COPYQ_TRANSLATION_PREFIX
COPYQ_TRANSLATION_PREFIX
#else
m_proxy ? m_proxy->translationsPath() : translationsPath()
#endif
);
info.insert("themes(custom)", qgetenv("COPYQ_THEME_PREFIX"));
info.insert("translations(custom)", qgetenv("COPYQ_TRANSLATION_PREFIX"));
info.insert("icons",
#ifdef COPYQ_ICON_PREFIX
COPYQ_ICON_PREFIX
#else
QString()
#endif
);
info.insert("desktop",
#ifdef COPYQ_DESKTOP_FILE
COPYQ_DESKTOP_FILE
#else
QString()
#endif
);
info.insert("has-mouse-selection",
#ifdef HAS_MOUSE_SELECTIONS
"1"
#else
"0"
#endif
);
info.insert("has-global-shortcuts",
#ifdef COPYQ_GLOBAL_SHORTCUTS
"1"
#else
"0"
#endif
);
info.insert("platform",
#if defined(Q_OS_WIN)
"Windows"
#elif defined(Q_OS_MAC)
"OS X"
#elif defined(Q_OS_LINUX)
"Linux"
#elif defined(Q_OS_UNIX)
"Unix"
#else
"?"
#endif
#ifdef COPYQ_WITH_X11
"/X11"
#endif
);
const QString name = arg(0);
if (!name.isEmpty())
return info.value(name);
QString result;
for (auto it = info.constBegin(); it != info.constEnd(); ++it)
result.append( QStringLiteral("%1: %2\n").arg(it.key(), it.value()) );
result.chop(1);
return result;
}
QJSValue Scriptable::eval()
{
const auto script = arg(0);
const auto result = eval(script);
if ( result.isError() )
setUncaughtException(result);
m_skipArguments = -1;
return result;
}
QJSValue Scriptable::source()
{
const auto scriptFilePath = arg(0);
QByteArray script;
{
QFile scriptFile( getAbsoluteFilePath(scriptFilePath) );
if ( !scriptFile.open(QIODevice::ReadOnly) ) {
return throwError(
QStringLiteral("Failed to open \"%1\": %2")
.arg(scriptFilePath,
scriptFile.errorString()) );
}
script = scriptFile.readAll();
}
const auto result = eval(script, scriptFilePath);
m_skipArguments = 1;
return result;
}
QJSValue Scriptable::currentPath()
{
m_skipArguments = 1;
if (argumentCount() > 0)
setCurrentPath(arg(0));
return getCurrentPath();
}
QJSValue Scriptable::str()
{
m_skipArguments = 1;
return arg(0);
}
QJSValue Scriptable::input()
{
m_skipArguments = 0;
if ( !getByteArray(m_input) )
m_input = readInput();
return m_input;
}
QJSValue Scriptable::toUnicode()
{
m_skipArguments = 2;
const auto bytes = makeByteArray(argument(0));
if (argumentCount() >= 2)
return ::toUnicode(bytes, argument(1), this);
if (argumentCount() >= 1)
return ::toUnicode(bytes, this);
return throwError(argumentError());
}
QJSValue Scriptable::fromUnicode()
{
m_skipArguments = 2;
if (argumentCount() < 2)
return throwError(argumentError());
const QJSValue codecName = argument(1);
const QString text = arg(0);
return ::fromUnicode(text, codecName, this);
}
QJSValue Scriptable::dataFormats()
{
m_skipArguments = 0;
return toScriptValue( m_data.keys(), m_engine );
}
QJSValue Scriptable::data()
{
m_skipArguments = 1;
return newByteArray( m_data.value(arg(0)).toByteArray() );
}
QJSValue Scriptable::setData()
{
m_skipArguments = 2;
const QString mime = arg(0);
if ( !toItemData(argument(1), mime, &m_data) )
return false;
if (!m_modifyDisplayDataOnly)
m_proxy->setSelectedItemsData(mime, m_data.value(mime));
return true;
}
QJSValue Scriptable::removeData()
{
m_skipArguments = 1;
const QString mime = arg(0);
m_data.remove(mime);
if (!m_modifyDisplayDataOnly)
m_proxy->setSelectedItemsData(mime, QVariant());
return true;
}
void Scriptable::print()
{
m_skipArguments = 1;
print(makeByteArray(argument(0)));
}
void Scriptable::abort()
{
m_skipArguments = 0;
abortEvaluation(m_action ? Abort::CurrentEvaluation : Abort::AllEvaluations);
}
void Scriptable::fail()
{
m_skipArguments = 0;
m_failed = true;
abortEvaluation(Abort::CurrentEvaluation);
}
#ifdef HAS_TESTS
QJSValue Scriptable::keys()
{
m_skipArguments = -1;
bool ok;
// Wait interval after shortcut pressed or text typed.
const auto waitValue = qgetenv("COPYQ_TESTS_KEYS_WAIT");
int wait = waitValue.toInt(&ok);
if (!ok)
wait = 0;
// Delay while typing.
const auto delayValue = qgetenv("COPYQ_TESTS_KEY_DELAY");
int delay = delayValue.toInt(&ok);
if (!ok)
delay = 0;
QString expectedWidgetName;
const auto focusPrefix = QLatin1String("focus:");
for (int i = 0; i < argumentCount(); ++i) {
const QString keys = toString(argument(i));
if (keys.startsWith(focusPrefix)) {
expectedWidgetName = keys.mid(focusPrefix.size());
m_proxy->sendKeys(expectedWidgetName, QString(), 0);
} else {
waitFor(wait);
m_proxy->sendKeys(expectedWidgetName, keys, delay);
}
// Make sure all keys are send (shortcuts are postponed because they can be blocked by modal windows).
for (;;) {
if ( m_proxy->sendKeysSucceeded() )
break;
if ( m_proxy->sendKeysFailed() )
return throwError("Failed to send key presses");
QCoreApplication::processEvents();
if (!canContinue())
return throwError("Disconnected");
}
}
return QJSValue();
}
QJSValue Scriptable::testSelected()
{
m_skipArguments = 0;
return m_proxy->testSelected();
}
#else // HAS_TESTS
QJSValue Scriptable::keys()
{
m_skipArguments = -1;
return QJSValue();
}
QJSValue Scriptable::testSelected()
{
m_skipArguments = 0;
return QJSValue();
}
#endif // HAS_TESTS
void Scriptable::serverLog()
{
m_skipArguments = 1;
m_proxy->serverLog(arg(0));
}
QJSValue Scriptable::logs()
{
m_skipArguments = 0;
return QString::fromUtf8(readLogFile(50 * 1024 * 1024));
}
void Scriptable::setCurrentTab()
{
m_skipArguments = 1;
const QString tabName = arg(0);
m_proxy->setCurrentTab(tabName);
}
QJSValue Scriptable::selectItems()
{
const auto rows = getRows();
m_skipArguments = rows.size();
return m_proxy->selectItems(m_tabName, rows);
}
QJSValue Scriptable::selectedTab()
{
m_skipArguments = 0;
return m_proxy->selectedTab();
}
QJSValue Scriptable::selectedItems()
{
m_skipArguments = 0;
return toScriptValue( m_proxy->selectedItems(), m_engine );
}
QJSValue Scriptable::currentItem()
{
m_skipArguments = 0;
return m_proxy->currentItem();
}
QJSValue Scriptable::selectedItemData()
{
int selectedIndex;
if ( !toInt(argument(0), &selectedIndex) )
return throwError(argumentError());
return toScriptValue( m_proxy->selectedItemData(selectedIndex), m_engine );
}
QJSValue Scriptable::setSelectedItemData()
{
int selectedIndex;
if ( !toInt(argument(0), &selectedIndex) )
return throwError(argumentError());
const auto data = toDataMap( argument(1) );
return toScriptValue( m_proxy->setSelectedItemData(selectedIndex, data), m_engine );
}
QJSValue Scriptable::selectedItemsData()
{
return toScriptValue( m_proxy->selectedItemsData().items, m_engine );
}
void Scriptable::setSelectedItemsData()
{
m_skipArguments = 1;
const VariantMapList dataList{fromScriptValue<QVector<QVariantMap>>( argument(0), m_engine )};
m_proxy->setSelectedItemsData(dataList);
}
QJSValue Scriptable::escapeHtml()
{
m_skipArguments = 1;
return ::escapeHtml( toString(argument(0)) );
}
QJSValue Scriptable::unpack()
{
m_skipArguments = 1;
QVariantMap data;
if ( !toItemData(argument(0), mimeItems, &data) )
return throwError(argumentError());
return toScriptValue(data, m_engine);
}
QJSValue Scriptable::pack()
{
m_skipArguments = 1;
QVariantMap data = toDataMap( argument(0) );
return newByteArray(serializeData(data));
}
QJSValue Scriptable::getItem()
{
m_skipArguments = 1;
int row;
if ( !toInt(argument(0), &row) )
return throwError(argumentError());
return toScriptValue( m_proxy->browserItemData(m_tabName, row), m_engine );
}
void Scriptable::setItem()
{
insert(2);
}
QJSValue Scriptable::toBase64()
{
m_skipArguments = 1;
return QString::fromLatin1(makeByteArray(argument(0)).toBase64());
}
QJSValue Scriptable::fromBase64()
{
m_skipArguments = 1;
return newByteArray(QByteArray::fromBase64(makeByteArray(argument(0))));
}
QJSValue Scriptable::md5sum()
{
m_skipArguments = 1;
return checksumForArgument(this, QCryptographicHash::Md5);
}
QJSValue Scriptable::sha1sum()
{
m_skipArguments = 1;
return checksumForArgument(this, QCryptographicHash::Sha1);
}
QJSValue Scriptable::sha256sum()
{
m_skipArguments = 1;
return checksumForArgument(this, QCryptographicHash::Sha256);
}
QJSValue Scriptable::sha512sum()
{
m_skipArguments = 1;
return checksumForArgument(this, QCryptographicHash::Sha512);
}
QJSValue Scriptable::open()
{
m_skipArguments = -1;
return m_proxy->openUrls( arguments() );
}
QJSValue Scriptable::execute()
{
m_skipArguments = -1;
QByteArray executeStdoutData;
QString executeStdoutLastLine;
QJSValue executeStdoutCallback;
// Pass all arguments until null to command. The rest will be sent to stdin.
QStringList args;
int i = 0;
for ( ; i < argumentCount(); ++i ) {
const auto arg = argument(i);
if (arg.isNull())
break;
if ( arg.isCallable() )
executeStdoutCallback = arg;
else
args.append( toString(arg) );
}
Action action;
for ( ++i ; i < argumentCount(); ++i ) {
const auto arg = argument(i);
if ( arg.isCallable() )
executeStdoutCallback = arg;
else
action.setInput( action.input() + makeByteArray(arg) );
}
action.setCommand(args);
action.setReadOutput(true);
connect( &action, &Action::actionOutput,
this, [&](const QByteArray &output) {
executeStdoutData.append(output);
});
if ( executeStdoutCallback.isCallable() ) {
connect( &action, &Action::actionOutput,
this, [&](const QByteArray &output) {
executeStdoutLastLine.append( getTextData(output) );
auto lines = executeStdoutLastLine.split('\n');
executeStdoutLastLine = lines.takeLast();
if ( !lines.isEmpty() ) {
const auto arg = toScriptValue(lines, m_engine);
call( "executeStdoutCallback", &executeStdoutCallback, {arg} );
}
});
}
if ( !runAction(&action) || action.actionFailed() ) {
return throwError( QStringLiteral("Failed to run command") );
}
if ( executeStdoutCallback.isCallable() ) {
const auto arg = toScriptValue(executeStdoutLastLine, m_engine);
call( "executeStdoutCallback", &executeStdoutCallback, {arg} );
}
QJSValue actionResult = m_engine->newObject();
actionResult.setProperty( QStringLiteral("stdout"), newByteArray(executeStdoutData) );
actionResult.setProperty( QStringLiteral("stderr"), getTextData(action.errorOutput()) );
actionResult.setProperty( QStringLiteral("exit_code"), action.exitCode() );
return actionResult;
}
QJSValue Scriptable::currentWindowTitle()
{
m_skipArguments = 0;
if ( isGuiApplication() ) {
PlatformWindowPtr window = platformNativeInterface()->getCurrentWindow();
return window ? window->getTitle() : QString();
}
return m_proxy->currentWindowTitle();
}
QJSValue Scriptable::currentClipboardOwner()
{
return eval("currentWindowTitle()");
}
QJSValue Scriptable::dialog()
{
m_skipArguments = -1;
NamedValueList values;
values.items.reserve(argumentCount() / 2);
for ( int i = 0; i < argumentCount(); i += 2 ) {
const QString key = arg(i);
const QJSValue value = argument(i + 1);
values.items.append( NamedValue(key, toVariant(value)) );
}
const auto dialogId = m_proxy->inputDialog(values);
if ( !canContinue() )
return QJSValue();
QEventLoop loop;
connect(this, &Scriptable::finished, &loop, &QEventLoop::quit);
connect( m_proxy, &ScriptableProxy::inputDialogFinished,
&loop, [&](int finishedDialogId, const NamedValueList &result) {
if (finishedDialogId != dialogId)
return;
values = result;
loop.quit();
});
loop.exec();
if (values.items.isEmpty())
return QJSValue();
if (values.items.size() == 1)
return toScriptValue( values.items.first().value, m_engine );
QJSValue result = m_engine->newObject();
for (const auto &value : values.items)
result.setProperty( value.name, toScriptValue(value.value, m_engine) );
return result;
}
QJSValue Scriptable::menuItems()
{
const auto text = argument(0);
if ( text.isString() ) {
m_skipArguments = -1;
VariantMapList items;
for (const auto &arg : arguments())
items.items.append(createDataMap(mimeText, arg));
const int i = m_proxy->menuItems(items);
if (i == -1 || i >= items.items.size())
return QString();
return getTextData(items.items[i]);
}
m_skipArguments = 1;
const VariantMapList items{fromScriptValue<QVector<QVariantMap>>(text, m_engine)};
if ( items.items.isEmpty() )
return -1;
return m_proxy->menuItems(items);
}
QJSValue Scriptable::settings()
{
m_skipArguments = 2;
QSettings settings(
QSettings::IniFormat,
QSettings::UserScope,
QCoreApplication::organizationName(),
QCoreApplication::applicationName() + "-scripts");
if (argumentCount() == 2) {
const QString key = arg(0);
const QJSValue value = argument(1);
const QVariant saveValue = toVariant(value);
settings.setValue(key, saveValue);
return QJSValue();
}
if (argumentCount() == 1) {
const auto value = settings.value(arg(0));
return toScriptValue(value, m_engine);
}
return toScriptValue(settings.allKeys(), m_engine);
}
QJSValue Scriptable::dateString()
{
m_skipArguments = 1;
const QDateTime dateTime = QDateTime::currentDateTime();
return dateTime.toString(arg(0));
}
QJSValue Scriptable::commands()
{
return toScriptValue( m_proxy->commands(), m_engine );
}
void Scriptable::setCommands()
{
const auto commands = fromScriptValue<QVector<Command>>(argument(0), m_engine);
m_proxy->setCommands(commands);
}
void Scriptable::addCommands()
{
const auto commands = fromScriptValue<QVector<Command>>(argument(0), m_engine);
m_proxy->addCommands(commands);
}
QJSValue Scriptable::importCommands()
{
m_skipArguments = 1;
const auto commands = importCommandsFromText(arg(0));
return toScriptValue(commands, m_engine);
}
QJSValue Scriptable::exportCommands()
{
m_skipArguments = 1;
const auto commands = fromScriptValue<QVector<Command>>(argument(0), m_engine);
const auto exportedCommands = ::exportCommands(commands);
if ( exportedCommands.isEmpty() )
return throwError("Failed to export commands");
return exportedCommands;
}
QJSValue Scriptable::networkGet()
{
NetworkReply *reply = networkGetHelper();
reply->data();
return reply->toScriptValue();
}
QJSValue Scriptable::networkPost()
{
NetworkReply *reply = networkPostHelper();
reply->data();
return reply->toScriptValue();
}
QJSValue Scriptable::networkGetAsync()
{
NetworkReply *reply = networkGetHelper();
return reply->toScriptValue();
}
QJSValue Scriptable::networkPostAsync()
{
NetworkReply *reply = networkPostHelper();
return reply->toScriptValue();
}
QJSValue Scriptable::env()
{
m_skipArguments = 1;
const QString name = arg(0);
const QByteArray value = qgetenv(name.toUtf8().constData());
return newByteArray(value);
}
QJSValue Scriptable::setEnv()
{
m_skipArguments = 2;
const QString name = arg(0);
const QByteArray value = makeByteArray(argument(1));
return qputenv(name.toUtf8().constData(), value);
}
QJSValue Scriptable::sleep()
{
m_skipArguments = 1;
int msec;
if ( !toInt(argument(0), &msec) )
return throwError(argumentError());
interruptibleSleep(msec);
return QJSValue();
}
QJSValue Scriptable::afterMilliseconds()
{
m_skipArguments = 2;
if (argumentCount() < 2)
return throwError(argumentError());
int msec;
if ( !toInt(argument(0), &msec) )
return throwError(argumentError());
const auto fn = argument(1);
if ( !fn.isCallable() )
return throwError(argumentError());
class TimedFunctionCall final : public QObject {
public:
TimedFunctionCall(int msec, const QJSValue &fn, Scriptable *scriptable)
: QObject(scriptable)
, m_timerId( startTimer(msec, Qt::PreciseTimer) )
, m_fn(fn)
, m_scriptable(scriptable)
{
}
protected:
void timerEvent(QTimerEvent *event) override
{
QObject::timerEvent(event);
if ( m_timerId == event->timerId() ) {
killTimer(m_timerId);
m_scriptable->call("afterMillisecondsCallback", &m_fn);
}
}
private:
int m_timerId;
QJSValue m_fn;
Scriptable *m_scriptable;
};
new TimedFunctionCall(msec, fn, this);
return QJSValue();
}
QVariant Scriptable::call(const QString &method, const QVariantList &arguments)
{
if ( hasUncaughtException() )
return QVariant();
m_skipArguments = 2;
auto fn = m_engine->globalObject().property(method);
const auto result = call(method, &fn, arguments);
if ( result.isUndefined() || result.isNull() )
return QVariant();
return toVariant(result);
}
QVariantList Scriptable::currentArguments()
{
m_skipArguments = -1;
QVariantList arguments;
arguments.reserve( argumentCount() );
for ( int i = 0; i < argumentCount(); ++i )
arguments.append( toVariant(argument(i)) );
return arguments;
}
void Scriptable::throwException(const QString &errorMessage)
{
throwError(errorMessage);
}
QJSValue Scriptable::screenshot()
{
return screenshot(false);
}
QJSValue Scriptable::screenshotSelect()
{
return screenshot(true);
}
QJSValue Scriptable::screenNames()
{
return toScriptValue( m_proxy->screenNames(), m_engine );
}
QJSValue Scriptable::queryKeyboardModifiers()
{
const auto modifiers = m_proxy->queryKeyboardModifiers().items;
QStringList modifierList;
if (modifiers.testFlag(Qt::ControlModifier))
modifierList.append("Ctrl");
if (modifiers.testFlag(Qt::ShiftModifier))
modifierList.append("Shift");
if (modifiers.testFlag(Qt::AltModifier))
modifierList.append("Alt");
if (modifiers.testFlag(Qt::MetaModifier))
modifierList.append("Meta");
return toScriptValue(modifierList, m_engine);
}
QJSValue Scriptable::pointerPosition()
{
const QPoint pos = m_proxy->pointerPosition();
return toScriptValue(QVector<int>{pos.x(), pos.y()}, m_engine);
}
QJSValue Scriptable::setPointerPosition()
{
m_skipArguments = 2;
int x = 0;
int y = 0;
if ( !toInt(argument(0), &x) || !toInt(argument(1), &y) )
return throwError(argumentError());
m_proxy->setPointerPosition(x, y);
// Apparently, on macOS the pointer position is set only after some time.
SleepTimer t(5000);
while ( m_proxy->pointerPosition() != QPoint(x, y) ) {
if ( !t.sleep() )
return throwError("Failed to set pointer position");
}
return QJSValue();
}
QJSValue Scriptable::iconColor()
{
m_skipArguments = 1;
if (argumentCount() == 0)
return m_proxy->iconColor();
const auto color = arg(0);
if ( !m_proxy->setIconColor(color) )
return throwError("Invalid color name");
return QJSValue();
}
QJSValue Scriptable::iconTag()
{
m_skipArguments = 1;
if (argumentCount() == 0)
return m_proxy->iconTag();
const auto tag = arg(0);
m_proxy->setIconTag(tag);
return QJSValue();
}
QJSValue Scriptable::iconTagColor()
{
m_skipArguments = 1;
if (argumentCount() == 0)
return m_proxy->iconTagColor();
const auto color = arg(0);
if ( !m_proxy->setIconTagColor(color) )
return throwError("Invalid color name");
return QJSValue();
}
QJSValue Scriptable::loadTheme()
{
m_skipArguments = 1;
const QString path = getAbsoluteFilePath(arg(0));
if ( const QString error = m_proxy->loadTheme(path); !error.isEmpty() )
return throwError(error);
return QJSValue();
}
void Scriptable::onClipboardChanged()
{
eval(R"(
if (!hasData()) {
updateClipboardData();
} else if (runAutomaticCommands()) {
saveData();
updateClipboardData();
} else {
clearClipboardData();
}
)", "onClipboardChanged()");
}
void Scriptable::onOwnClipboardChanged()
{
eval("updateClipboardData()");
}
void Scriptable::onHiddenClipboardChanged()
{
eval("updateClipboardData()");
}
void Scriptable::onClipboardUnchanged()
{
}
void Scriptable::onSecretClipboardChanged()
{
// Drop secret data by default
m_data = {{mimeSecret, m_data.value(mimeSecret)}};
eval("updateClipboardData()");
}
void Scriptable::synchronizeToSelection()
{
if ( canSynchronizeSelection(ClipboardMode::Selection) ) {
COPYQ_LOG( QStringLiteral("Synchronizing to selection: Calling provideSelection()") );
provideSelection();
}
}
void Scriptable::synchronizeFromSelection()
{
if( canSynchronizeSelection(ClipboardMode::Clipboard) ) {
COPYQ_LOG( QStringLiteral("Synchronizing to clipboard: Calling provideClipboard()") );
provideClipboard();
}
}
void Scriptable::setClipboardData()
{
auto data = copyWithoutInternalData(m_data);
m_proxy->setClipboardData(data);
}
void Scriptable::updateTitle()
{
m_proxy->setTitleForData(m_data);
}
void Scriptable::setTitle()
{
m_skipArguments = 1;
const auto title = arg(0);
m_proxy->setTitle(title);
}
void Scriptable::saveData()
{
const QString outputTab = getTextData(m_data, mimeOutputTab);
if ( !outputTab.isEmpty() )
saveData(outputTab);
}
QJSValue Scriptable::hasData()
{
for (auto it = m_data.constBegin(); it != m_data.constEnd(); ++it) {
const auto &format = it.key();
if ( isInternalDataFormat(format) )
continue;
auto bytes = it.value().toByteArray();
for (const auto &byte : bytes) {
const QChar c(byte);
if ( !c.isSpace() && !c.isNull() )
return true;
}
}
return false;
}
void Scriptable::showDataNotification()
{
m_proxy->showDataNotification(m_data);
}
void Scriptable::hideDataNotification()
{
m_proxy->showDataNotification(QVariantMap());
}
void Scriptable::updateClipboardData()
{
eval(R"(
if (isClipboard()) {
updateTitle();
showDataNotification();
setClipboardData();
}
)", "updateClipboardData()");
}
void Scriptable::clearClipboardData()
{
eval(R"(
if (isClipboard()) {
setTitle();
hideDataNotification();
}
)", "clearClipboardData()");
}
QJSValue Scriptable::runAutomaticCommands()
{
return runCommands(CommandType::Automatic);
}
void Scriptable::runDisplayCommands()
{
m_modifyDisplayDataOnly = true;
QEventLoop loop;
connect(this, &Scriptable::finished, &loop, [&]() {
if (m_abort == Abort::AllEvaluations)
loop.exit();
});
QTimer timer;
timer.setSingleShot(true);
timer.setInterval(0);
connect(this, &Scriptable::dataReceived, &loop, [&](const QByteArray &receivedBytes) {
if (receivedBytes == "ABORT") {
abortEvaluation(Abort::AllEvaluations);
return;
}
timer.start();
});
bool running = false;
connect(&timer, &QTimer::timeout, &loop, [&]() {
if (running)
return;
running = true;
if ( m_data.isEmpty() )
m_data = m_proxy->setDisplayData(m_actionId, m_data);
while ( !m_data.isEmpty() && runCommands(CommandType::Display) ) {
m_data = m_proxy->setDisplayData(m_actionId, m_data);
}
m_data.clear();
running = false;
});
emit receiveData();
if (m_abort == Abort::None)
loop.exec();
m_modifyDisplayDataOnly = false;
}
void Scriptable::runMenuCommandFilters()
{
QEventLoop loop;
connect(this, &Scriptable::finished, &loop, [&]() {
if (m_abort == Abort::AllEvaluations)
loop.exit();
});
QByteArray bytes;
QTimer timer;
timer.setSingleShot(true);
timer.setInterval(0);
connect(this, &Scriptable::dataReceived, &loop, [&](const QByteArray &receivedBytes) {
if (receivedBytes == "ABORT") {
abortEvaluation(Abort::AllEvaluations);
return;
}
bytes = receivedBytes;
if ( !bytes.isEmpty() )
timer.start();
});
// Avoid modifying menu filter data.
const int actionId = m_actionId;
m_actionId = -1;
const QString menuItemProperty = QStringLiteral("menuItem");
const QString enabledProperty = QStringLiteral("enabled");
bool running = false;
bool restart = false;
connect(&timer, &QTimer::timeout, &loop, [&]() {
if ( bytes.isEmpty() )
return;
if (running) {
restart = true;
return;
}
running = true;
do {
restart = false;
const int currentRun = bytes.toInt();
getActionData(actionId);
const QStringList matchCommands =
m_data.value(COPYQ_MIME_PREFIX "match-commands").toStringList();
PerformanceLogger logger( QStringLiteral("Menu item filters") );
for (int i = 0; i < matchCommands.length(); ++i) {
const auto obj = m_engine->newObject();
m_engine->globalObject().setProperty(menuItemProperty, obj);
const bool enabled = canExecuteCommandFilter(matchCommands[i]);
QVariantMap menuItem = toDataMap(obj);
menuItem[enabledProperty] = enabled && menuItem.value(enabledProperty, true).toBool();
if ( restart || !m_proxy->enableMenuItem(actionId, currentRun, i, menuItem) )
break;
}
} while (restart);
running = false;
});
emit receiveData();
if (m_abort == Abort::None)
loop.exec();
}
void Scriptable::monitorClipboard()
{
if (!verifyClipboardAccess())
return;
ClipboardMonitor monitor(
fromScriptValue<QStringList>(eval("clipboardFormatsToSave()"), m_engine) );
QEventLoop loop;
connect(this, &Scriptable::finished, &loop, &QEventLoop::quit);
connect( &monitor, &ClipboardMonitor::clipboardChanged,
this, &Scriptable::onMonitorClipboardChanged );
connect( &monitor, &ClipboardMonitor::hiddenClipboardChanged,
this, &Scriptable::onMonitorHiddenClipboardChanged );
connect( &monitor, &ClipboardMonitor::ownClipboardChanged,
this, &Scriptable::onMonitorOwnClipboardChanged );
connect( &monitor, &ClipboardMonitor::secretClipboardChanged,
this, &Scriptable::onMonitorSecretClipboardChanged );
connect( &monitor, &ClipboardMonitor::clipboardUnchanged,
this, &Scriptable::onMonitorClipboardUnchanged );
connect( &monitor, &ClipboardMonitor::synchronizeSelection,
this, &Scriptable::onSynchronizeSelection );
connect( &monitor, &ClipboardMonitor::fetchCurrentClipboardOwner,
this, &Scriptable::onFetchCurrentClipboardOwner );
connect( &monitor, &ClipboardMonitor::saveData,
m_proxy, [this](const QVariantMap &data) {
m_data = data;
eval("saveData()");
} );
monitor.startMonitoring();
setClipboardMonitorRunning(true);
loop.exec();
setClipboardMonitorRunning(false);
}
void Scriptable::provideClipboard()
{
provideClipboard(ClipboardMode::Clipboard);
}
void Scriptable::provideSelection()
{
provideClipboard(ClipboardMode::Selection);
}
QJSValue Scriptable::isClipboardMonitorRunning()
{
return ::isClipboardMonitorRunning();
}
QJSValue Scriptable::clipboardFormatsToSave()
{
if (!m_factory)
return toScriptValue(QStringList(), m_engine);
QStringList formats = m_factory->formatsToSave();
COPYQ_LOG( "Clipboard formats to save: " + formats.join(", ") );
for (const auto &command : m_proxy->automaticCommands()) {
if ( !command.input.isEmpty() && !formats.contains(command.input) ) {
COPYQ_LOG( QStringLiteral("Clipboard format to save for command \"%1\": %2")
.arg(command.name, command.input) );
formats.append(command.input);
}
}
return toScriptValue(formats, m_engine);
}
QJSValue Scriptable::styles()
{
return toScriptValue( m_proxy->styles(), m_engine );
}
void Scriptable::collectScriptOverrides()
{
m_skipArguments = 1;
auto globalObject = engine()->globalObject();
QVector<int> overrides;
if (isOverridden(globalObject, QStringLiteral("paste")))
overrides.append(ScriptOverrides::Paste);
if (isOverridden(globalObject, QStringLiteral("onItemsAdded")))
overrides.append(ScriptOverrides::OnItemsAdded);
if (isOverridden(globalObject, QStringLiteral("onItemsRemoved")))
overrides.append(ScriptOverrides::OnItemsRemoved);
if (isOverridden(globalObject, QStringLiteral("onItemsChanged")))
overrides.append(ScriptOverrides::OnItemsChanged);
if (isOverridden(globalObject, QStringLiteral("onTabSelected")))
overrides.append(ScriptOverrides::OnTabSelected);
if (isOverridden(globalObject, QStringLiteral("onItemsLoaded")))
overrides.append(ScriptOverrides::OnItemsLoaded);
m_proxy->setScriptOverrides(overrides);
}
void Scriptable::onMonitorClipboardChanged(const QVariantMap &data)
{
COPYQ_LOG("onClipboardChanged");
m_proxy->runInternalAction(data, QStringLiteral("copyq onClipboardChanged"));
}
void Scriptable::onMonitorSecretClipboardChanged(const QVariantMap &data)
{
COPYQ_LOG("onSecretClipboardChanged");
m_proxy->runInternalAction(data, QStringLiteral("copyq onSecretClipboardChanged"));
}
void Scriptable::onMonitorHiddenClipboardChanged(const QVariantMap &data)
{
COPYQ_LOG("onHiddenClipboardChanged");
m_proxy->runInternalAction(data, QStringLiteral("copyq onHiddenClipboardChanged"));
}
void Scriptable::onMonitorOwnClipboardChanged(const QVariantMap &data)
{
COPYQ_LOG("onOwnClipboardChanged");
m_proxy->runInternalAction(data, QStringLiteral("copyq onOwnClipboardChanged"));
}
void Scriptable::onMonitorClipboardUnchanged(const QVariantMap &data)
{
COPYQ_LOG("onOwnClipboardUnchanged");
m_proxy->runInternalAction(data, "copyq onClipboardUnchanged");
}
void Scriptable::onSynchronizeSelection(ClipboardMode sourceMode, uint sourceTextHash, uint targetTextHash)
{
#ifdef HAS_MOUSE_SELECTIONS
QVariantMap data;
data[COPYQ_MIME_PREFIX "source-text-hash"] = QByteArray::number(sourceTextHash);
data[COPYQ_MIME_PREFIX "target-text-hash"] = QByteArray::number(targetTextHash);
const auto command = sourceMode == ClipboardMode::Clipboard
? "copyq --clipboard-access synchronizeToSelection"
: "copyq --clipboard-access synchronizeFromSelection";
m_proxy->runInternalAction(data, command);
#else
Q_UNUSED(sourceMode)
Q_UNUSED(sourceTextHash)
Q_UNUSED(targetTextHash)
#endif
}
void Scriptable::onFetchCurrentClipboardOwner(QString *owner)
{
const QJSValue result = eval("currentClipboardOwner()");
if ( !result.isError() )
*owner = toString(result);
}
bool Scriptable::sourceScriptCommands()
{
const auto commands = m_proxy->scriptCommands();
for (const auto &command : commands) {
const auto script = QStringLiteral("(function(){%1\n;})()").arg(command.cmd);
const auto label = QStringLiteral("source@<%1>").arg(command.name);
eval(script, label);
if ( hasUncaughtException() ) {
processUncaughtException(label);
return false;
}
}
return true;
}
int Scriptable::executeArguments(const QStringList &args)
{
if ( !sourceScriptCommands() )
return CommandError;
const int exitCode = executeArgumentsSimple(args);
if (exitCode == CommandFinished)
setActionData();
// Destroy objects so destructors are run before script finishes
// (e.g. file writes are flushed or temporary files are automatically removed).
m_engine->collectGarbage();
return exitCode;
}
int Scriptable::executeArgumentsSimple(const QStringList &args)
{
/* Special arguments:
* "-" read this argument from stdin
* "--" read all following arguments without control sequences
*/
QJSValueList fnArgs;
bool readRaw = false;
for (const auto &arg : args) {
if (readRaw) {
fnArgs.append( newByteArray(arg.toUtf8()) );
} else if (arg == "--") {
readRaw = true;
} else if (arg == "-") {
fnArgs.append( input() );
} else if (arg == "-e") {
fnArgs.append("eval");
} else {
const auto unescapedArg = parseCommandLineArgument(arg);
const auto value = newByteArray( unescapedArg.toUtf8() );
fnArgs.append(value);
}
}
QString cmd;
QJSValue result;
int skipArguments = 0;
if (!fnArgs.isEmpty() && toString(fnArgs[0]) == "--clipboard-access")
++skipArguments;
auto globalObject = engine()->globalObject();
const auto evalFn = globalObject.property("eval");
QString label;
while ( skipArguments < fnArgs.size() && canContinue() && !hasUncaughtException() ) {
if ( result.isCallable() ) {
const auto arguments = fnArgs.mid(skipArguments);
if ( result.strictlyEquals(evalFn) )
globalObject.setProperty( QStringLiteral("arguments"), toScriptValue(arguments, m_engine) );
m_skipArguments = -1;
result = call( label, &result, arguments );
if (m_skipArguments == -1)
break;
skipArguments += m_skipArguments;
} else {
cmd = toString(fnArgs[skipArguments]);
label = scriptToLabel(cmd);
result = eval(cmd, label);
++skipArguments;
}
}
if ( result.isCallable() && canContinue() && !hasUncaughtException() ) {
const QString label2 = QStringLiteral("eval(arguments[%1])()").arg(skipArguments - 1);
result = call( label2, &result, fnArgs.mid(skipArguments) );
}
int exitCode;
if (m_failed) {
exitCode = CommandError;
} else if (m_abort != Abort::None) {
exitCode = CommandFinished;
} else if ( hasUncaughtException() ) {
processUncaughtException(QString());
exitCode = CommandException;
} else {
const auto message = serializeScriptValue(result, this);
print(message);
exitCode = CommandFinished;
}
return exitCode;
}
void Scriptable::processUncaughtException(const QString &cmd)
{
if ( !hasUncaughtException() )
return;
const auto exceptionName = m_uncaughtException.toString()
.remove(QRegularExpression("^Error: "))
.trimmed();
const QString backtraceText = exceptionBacktrace(m_uncaughtException, m_uncaughtExceptionStack);
const auto exceptionText = QStringLiteral("ScriptError: %3%4").arg(exceptionName, backtraceText);
// Show exception popups only if the script was launched from application.
// (avoid it if launched from command line).
if (m_actionId != -1) {
showExceptionMessage(exceptionName);
auto label = m_actionName;
if ( !cmd.isEmpty() )
label.append("::" + cmd);
if (label.isEmpty())
label = QStringLiteral("Exception in command: ");
else
label = QStringLiteral("Exception in command \"%1\": ").arg(label);
m_proxy->serverLog(label + exceptionText);
}
printError(exceptionText.toUtf8());
}
void Scriptable::showExceptionMessage(const QString &message)
{
if (!m_proxy)
return;
const auto title = m_actionName.isEmpty()
? tr("Exception")
: tr("Exception in %1").arg( quoteString(m_actionName) );
QtPrivate::QHashCombine hash;
const auto id = hash(hash(0, title), message);
const auto notificationId = QString::number(id);
m_proxy->showMessage(title, message, QString(QChar(IconCircleExclamation)), 8000, notificationId);
}
QVector<int> Scriptable::getRows() const
{
QVector<int> rows;
for ( int i = 0; i < argumentCount(); ++i ) {
int row;
if ( !toInt(argument(i), &row) )
break;
rows.append(row);
}
return rows;
}
QVector<QVariantMap> Scriptable::getItemArguments(int begin, int end, QString *error)
{
if (begin == end) {
*error = QStringLiteral("Expected item arguments");
return {};
}
const auto firstArg = argument(begin);
if (firstArg.isArray()) {
if (end - begin != 1) {
*error = QStringLiteral("Unexpected multiple item list arguments");
return {};
}
return getItemList(0, firstArg.property("length").toInt(), firstArg);
}
QVector<QVariantMap> items;
if (firstArg.toVariant().canConvert<QVariantMap>()) {
for (int i = begin; i < end; ++i)
items.append( fromScriptValue<QVariantMap>(argument(i), m_engine) );
} else if (end - begin == 1) {
QVariantMap data;
QJSValue value = argument(begin);
setTextData( &data, toString(value) );
items.append(data);
} else {
if ((end - begin) % 2 != 0) {
*error = QStringLiteral("Unexpected uneven number of mimeType/data arguments");
return {};
}
QVariantMap data;
for (int i = begin; i < end; i += 2) {
// MIME
const QString mime = toString(argument(i));
// DATA
toItemData( argument(i + 1), mime, &data );
}
items.append(data);
}
return items;
}
QVector<QVariantMap> Scriptable::getItemList(int begin, int end, const QJSValue &arguments)
{
if (end < begin)
return {};
QVector<QVariantMap> items;
items.reserve(end - begin);
for (int i = begin; i < end; ++i) {
const auto arg = arguments.property( static_cast<quint32>(i) );
if ( arg.isObject() && getByteArray(arg) == nullptr && !arg.isArray() )
items.append( fromScriptValue<QVariantMap>(arg, m_engine) );
else
items.append( createDataMap(mimeText, toString(arg)) );
}
return items;
}
QJSValue Scriptable::copy(ClipboardMode mode)
{
const int args = argumentCount();
if (args == 0) {
// Reset clipboard first.
const QString mime = COPYQ_MIME_PREFIX "invalid";
const QByteArray value = "invalid";
const QVariantMap data = createDataMap(mime, value);
m_proxy->setClipboard(data, mode);
m_proxy->copyFromCurrentWindow();
// Wait for clipboard to be set.
for (int i = 0; i < 10; ++i) {
if ( getClipboardData(mime) != value )
return true;
waitFor(5 + i * 25);
}
return throwError( tr("Failed to copy to clipboard!") );
}
QString error;
const QVector<QVariantMap> items = getItemArguments(0, args, &error);
if ( !error.isEmpty() )
return throwError(error);
if (items.size() != 1)
return throwError(QStringLiteral("Expected single item"));
m_proxy->setClipboard(items[0], mode);
return true;
}
void Scriptable::abortEvaluation(Abort abort)
{
m_abort = abort;
throwError("Evaluation aborted");
if (m_abort == Abort::AllEvaluations)
m_proxy->clientDisconnected();
else
m_proxy->abortEvaluation();
emit finished();
}
QJSValue Scriptable::changeItem(bool create)
{
int row;
int args = argumentCount();
int i;
// [ROW]
if ( toInt(argument(0), &row) ) {
i = 1;
} else {
row = 0;
i = 0;
}
QString error;
const VariantMapList items{getItemArguments(i, args, &error)};
if ( !error.isEmpty() )
return throwError(error);
if (create) {
error = m_proxy->browserInsert(m_tabName, row, items);
if ( !error.isEmpty() )
return throwError(error);
} else {
error = m_proxy->browserChange(m_tabName, row, items);
if ( !error.isEmpty() )
return throwError(error);
}
return QJSValue();
}
void Scriptable::nextToClipboard(int where)
{
QVariantMap data = m_proxy->nextItem(m_tabName, where);
if (data.isEmpty())
return;
m_proxy->setClipboard(data, ClipboardMode::Clipboard);
#ifdef HAS_MOUSE_SELECTIONS
m_proxy->setClipboard(data, ClipboardMode::Selection);
#endif
}
void Scriptable::editContent(
int editRow, const QString &format, const QByteArray &content, bool changeClipboard)
{
if ( m_proxy->browserOpenEditor(m_tabName, editRow, format, content, changeClipboard) )
return;
m_proxy->showBrowser(m_tabName);
if (editRow >= 0) {
m_proxy->browserSetCurrent(m_tabName, editRow);
m_proxy->browserEditRow(m_tabName, editRow, format);
} else {
m_proxy->browserEditNew(m_tabName, format, content, changeClipboard);
}
}
QJSValue Scriptable::screenshot(bool select)
{
m_skipArguments = 2;
const auto format = arg(0, "png");
const auto screen = arg(1);
const auto imageData = m_proxy->screenshot(format, screen, select);
if ( imageData.isEmpty() ) {
QString error = "Failed to grab screenshot";
if ( !screen.isEmpty() ) {
const auto screenNames = m_proxy->screenNames();
error.append( " (valid screen names are " + screenNames.join(", ") + ")" );
}
throwError(error);
return QJSValue();
}
return newByteArray(imageData);
}
QJSValue Scriptable::eval(const QString &script, const QString &label)
{
m_stack.prepend(QStringLiteral("eval:") + label);
COPYQ_LOG_VERBOSE( QStringLiteral("Stack push: %1").arg(m_stack.join('|')) );
const auto result = m_safeEval.call({QJSValue(script)});
m_stack.pop_front();
COPYQ_LOG_VERBOSE( QStringLiteral("Stack pop: %1").arg(m_stack.join('|')) );
if (m_abort != Abort::None) {
clearExceptions();
if (m_abort == Abort::AllEvaluations)
abortEvaluation(Abort::AllEvaluations);
else
m_abort = Abort::None;
return QJSValue();
}
return result;
}
void Scriptable::setActionId(int actionId)
{
m_actionId = actionId;
getActionData();
}
void Scriptable::setActionName(const QString &actionName)
{
m_actionName = actionName;
}
QJSValue Scriptable::eval(const QString &script)
{
return eval(script, scriptToLabel(script));
}
bool Scriptable::runAction(Action *action)
{
if (!canContinue())
return false;
// Shortcut to run script in current Scriptable
// instead of spawning new process.
const auto &cmd = action->command();
const auto cmd1 = cmd.value(0).value(0);
if ( cmd.size() == 1 && cmd[0].size() == 1
&& cmd1.size() >= 2
&& cmd1[0] == "copyq"
&& (!cmd1[1].startsWith("-") || cmd1[1] == "-e") )
{
const auto oldInput = m_input;
m_input = newByteArray(action->input());
const auto oldAction = m_action;
m_action = action;
const auto exitCode = executeArgumentsSimple(cmd1.mid(1));
action->setExitCode(exitCode);
m_failed = false;
clearExceptions();
if (m_abort == Abort::AllEvaluations)
abortEvaluation(Abort::AllEvaluations);
else
m_abort = Abort::None;
m_action = oldAction;
m_input = oldInput;
return true;
}
// Update data for the new action.
setActionData();
action->setWorkingDirectory( getCurrentPath() );
QEventLoop loop;
connect(action, &Action::actionFinished, &loop, &QEventLoop::quit);
connect(this, &Scriptable::finished, &loop, &QEventLoop::quit);
action->start();
loop.exec();
if ( action->isRunning() && !action->waitForFinished(5000) ) {
action->terminate();
return false;
}
// Data could have changed so refetch them.
getActionData();
return true;
}
bool Scriptable::runCommands(CommandType::CommandType type)
{
Q_ASSERT(type == CommandType::Automatic || type == CommandType::Display);
const auto label = type == CommandType::Automatic
? "Automatic command \"%1\": %2"
: "Display command \"%1\": %2";
auto commands = type == CommandType::Automatic
? m_proxy->automaticCommands()
: m_proxy->displayCommands();
const QString tabName = getTextData(m_data, mimeCurrentTab);
for (auto &command : commands) {
PerformanceLogger logger( QStringLiteral("Command \"%1\"").arg(command.name) );
if ( command.outputTab.isEmpty() )
command.outputTab = tabName;
QStringList arguments;
if ( !canExecuteCommand(command, &arguments) )
continue;
if ( canContinue() && !command.cmd.isEmpty() ) {
Action action;
action.setCommand(command.cmd, arguments);
action.setInputWithFormat(m_data, command.input);
action.setName(command.name);
action.setData(m_data);
// FIXME: Handle automatic and display command output.
//action.setOutputFormat(command.output);
//action.setItemSeparator(QRegularExpression(command.sep));
//action.setOutputTab(command.outputTab);
if ( !runAction(&action) && canContinue() ) {
throwError( QString(label).arg(command.name, "Failed to start") );
return false;
}
}
if (!canContinue()) {
COPYQ_LOG( QString(label).arg(command.name, "Interrupted") );
return false;
}
if ( type == CommandType::Automatic ) {
if ( !command.tab.isEmpty() ) {
COPYQ_LOG( QString(label).arg(command.name, "Saving to tab: " + command.tab) );
saveData(command.tab);
}
if ( command.remove || command.transform || m_data.contains(mimeIgnore) ) {
COPYQ_LOG( QString(label).arg(command.name, "Ignoring data") );
return false;
}
}
COPYQ_LOG_VERBOSE( QString(label).arg(command.name, "Finished") );
}
return true;
}
bool Scriptable::canExecuteCommand(const Command &command, QStringList *arguments)
{
// Verify that data for given MIME is available.
if ( !command.input.isEmpty() ) {
if (command.input == mimeItems || command.input == "!OUTPUT") {
// Disallow applying action that takes serialized item more times.
if ( m_data.contains(command.output) )
return false;
} else if ( !m_data.contains(command.input) ) {
return false;
}
}
const QString text = getTextData(m_data);
arguments->append(text);
// Verify that and text matches given regexp.
if ( !command.re.pattern().isEmpty() ) {
QRegularExpressionMatchIterator it = command.re.globalMatch(text);
if ( !it.isValid() || !it.hasNext() )
return false;
while (it.hasNext())
arguments->append( it.next().capturedTexts().mid(1) );
}
// Verify that window title matches given regexp.
if ( !command.wndre.pattern().isEmpty() && !getTextData(m_data, mimeWindowTitle).contains(command.wndre) )
return false;
return canExecuteCommandFilter(command.matchCmd);
}
bool Scriptable::canExecuteCommandFilter(const QString &matchCommand)
{
if ( matchCommand.isEmpty() )
return true;
Action action;
const QString text = getTextData(m_data);
action.setInput(text.toUtf8());
action.setData(m_data);
const QString arg = getTextData(action.input());
action.setCommand(matchCommand, QStringList(arg));
return runAction(&action) && action.exitCode() == 0;
}
bool Scriptable::verifyClipboardAccess()
{
if ( isGuiApplication() )
return true;
throwError("Cannot access system clipboard with QCoreApplication");
return false;
}
void Scriptable::provideClipboard(ClipboardMode mode)
{
if (!verifyClipboardAccess())
return;
const auto owner = makeClipboardOwnerData();
m_data.insert(mimeOwner, owner);
const auto type = mode == ClipboardMode::Clipboard ? "clipboard" : "selection";
ClipboardSpy spy(mode, owner);
connect( this, &Scriptable::finished, &spy, &ClipboardSpy::stop );
if ( !spy.setClipboardData(m_data) ) {
if (m_abort != Abort::None)
return;
log( QStringLiteral("Failed to provide %1").arg(type), LogWarning );
return;
}
if (m_abort != Abort::None)
return;
COPYQ_LOG( QStringLiteral("Started providing %1").arg(type) );
spy.wait(-1, 8000);
COPYQ_LOG( QStringLiteral("Finished providing %1").arg(type) );
}
void Scriptable::insert(int argumentsEnd)
{
int row;
if ( !toInt(argument(0), &row) ) {
throwError(argumentError());
return;
}
insert(row, 1, argumentsEnd);
}
void Scriptable::insert(int row, int argumentsBegin, int argumentsEnd)
{
m_skipArguments = argumentsEnd;
const VariantMapList items{getItemList(argumentsBegin, argumentsEnd, argumentsArray())};
if ( const auto error = m_proxy->browserInsert(m_tabName, row, items); !error.isEmpty() )
throwError(error);
}
QStringList Scriptable::arguments()
{
QStringList args;
args.reserve( argumentCount() );
for (int i = 0; i < argumentCount(); ++i)
args.append( arg(i) );
return args;
}
QVariantList Scriptable::argumentsAsVariants()
{
QVariantList args;
args.reserve( argumentCount() );
for (int i = 0; i < argumentCount(); ++i)
args.append( toVariant(argument(i)) );
return args;
}
void Scriptable::print(const QByteArray &message)
{
if (m_action) {
m_action->appendOutput(message);
} else if ( canUseStandardOutput() ) {
QFile f;
f.open(stdout, QIODevice::WriteOnly);
f.write(message);
}
}
void Scriptable::printError(const QByteArray &message)
{
if (m_action) {
m_action->appendErrorOutput(message);
} else if ( canUseStandardOutput() ) {
QFile f;
f.open(stderr, QIODevice::WriteOnly);
f.write(message);
if ( !message.endsWith('\n') )
f.write("\n");
}
}
void Scriptable::getActionData()
{
getActionData(m_actionId);
}
void Scriptable::getActionData(int actionId)
{
if (actionId != -1)
m_data = m_oldData = m_proxy->getActionData(actionId);
}
void Scriptable::setActionData()
{
if (m_actionId != -1 && m_oldData != m_data) {
m_proxy->setActionData(m_actionId, m_data);
m_oldData = m_data;
}
}
QByteArray Scriptable::getClipboardData(const QString &mime, ClipboardMode mode)
{
return m_proxy->getClipboardData(mime, mode);
}
bool Scriptable::hasClipboardFormat(const QString &mime, ClipboardMode mode)
{
return m_proxy->hasClipboardFormat(mime, mode);
}
bool Scriptable::canSynchronizeSelection(ClipboardMode targetMode)
{
#ifdef HAS_MOUSE_SELECTIONS
if (!verifyClipboardAccess())
return false;
// Make sure a clipboard instance is created so as to monitor any changes;
clipboardInstance();
SleepTimer tMin(50);
// Avoid changing clipboard after a text is selected just before it's copied
// with a keyboard shortcut.
SleepTimer t(5000);
while ( QGuiApplication::queryKeyboardModifiers() != Qt::NoModifier ) {
if ( !t.sleep() && !canContinue() ) {
COPYQ_LOG("Sync: Cancelled - keyboard modifiers still being held");
return false;
}
}
const auto sourceMode = targetMode == ClipboardMode::Selection ? ClipboardMode::Clipboard : ClipboardMode::Selection;
// Wait at least few milliseconds before synchronization
// to avoid overriding just changed clipboard/selection.
while ( tMin.sleep() ) {}
// Stop if the clipboard/selection text already changed again.
const QVariantMap sourceData = clipboardInstance()->data(
sourceMode, {mimeTextUtf8, mimeText, mimeUriList});
QByteArray source;
if (!sourceData.isEmpty()) {
source = sourceData.value(mimeText).toByteArray();
const QString owner = sourceData.value(mimeOwner).toString();
if ( owner.isEmpty() && !source.isEmpty() ) {
const auto sourceTextHash = m_data.value(COPYQ_MIME_PREFIX "source-text-hash").toByteArray().toUInt();
const uint newSourceTextHash = qHash(source);
if (sourceTextHash != newSourceTextHash) {
COPYQ_LOG("Sync: Cancelled - source text changed");
return false;
}
}
} else {
COPYQ_LOG("Sync: Failed to fetch source data");
}
const QVariantMap targetData = clipboardInstance()->data(
targetMode, {mimeText});
if (!targetData.isEmpty()) {
const QByteArray target = targetData.value(mimeText).toByteArray();
const QString owner = targetData.value(mimeOwner).toString();
if ( owner.isEmpty() && !target.isEmpty() ) {
const auto targetTextHash = m_data.value(COPYQ_MIME_PREFIX "target-text-hash").toByteArray().toUInt();
const uint newTargetTextHash = qHash(target);
if (targetTextHash != newTargetTextHash) {
COPYQ_LOG("Sync: Cancelled - target text changed");
return false;
}
}
// Stop if the clipboard and selection text is already synchronized
// or user selected text and copied it to clipboard.
if (!sourceData.isEmpty() && source == target) {
COPYQ_LOG("Sync: Cancelled - target text is already same as source");
return false;
}
} else {
COPYQ_LOG("Sync: Failed to fetch target data");
}
if (m_abort != Abort::None) {
COPYQ_LOG("Sync: Aborting");
return false;
}
m_data = sourceData;
return true;
#else
Q_UNUSED(targetMode)
return false;
#endif
}
void Scriptable::saveData(const QString &tab)
{
const auto data = copyWithoutInternalData(m_data);
const auto clipboardMode = isClipboardData(m_data)
? ClipboardMode::Clipboard
: ClipboardMode::Selection;
m_proxy->saveData(tab, data, clipboardMode);
}
QJSValue Scriptable::readInput()
{
// Try to read stdin in a non-blocking way.
class InputReaderThread final : public QThread {
public:
QByteArray input;
protected:
void run() override {
QFile in;
in.open(stdin, QIODevice::ReadOnly);
input = in.readAll();
}
};
auto inputReaderThread = new InputReaderThread;
QEventLoop loop;
connect(inputReaderThread, &QThread::finished, &loop, &QEventLoop::quit);
connect(this, &Scriptable::finished, &loop, &QEventLoop::quit);
inputReaderThread->start();
loop.exec();
if ( inputReaderThread->isRunning() ) {
inputReaderThread->terminate();
COPYQ_LOG("Terminating input reader");
if ( !inputReaderThread->wait(4000) )
COPYQ_LOG("Failed to terminate input reader");
return QJSValue();
}
inputReaderThread->deleteLater();
COPYQ_LOG(QStringLiteral("Read Input %1 bytes").arg(inputReaderThread->input.length()));
return newByteArray(inputReaderThread->input);
}
PlatformClipboard *Scriptable::clipboardInstance()
{
if (m_clipboard == nullptr)
m_clipboard = platformNativeInterface()->clipboard();
return m_clipboard.get();
}
void Scriptable::interruptibleSleep(int msec)
{
if ( !canContinue() )
return;
QEventLoop loop;
connect(this, &Scriptable::finished, &loop, &QEventLoop::quit);
QTimer t;
t.setTimerType(Qt::PreciseTimer);
t.setInterval(msec);
connect(&t, &QTimer::timeout, &loop, &QEventLoop::quit);
t.start();
loop.exec();
}
NetworkReply *Scriptable::networkGetHelper()
{
m_skipArguments = 1;
const QString url = arg(0);
return NetworkReply::get(url, this);
}
NetworkReply *Scriptable::networkPostHelper()
{
m_skipArguments = 2;
const QString url = arg(0);
const QByteArray postData = makeByteArray(argument(1));
return NetworkReply::post(url, postData, this);
}
QJSValue Scriptable::newQObject(QObject *obj, const QJSValue &prototype) const
{
auto value = m_engine->newQObject(obj);
value.setPrototype(prototype);
return value;
}
void Scriptable::installObject(QObject *fromObj, const QMetaObject *metaObject, QJSValue &toObject)
{
const auto from = m_engine->newQObject(fromObj);
for (int i = 0; i < metaObject->methodCount(); ++i) {
const QMetaMethod slot = metaObject->method(i);
if ( slot.methodType() != QMetaMethod::Slot )
continue;
if ( slot.access() != QMetaMethod::Public )
continue;
if ( slot.parameterCount() != 0 )
continue;
const QLatin1String name( slot.name() );
const bool hasByteArrayReturnType = slot.returnType() == QMetaType::QByteArray;
// Allow passing variable number of arguments to scriptable methods
// and handle exceptions.
const auto v = hasByteArrayReturnType
? m_createFnB.call({from, name})
: m_createFn.call({from, name});
if ( v.isError() ) {
log( QStringLiteral("Exception while wrapping %1.%2: %3").arg(fromObj->objectName(), name, v.toString()), LogError );
Q_ASSERT(false);
} else {
toObject.setProperty(name, v);
}
}
for (int i = 0; i < metaObject->propertyCount(); ++i) {
const QMetaProperty prop = metaObject->property(i);
const QLatin1String name( prop.name() );
const auto v = m_createProperty.call({toObject, name, from});
if ( v.isError() ) {
log( QStringLiteral("Exception while adding property %1.%2: %3").arg(fromObj->objectName(), name, v.toString()), LogError );
Q_ASSERT(false);
}
}
}
NetworkReply *NetworkReply::get(const QString &url, Scriptable *scriptable)
{
return new NetworkReply(url, QByteArray(), scriptable);
}
NetworkReply *NetworkReply::post(const QString &url, const QByteArray &postData, Scriptable *scriptable)
{
return new NetworkReply(url, postData, scriptable);
}
NetworkReply::~NetworkReply()
{
if (m_reply)
m_reply->deleteLater();
}
QJSValue NetworkReply::data()
{
if ( !m_data.isUndefined() )
return m_data;
if ( !m_reply->isFinished() && m_scriptable->canContinue() ) {
QEventLoop loop;
connect(m_scriptable, &Scriptable::finished, &loop, &QEventLoop::quit);
connect(m_reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
}
if ( !m_reply->isFinished() )
return QJSValue();
m_data = m_scriptable->newByteArray(m_rawData);
return m_data;
}
QJSValue NetworkReply::error()
{
data();
if (m_reply->error() != QNetworkReply::NoError)
return m_reply->errorString();
return QJSValue();
}
QJSValue NetworkReply::status()
{
data();
const QVariant v = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
if (v.isValid())
return v.toInt();
return QJSValue();
}
QJSValue NetworkReply::redirect()
{
data();
const QVariant v = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (v.isValid())
return v.toUrl().resolved(m_reply->url()).toString();
return QJSValue();
}
QJSValue NetworkReply::headers()
{
data();
QJSValue headers = m_scriptable->engine()->newArray();
int i = 0;
for ( const auto &header : m_reply->rawHeaderList() ) {
QJSValue pair = m_scriptable->engine()->newArray();
pair.setProperty( 0, m_scriptable->newByteArray(header) );
pair.setProperty( 1, m_scriptable->newByteArray(m_reply->rawHeader(header)) );
headers.setProperty( static_cast<quint32>(i), pair );
++i;
}
return headers;
}
QJSValue NetworkReply::finished()
{
return m_reply->isFinished();
}
NetworkReply::NetworkReply(const QString &url, const QByteArray &postData, Scriptable *scriptable)
: QObject(scriptable)
, m_scriptable(scriptable)
, m_manager(new QNetworkAccessManager(this))
, m_reply(nullptr)
{
if (postData.isEmpty())
m_reply = m_manager->get(QNetworkRequest(url));
else
m_reply = m_manager->post(QNetworkRequest(url), postData);
connect(m_reply, &QNetworkReply::readyRead, this, [this](){
const qint64 available = m_reply->bytesAvailable();
m_rawData.append( m_reply->read(available) );
});
const qint64 available = m_reply->bytesAvailable();
m_rawData.append( m_reply->read(available) );
}
QJSValue NetworkReply::toScriptValue()
{
if ( m_self.isUndefined() )
m_self = m_scriptable->engine()->newQObject(this);
return m_self;
}
ScriptablePlugins::ScriptablePlugins(Scriptable *scriptable, ItemFactory *factory)
: QObject(scriptable)
, m_scriptable(scriptable)
, m_factory(factory)
{
}
QJSValue ScriptablePlugins::load(const QString &name)
{
const auto it = m_plugins.find(name);
if (it != std::end(m_plugins))
return it.value();
auto obj = m_factory->scriptableObject(name);
if (!obj) {
m_scriptable->throwError(
QStringLiteral("Plugin \"%1\" is not installed").arg(name) );
return QJSValue();
}
auto plugin = m_scriptable->engine()->newObject();
m_plugins.insert(name, plugin);
m_scriptable->installObject(obj, obj->metaObject(), plugin);
obj->setScriptable(m_scriptable);
obj->start();
return plugin;
}
| 102,244
|
C++
|
.cpp
| 3,152
| 26.516497
| 136
| 0.646916
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,181
|
scriptablebytearray.cpp
|
hluk_CopyQ/src/scriptable/scriptablebytearray.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "scriptablebytearray.h"
#include "common/textdata.h"
#include <QJSEngine>
#include <QJSValue>
ScriptableByteArray::ScriptableByteArray(const QByteArray &bytes)
: m_self(bytes)
{
}
ScriptableByteArray::ScriptableByteArray(const QString &text)
: m_self(text.toUtf8())
{
}
ScriptableByteArray::ScriptableByteArray(const QVariant &value)
: m_variant(value)
{
}
ScriptableByteArray::ScriptableByteArray(int size)
: m_self(size, /*ch=*/0)
{
}
ScriptableByteArray::ScriptableByteArray(const ScriptableByteArray &other)
: QObject()
, m_self(other.m_self)
, m_variant(other.m_variant)
{
}
void ScriptableByteArray::chop(int n)
{
self().chop(n);
}
bool ScriptableByteArray::equals(const QJSValue &other)
{
const auto byteArray = engine()->fromScriptValue<ScriptableByteArray*>(other);
return byteArray && self() == *byteArray->data();
}
QJSValue ScriptableByteArray::left(int len)
{
return newByteArray( self().left(len) );
}
QJSValue ScriptableByteArray::mid(int pos, int len)
{
return newByteArray( self().mid(pos, len) );
}
QJSValue ScriptableByteArray::remove(int pos, int len)
{
return newByteArray( self().remove(pos, len) );
}
QJSValue ScriptableByteArray::right(int len)
{
return newByteArray( self().right(len) );
}
QJSValue ScriptableByteArray::simplified()
{
return newByteArray( self().simplified() );
}
QJSValue ScriptableByteArray::toBase64()
{
return newByteArray( self().toBase64() );
}
QJSValue ScriptableByteArray::toLower()
{
return newByteArray( self().toLower() );
}
QJSValue ScriptableByteArray::toUpper()
{
return newByteArray( self().toUpper() );
}
QJSValue ScriptableByteArray::trimmed()
{
return newByteArray( self().trimmed() );
}
void ScriptableByteArray::truncate(int pos)
{
self().truncate(pos);
}
QJSValue ScriptableByteArray::valueOf()
{
return toString();
}
int ScriptableByteArray::size()
{
return self().size();
}
QString ScriptableByteArray::toString()
{
return getTextData(self());
}
QString ScriptableByteArray::toLatin1String()
{
return QString::fromLatin1(self());
}
QJSValue ScriptableByteArray::length()
{
return static_cast<int>(self().length());
}
void ScriptableByteArray::setLength(QJSValue size)
{
self().resize(size.toInt());
}
QJSEngine *ScriptableByteArray::engine() const
{
return qjsEngine(this);
}
QJSValue ScriptableByteArray::newByteArray(const QByteArray &bytes) const
{
return engine()->newQObject( new ScriptableByteArray(bytes) );
}
QByteArray &ScriptableByteArray::self()
{
// Convert lazily to QByteArray from QVariant when needed.
// This avoids expensive conversion from DataFile type.
if (m_variant.isValid()) {
m_self = m_variant.toByteArray();
m_variant.clear();
}
return m_self;
}
const QByteArray *getByteArray(const QJSValue &value)
{
const auto obj1 = value.toQObject();
const auto obj = qobject_cast<ScriptableByteArray*>(obj1);
return obj ? obj->data() : nullptr;
}
QByteArray toByteArray(const QJSValue &value)
{
const auto byteArray = qobject_cast<ScriptableByteArray*>(value.toQObject());
if (byteArray)
return *byteArray->data();
const QVariant variant = value.toVariant();
if (variant.canConvert<QByteArray>())
return variant.toByteArray();
return value.toString().toUtf8();
}
QString toString(const QJSValue &value)
{
const QByteArray *bytes = getByteArray(value);
return (bytes == nullptr) ? value.toString() : getTextData(*bytes);
}
| 3,596
|
C++
|
.cpp
| 139
| 23.151079
| 82
| 0.738165
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,182
|
scriptableproxy.cpp
|
hluk_CopyQ/src/scriptable/scriptableproxy.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "scriptableproxy.h"
#include "common/action.h"
#include "common/appconfig.h"
#include "common/command.h"
#include "common/commandstatus.h"
#include "common/commandstore.h"
#include "common/common.h"
#include "common/config.h"
#include "common/contenttype.h"
#include "common/display.h"
#include "common/log.h"
#include "common/mimetypes.h"
#include "common/sleeptimer.h"
#include "common/textdata.h"
#include "gui/clipboardbrowser.h"
#include "gui/filedialog.h"
#include "gui/iconfactory.h"
#include "gui/icons.h"
#include "gui/mainwindow.h"
#include "gui/notification.h"
#include "gui/pixelratio.h"
#include "gui/screen.h"
#include "gui/selectiondata.h"
#include "gui/tabicons.h"
#include "gui/traymenu.h"
#include "gui/windowgeometryguard.h"
#include "item/serialize.h"
#include "platform/platformnativeinterface.h"
#include "platform/platformwindow.h"
#include <QDialog>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QApplication>
#include <QBuffer>
#include <QDataStream>
#include <QCheckBox>
#include <QComboBox>
#include <QCursor>
#include <QDateTimeEdit>
#include <QDesktopServices>
#include <QDialogButtonBox>
#include <QFile>
#include <QFileInfo>
#include <QFileDialog>
#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QMetaMethod>
#include <QMetaType>
#include <QMimeData>
#include <QPainter>
#include <QPaintEvent>
#include <QPen>
#include <QPixmap>
#include <QPushButton>
#include <QScreen>
#include <QShortcut>
#include <QSpinBox>
#include <QStyleFactory>
#include <QTextEdit>
#include <QUrl>
#ifdef HAS_TESTS
# include <QTest>
#endif
#include <type_traits>
namespace {
const quint32 serializedFunctionCallMagicNumber = 0x58746908;
const quint32 serializedFunctionCallVersion = 2;
void registerMetaTypes() {
static bool registered = false;
if (registered)
return;
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
qRegisterMetaType<QPointer<QWidget>>("QPointer<QWidget>");
qRegisterMetaTypeStreamOperators<ClipboardMode>("ClipboardMode");
qRegisterMetaTypeStreamOperators<Command>("Command");
qRegisterMetaTypeStreamOperators<NamedValueList>("NamedValueList");
qRegisterMetaTypeStreamOperators<NotificationButtonList>("NotificationButtonList");
qRegisterMetaTypeStreamOperators<QVector<int>>("QVector<int>");
qRegisterMetaTypeStreamOperators<QVector<Command>>("QVector<Command>");
qRegisterMetaTypeStreamOperators<VariantMapList>("VariantMapList");
qRegisterMetaTypeStreamOperators<KeyboardModifierList>("KeyboardModifierList");
#else
qRegisterMetaType<QPointer<QWidget>>("QPointer<QWidget>");
qRegisterMetaType<ClipboardMode>("ClipboardMode");
qRegisterMetaType<Command>("Command");
qRegisterMetaType<NamedValueList>("NamedValueList");
qRegisterMetaType<NotificationButtonList>("NotificationButtonList");
qRegisterMetaType<QVector<int>>("QVector<int>");
qRegisterMetaType<QVector<Command>>("QVector<Command>");
qRegisterMetaType<VariantMapList>("VariantMapList");
qRegisterMetaType<KeyboardModifierList>("KeyboardModifierList");
#endif
registered = true;
}
template<typename Predicate>
void selectionRemoveIf(QList<QPersistentModelIndex> *indexes, Predicate predicate)
{
indexes->erase(
std::remove_if(indexes->begin(), indexes->end(), predicate),
indexes->end());
}
void selectionRemoveInvalid(QList<QPersistentModelIndex> *indexes)
{
selectionRemoveIf(
indexes,
[](const QPersistentModelIndex &index){
return !index.isValid();
});
}
} // namespace
#define BROWSER(tabName, call) \
ClipboardBrowser *c = fetchBrowser(tabName); \
if (c) \
(c->call)
#define STR(str) str
#define INVOKE_(function, arguments, functionCallId) do { \
static const auto f = FunctionCallSerializer(QByteArrayLiteral(STR(#function))).withSlotArguments arguments; \
const auto args = f.argumentList arguments; \
emit sendMessage(f.serialize(functionCallId, args), CommandFunctionCall); \
} while(false)
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
# define CHECK_STREAM_OPERATORS(CALL) \
static constexpr auto metaType = QMetaType::fromType<Result>(); \
COPYQ_LOG_VERBOSE( \
QStringLiteral("%1 invoking: %2 " CALL)\
.arg(m_wnd ? "Server" : "Client") \
.arg(metaType.name())); \
Q_ASSERT(metaType.hasRegisteredDataStreamOperators())
#else
# define CHECK_STREAM_OPERATORS(CALL) \
if ( hasLogLevel(LogTrace) ) { \
static const auto metaTypeName = QMetaType::typeName(qMetaTypeId<Result>()); \
COPYQ_LOG_VERBOSE( \
QStringLiteral("%1 invoking: %2 " CALL)\
.arg(m_wnd ? "Server" : "Client") \
.arg(metaTypeName) \
); \
}
#endif
#define INVOKE(FUNCTION, ARGUMENTS) do { \
using Result = decltype(FUNCTION ARGUMENTS); \
CHECK_STREAM_OPERATORS(STR(#FUNCTION #ARGUMENTS)); \
if (!m_wnd) { \
const auto functionCallId = ++m_lastFunctionCallId; \
INVOKE_(FUNCTION, ARGUMENTS, functionCallId); \
const auto result = waitForFunctionCallFinished(functionCallId); \
return result.value<Result>(); \
} \
} while(false)
#define INVOKE2(FUNCTION, ARGUMENTS) do { \
if (!m_wnd) { \
const auto functionCallId = ++m_lastFunctionCallId; \
INVOKE_(FUNCTION, ARGUMENTS, functionCallId); \
waitForFunctionCallFinished(functionCallId); \
return; \
} \
} while(false)
Q_DECLARE_METATYPE(QFile*)
QDataStream &operator<<(QDataStream &out, const NotificationButtonList &list)
{
out << list.items.size();
for (const auto &button : list.items)
out << button.name << button.script << button.data;
Q_ASSERT(out.status() == QDataStream::Ok);
return out;
}
QDataStream &operator>>(QDataStream &in, NotificationButtonList &list)
{
decltype(list.items.size()) size;
in >> size;
list.items.reserve(size);
for (int i = 0; i < size; ++i) {
NotificationButton button;
in >> button.name >> button.script >> button.data;
list.items.append(button);
}
Q_ASSERT(in.status() == QDataStream::Ok);
return in;
}
QDataStream &operator<<(QDataStream &out, const NamedValueList &list)
{
out << list.items.size();
for (const auto &item : list.items)
out << item.name << item.value;
Q_ASSERT(out.status() == QDataStream::Ok);
return out;
}
QDataStream &operator>>(QDataStream &in, NamedValueList &list)
{
decltype(list.items.size()) size;
in >> size;
list.items.reserve(size);
for (int i = 0; i < size; ++i) {
NamedValue item;
in >> item.name >> item.value;
list.items.append(item);
}
Q_ASSERT(in.status() == QDataStream::Ok);
return in;
}
QDataStream &operator<<(QDataStream &out, const VariantMapList &items)
{
out << items.items;
Q_ASSERT(out.status() == QDataStream::Ok);
return out;
}
QDataStream &operator>>(QDataStream &in, VariantMapList &items)
{
in >> items.items;
Q_ASSERT(in.status() == QDataStream::Ok);
return in;
}
QDataStream &operator<<(QDataStream &out, ClipboardMode mode)
{
const int modeId = static_cast<int>(mode);
out << modeId;
Q_ASSERT(out.status() == QDataStream::Ok);
return out;
}
QDataStream &operator>>(QDataStream &in, ClipboardMode &mode)
{
int modeId;
in >> modeId;
Q_ASSERT(in.status() == QDataStream::Ok);
mode = static_cast<ClipboardMode>(modeId);
return in;
}
QDataStream &operator<<(QDataStream &out, KeyboardModifierList value)
{
return out << static_cast<int>(value.items);
}
QDataStream &operator>>(QDataStream &in, KeyboardModifierList &value)
{
int valueInt;
in >> valueInt;
Q_ASSERT(in.status() == QDataStream::Ok);
value.items = static_cast<Qt::KeyboardModifiers>(valueInt);
return in;
}
namespace {
const char propertyWidgetName[] = "CopyQ_widget_name";
const char propertyWidgetProperty[] = "CopyQ_widget_property";
struct InputDialog {
QPointer<QDialog> dialog;
QVariant defaultChoice; /// Default text for list widgets.
};
class FunctionCallSerializer final {
public:
explicit FunctionCallSerializer(QByteArray functionName)
: m_slotName(std::move(functionName))
{
}
template<typename ...Ts>
FunctionCallSerializer &withSlotArguments(Ts... arguments)
{
QByteArray args;
for (const auto argType : std::initializer_list<const char *>{ argumentType(arguments)... }) {
args.append(argType);
args.append(',');
}
args.chop(1);
setSlotArgumentTypes(args);
return *this;
}
QByteArray serialize(int functionCallId, const QVector<QVariant> args) const
{
QByteArray bytes;
QDataStream stream(&bytes, QIODevice::WriteOnly);
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
stream.setVersion(QDataStream::Qt_6_0);
#else
stream.setVersion(QDataStream::Qt_5_0);
#endif
stream << serializedFunctionCallMagicNumber << serializedFunctionCallVersion
<< functionCallId << m_slotName << args;
return bytes;
}
template<typename ...Ts>
static QVector<QVariant> argumentList(Ts... arguments)
{
return { QVariant::fromValue(arguments)... };
}
template<typename T>
static const char *argumentType(const T &)
{
if ( std::is_same<QVariant, T>::value )
return "QVariant";
return QMetaType::typeName(qMetaTypeId<T>());
}
private:
void setSlotArgumentTypes(const QByteArray &args)
{
m_slotName += "(" + args + ")";
const int slotIndex = ScriptableProxy::staticMetaObject.indexOfSlot(m_slotName);
if (slotIndex == -1) {
log("Failed to find scriptable proxy slot: " + m_slotName, LogError);
Q_ASSERT(false);
}
}
QByteArray m_slotName;
};
class ScreenshotRectWidget final : public QLabel {
public:
explicit ScreenshotRectWidget(const QPixmap &pixmap)
{
setWindowFlags(Qt::Widget | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
setCursor(Qt::CrossCursor);
setPixmap(pixmap);
}
void paintEvent(QPaintEvent *ev) override
{
QLabel::paintEvent(ev);
if (selectionRect.isValid()) {
QPainter p(this);
const auto w = pointsToPixels(1, this);
p.setPen(QPen(Qt::white, w));
p.drawRect(selectionRect);
p.setPen(QPen(Qt::black, w));
p.drawRect(selectionRect.adjusted(-w, -w, w, w));
}
}
void keyPressEvent(QKeyEvent *ev) override
{
QWidget::keyPressEvent(ev);
hide();
}
void mousePressEvent(QMouseEvent *ev) override
{
if ( ev->button() == Qt::LeftButton ) {
m_pos = ev->pos();
selectionRect.setTopLeft(m_pos);
update();
} else {
hide();
}
}
void mouseReleaseEvent(QMouseEvent *) override
{
hide();
}
void mouseMoveEvent(QMouseEvent *ev) override
{
if ( !ev->buttons().testFlag(Qt::LeftButton) )
return;
const auto pos = ev->pos();
// Types need to be explicitly specified because minmax() returns pair of references.
const std::pair<int,int> x = std::minmax(pos.x(), m_pos.x());
const std::pair<int,int> y = std::minmax(pos.y(), m_pos.y());
selectionRect = QRect( QPoint(x.first, y.first), QPoint(x.second, y.second) );
update();
}
QRect selectionRect;
private:
QPoint m_pos;
};
/// Load icon from icon font, path or theme.
QIcon loadIcon(const QString &idPathOrName)
{
if (idPathOrName.size() == 1)
return createPixmap(idPathOrName[0].unicode(), Qt::white, 64);
if ( QFile::exists(idPathOrName) )
return QIcon(idPathOrName);
return QIcon::fromTheme(idPathOrName);
}
QWidget *label(Qt::Orientation orientation, const QString &name, QWidget *w)
{
QWidget *parent = w->parentWidget();
if ( !name.isEmpty() ) {
QBoxLayout *layout;
if (orientation == Qt::Horizontal)
layout = new QHBoxLayout;
else
layout = new QVBoxLayout;
parent->layout()->addItem(layout);
QLabel *label = new QLabel(name + ":", parent);
label->setBuddy(w);
layout->addWidget(label);
layout->addWidget(w, 1);
}
w->setProperty(propertyWidgetName, name);
return w;
}
QWidget *label(const QString &name, QWidget *w)
{
w->setProperty("text", name);
w->setProperty(propertyWidgetName, name);
return w;
}
template <typename Widget>
Widget *createAndSetWidget(const char *propertyName, const QVariant &value, QWidget *parent)
{
auto w = new Widget(parent);
w->setProperty(propertyName, value);
w->setProperty(propertyWidgetProperty, propertyName);
parent->layout()->addWidget(w);
return w;
}
QWidget *createDateTimeEdit(
const QString &name, const char *propertyName, const QVariant &value, QWidget *parent)
{
QDateTimeEdit *w = createAndSetWidget<QDateTimeEdit>(propertyName, value, parent);
w->setCalendarPopup(true);
return label(Qt::Horizontal, name, w);
}
void installShortcutToCloseDialog(QDialog *dialog, QWidget *shortcutParent, int shortcut)
{
QShortcut *s = new QShortcut(QKeySequence(shortcut), shortcutParent);
QObject::connect(s, &QShortcut::activated, dialog, &QDialog::accept);
QObject::connect(s, &QShortcut::activatedAmbiguously, dialog, &QDialog::accept);
}
QWidget *createListWidget(const QString &name, const QStringList &items, InputDialog *inputDialog)
{
QDialog *parent = inputDialog->dialog;
const QString currentText = inputDialog->defaultChoice.isValid()
? inputDialog->defaultChoice.toString()
: items.value(0);
const QLatin1String listPrefix(".list:");
if ( name.startsWith(listPrefix) ) {
QListWidget *w = createAndSetWidget<QListWidget>("currentRow", QVariant(), parent);
w->addItems(items);
const int i = items.indexOf(currentText);
if (i != -1)
w->setCurrentRow(i);
w->setAlternatingRowColors(true);
installShortcutToCloseDialog(parent, w, Qt::Key_Enter);
installShortcutToCloseDialog(parent, w, Qt::Key_Return);
return label(Qt::Vertical, name.mid(listPrefix.size()), w);
}
QComboBox *w = createAndSetWidget<QComboBox>("currentText", QVariant(), parent);
w->setEditable(true);
w->addItems(items);
w->setCurrentIndex(items.indexOf(currentText));
w->lineEdit()->setText(currentText);
w->lineEdit()->selectAll();
w->setMaximumWidth( pointsToPixels(400, w) );
installShortcutToCloseDialog(parent, w, Qt::Key_Enter);
installShortcutToCloseDialog(parent, w, Qt::Key_Return);
const QLatin1String comboPrefix(".combo:");
if ( name.startsWith(comboPrefix) ) {
w->setEditable(false);
return label(Qt::Horizontal, name.mid(comboPrefix.size()), w);
}
return label(Qt::Horizontal, name, w);
}
QWidget *createSpinBox(const QString &name, const QVariant &value, QWidget *parent)
{
QSpinBox *w = createAndSetWidget<QSpinBox>("value", value, parent);
w->setRange(-1e9, 1e9);
return label(Qt::Horizontal, name, w);
}
QLineEdit *createLineEdit(const QVariant &value, QWidget *parent)
{
QLineEdit *lineEdit = createAndSetWidget<QLineEdit>("text", value, parent);
lineEdit->selectAll();
return lineEdit;
}
QWidget *createFileNameEdit(const QString &name, const QString &path, QWidget *parent)
{
QWidget *w = new QWidget(parent);
parent->layout()->addWidget(w);
auto layout = new QHBoxLayout(w);
layout->setContentsMargins(0, 0, 0, 0);
QLineEdit *lineEdit = createLineEdit(path, w);
lineEdit->setProperty(propertyWidgetName, name);
QPushButton *browseButton = new QPushButton("...");
FileDialog *dialog = new FileDialog(w, name, path);
QObject::connect( browseButton, &QAbstractButton::clicked,
dialog, &FileDialog::exec );
QObject::connect( dialog, &FileDialog::fileSelected,
lineEdit, &QLineEdit::setText );
layout->addWidget(lineEdit);
layout->addWidget(browseButton);
label(Qt::Vertical, name, w);
return lineEdit;
}
QWidget *createTextEdit(const QString &name, const QVariant &value, QWidget *parent)
{
QTextEdit *w = createAndSetWidget<QTextEdit>("plainText", value, parent);
w->setTabChangesFocus(true);
return label(Qt::Vertical, name, w);
}
QWidget *createWidget(const QString &name, const QVariant &value, InputDialog *inputDialog)
{
QDialog *parent = inputDialog->dialog;
switch ( value.type() ) {
case QVariant::Bool:
return label(name, createAndSetWidget<QCheckBox>("checked", value, parent));
case QVariant::Int:
return createSpinBox("value", value, parent);
case QVariant::Date:
return createDateTimeEdit(name, "date", value, parent);
case QVariant::Time:
return createDateTimeEdit(name, "time", value, parent);
case QVariant::DateTime:
return createDateTimeEdit(name, "dateTime", value, parent);
case QVariant::List:
case QVariant::StringList:
return createListWidget(name, value.toStringList(), inputDialog);
default:
if ( value.type() == QVariant::Url ) {
const auto path = value.toUrl();
return createFileNameEdit(name, path.toLocalFile(), parent);
}
const QString text = value.toString();
if (text.contains('\n'))
return createTextEdit(name, value.toStringList(), parent);
return label(Qt::Horizontal, name, createLineEdit(value, parent));
}
}
void setGeometryWithoutSave(QWidget *window, QRect geometry)
{
setGeometryGuardBlockedUntilHidden(window, true);
const auto pos = (geometry.x() == -1 && geometry.y() == -1)
? QCursor::pos()
: geometry.topLeft();
const int w = pointsToPixels(geometry.width(), window);
const int h = pointsToPixels(geometry.height(), window);
if (w > 0 && h > 0)
window->resize(w, h);
moveWindowOnScreen(window, pos);
}
QString tabNotFoundError()
{
return ScriptableProxy::tr("Tab with given name doesn't exist!");
}
QString tabNameEmptyError()
{
return ScriptableProxy::tr("Tab name cannot be empty!");
}
} // namespace
#ifdef HAS_TESTS
class KeyClicker final : public QObject {
public:
KeyClicker(MainWindow *wnd, QObject *parent)
: QObject(parent)
, m_wnd(wnd)
{
}
void keyClicksRetry(const QString &expectedWidgetName, const QString &keys, int delay, int retry)
{
if (retry > 0)
sendKeyClicks(expectedWidgetName, keys, delay + 100, retry - 1);
else
keyClicksFailed(expectedWidgetName);
}
void keyClicksFailed(const QString &expectedWidgetName)
{
auto actual = keyClicksTarget();
auto popup = QApplication::activePopupWidget();
auto widget = QApplication::focusWidget();
auto window = QApplication::activeWindow();
auto modal = QApplication::activeModalWidget();
const auto currentWindow = platformNativeInterface()->getCurrentWindow();
const auto currentWindowTitle = currentWindow ? currentWindow->getTitle() : QString();
log( QString("Failed to send key press to target widget")
+ QLatin1String(qApp->applicationState() == Qt::ApplicationActive ? "" : "\nApp is INACTIVE!")
+ "\nExpected: " + (expectedWidgetName.isEmpty() ? "Any" : expectedWidgetName)
+ "\nActual: " + keyClicksTargetDescription(actual)
+ "\nPopup: " + keyClicksTargetDescription(popup)
+ "\nWidget: " + keyClicksTargetDescription(widget)
+ "\nWindow: " + keyClicksTargetDescription(window)
+ "\nModal: " + keyClicksTargetDescription(modal)
+ "\nTitle: " + currentWindowTitle
, LogError );
m_failed = true;
}
void keyClicks(const QString &expectedWidgetName, const QString &keys, int delay, int retry)
{
auto widget = keyClicksTarget();
if (!widget) {
keyClicksRetry(expectedWidgetName, keys, delay, retry);
return;
}
if (qApp->applicationState() != Qt::ApplicationActive) {
#if defined(Q_OS_MAC) && QT_VERSION >= QT_VERSION_CHECK(6,0,0)
// WORKAROUND for focusing back to main window on macOS.
if (m_wnd->isVisible())
m_wnd->activateWindow();
#endif
keyClicksRetry(expectedWidgetName, keys, delay, retry);
return;
}
auto widgetName = keyClicksTargetDescription(widget);
if ( !expectedWidgetName.isEmpty() && !widgetName.contains(expectedWidgetName) ) {
keyClicksRetry(expectedWidgetName, keys, delay, retry);
return;
}
// Only verified focused widget.
if ( keys.isEmpty() ) {
m_succeeded = true;
return;
}
// There could be some animation/transition effect on check boxes
// so wait for checkbox to be set.
if ( qobject_cast<QCheckBox*>(widget) )
waitFor(100);
COPYQ_LOG( QString("Sending keys \"%1\" to %2.")
.arg(keys, widgetName) );
const auto popupMessage = QString::fromLatin1("%1 (%2)")
.arg( quoteString(keys), widgetName );
auto notification = m_wnd->createNotification(QLatin1String("tests"));
notification->setMessage(popupMessage);
notification->setIcon(IconKeyboard);
notification->setInterval(2000);
if ( keys.startsWith(":") ) {
const auto text = keys.mid(1);
QTest::keyClicks(widget, text, Qt::NoModifier, 0);
// Increment key clicks sequence number after typing all the text.
m_succeeded = true;
} else {
const QKeySequence shortcut(keys, QKeySequence::PortableText);
if ( shortcut.isEmpty() ) {
log( QString("Cannot parse shortcut \"%1\"!").arg(keys), LogError );
m_failed = true;
return;
}
// Increment key clicks sequence number before opening any modal dialogs.
m_succeeded = true;
const auto key = static_cast<uint>(shortcut[0]);
QTest::keyClick( widget,
Qt::Key(key & ~Qt::KeyboardModifierMask),
Qt::KeyboardModifiers(key & Qt::KeyboardModifierMask),
0 );
}
COPYQ_LOG( QString("Key \"%1\" sent to %2.")
.arg(keys, widgetName) );
}
void sendKeyClicks(const QString &expectedWidgetName, const QString &keys, int delay, int retry)
{
m_succeeded = false;
m_failed = false;
// Don't stop when modal window is open.
auto t = new QTimer(m_wnd);
t->setSingleShot(true);
QObject::connect( t, &QTimer::timeout, this, [=]() {
keyClicks(expectedWidgetName, keys, delay, retry);
t->deleteLater();
});
t->start(delay);
}
bool succeeded() const { return m_succeeded; }
bool failed() const { return m_failed; }
private:
static QString keyClicksTargetDescription(QWidget *widget)
{
if (widget == nullptr)
return "None";
const auto className = widget->metaObject()->className();
auto widgetName = QString::fromLatin1("%1:%2")
.arg(widget->objectName(), className);
const auto window = widget->window();
if (window && widget != window) {
widgetName.append(
QString::fromLatin1(" in %1:%2")
.arg(window->objectName(), window->metaObject()->className())
);
}
auto parent = widget->parentWidget();
while (parent) {
if ( parent != window && !parent->objectName().startsWith("qt_") ) {
widgetName.append(
QString::fromLatin1(" in %1:%2")
.arg(parent->objectName(), parent->metaObject()->className())
);
}
parent = parent->parentWidget();
}
return widgetName;
}
QWidget *keyClicksTarget()
{
auto popup = QApplication::activePopupWidget();
if (popup)
return popup;
auto widget = QApplication::focusWidget();
if (widget)
return widget;
auto window = QApplication::activeWindow();
if (window)
return window->focusWidget();
auto modal = QApplication::activeModalWidget();
if (modal)
return modal->focusWidget();
#ifdef Q_OS_MAC
return m_wnd->focusWidget();
#else
return nullptr;
#endif
}
MainWindow *m_wnd = nullptr;
bool m_succeeded = true;
bool m_failed = false;
};
#endif // HAS_TESTS
ScriptableProxy::ScriptableProxy(MainWindow *mainWindow, QObject *parent)
: QObject(parent)
, m_wnd(mainWindow)
{
connect( this, &ScriptableProxy::clientDisconnected,
this, [this]() {
m_disconnected = true;
emit abortEvaluation();
} );
registerMetaTypes();
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
Q_ASSERT(QMetaType::fromType<Command>().hasRegisteredDataStreamOperators());
Q_ASSERT(QMetaType::fromType<ClipboardMode>().hasRegisteredDataStreamOperators());
#endif
}
void ScriptableProxy::callFunction(const QByteArray &serializedFunctionCall)
{
if (m_shouldBeDeleted)
return;
++m_functionCallStack;
auto t = new QTimer(this);
t->setSingleShot(true);
QObject::connect( t, &QTimer::timeout, this, [=]() {
const auto result = callFunctionHelper(serializedFunctionCall);
emit sendMessage(result, CommandFunctionCallReturnValue);
t->deleteLater();
--m_functionCallStack;
if (m_shouldBeDeleted && m_functionCallStack == 0)
deleteLater();
});
t->start(0);
}
QByteArray ScriptableProxy::callFunctionHelper(const QByteArray &serializedFunctionCall)
{
QVector<QVariant> arguments;
QByteArray slotName;
int functionCallId;
{
QDataStream stream(serializedFunctionCall);
stream.setVersion(QDataStream::Qt_5_0);
quint32 magicNumber;
quint32 version;
stream >> magicNumber >> version;
if (stream.status() != QDataStream::Ok) {
log("Failed to read scriptable proxy slot call preamble", LogError);
Q_ASSERT(false);
return QByteArray();
}
if (magicNumber != serializedFunctionCallMagicNumber) {
log("Unexpected scriptable proxy slot call preamble magic number", LogError);
Q_ASSERT(false);
return QByteArray();
}
if (version != serializedFunctionCallVersion) {
log("Unexpected scriptable proxy slot call preamble version", LogError);
Q_ASSERT(false);
return QByteArray();
}
stream >> functionCallId;
if (stream.status() != QDataStream::Ok) {
log("Failed to read scriptable proxy slot call ID", LogError);
Q_ASSERT(false);
return QByteArray();
}
stream >> slotName;
if (stream.status() != QDataStream::Ok) {
log("Failed to read scriptable proxy slot call name", LogError);
Q_ASSERT(false);
return QByteArray();
}
stream >> arguments;
if (stream.status() != QDataStream::Ok) {
log("Failed to read scriptable proxy slot call", LogError);
Q_ASSERT(false);
return QByteArray();
}
}
const auto slotIndex = metaObject()->indexOfSlot(slotName);
if (slotIndex == -1) {
log("Failed to find scriptable proxy slot: " + slotName, LogError);
Q_ASSERT(false);
return QByteArray();
}
const auto metaMethod = metaObject()->method(slotIndex);
const auto typeId = metaMethod.returnType();
QGenericArgument args[9];
for (int i = 0; i < arguments.size(); ++i) {
auto &value = arguments[i];
const int argumentTypeId = metaMethod.parameterType(i);
if (argumentTypeId == QMetaType::QVariant) {
args[i] = QGenericArgument( "QVariant", static_cast<void*>(value.data()) );
} else if ( value.userType() == argumentTypeId ) {
args[i] = QGenericArgument( value.typeName(), static_cast<void*>(value.data()) );
} else {
log( QString("Bad argument type (at index %1) for scriptable proxy slot: %2")
.arg(i)
.arg(metaMethod.methodSignature().constData()), LogError);
Q_ASSERT(false);
return QByteArray();
}
}
QVariant returnValue;
bool called;
if (typeId == QMetaType::Void) {
called = metaMethod.invoke(
this, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
} else {
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
const QMetaType metaType(typeId);
COPYQ_LOG_VERBOSE(QStringLiteral("Script function return type: %1").arg(metaType.name()));
Q_ASSERT(metaType.hasRegisteredDataStreamOperators());
returnValue = QVariant(metaType, nullptr);
#else
returnValue = QVariant(typeId, nullptr);
#endif
const auto genericReturnValue = returnValue.isValid()
? QGenericReturnArgument( returnValue.typeName(), static_cast<void*>(returnValue.data()) )
: QGenericReturnArgument( "QVariant", static_cast<void*>(returnValue.data()) );
called = metaMethod.invoke(
this, genericReturnValue,
args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
}
if (!called) {
log( QString("Bad scriptable proxy slot call: %1")
.arg(metaMethod.methodSignature().constData()), LogError);
Q_ASSERT(false);
}
QByteArray bytes;
{
QDataStream stream(&bytes, QIODevice::WriteOnly);
stream << functionCallId << returnValue;
if (stream.status() != QDataStream::Ok) {
log("Failed to write scriptable proxy slot call return value", LogError);
Q_ASSERT(false);
}
}
return bytes;
}
void ScriptableProxy::setFunctionCallReturnValue(const QByteArray &bytes)
{
QDataStream stream(bytes);
int functionCallId;
QVariant returnValue;
stream >> functionCallId >> returnValue;
if (stream.status() != QDataStream::Ok) {
log("Failed to read scriptable proxy slot call return value", LogError);
Q_ASSERT(false);
return;
}
emit functionCallFinished(functionCallId, returnValue);
}
void ScriptableProxy::setInputDialogResult(const QByteArray &bytes)
{
QDataStream stream(bytes);
int dialogId;
NamedValueList result;
stream >> dialogId >> result;
if (stream.status() != QDataStream::Ok) {
log("Failed to read input dialog result", LogError);
Q_ASSERT(false);
return;
}
emit inputDialogFinished(dialogId, result);
}
void ScriptableProxy::safeDeleteLater()
{
m_shouldBeDeleted = true;
if (m_functionCallStack == 0)
deleteLater();
}
QVariantMap ScriptableProxy::getActionData(int id)
{
INVOKE(getActionData, (id));
m_actionData = m_wnd->actionData(id);
m_actionId = id;
auto data = m_actionData;
data.remove(mimeSelectedItems);
data.remove(mimeCurrentItem);
return data;
}
void ScriptableProxy::setActionData(int id, const QVariantMap &data)
{
INVOKE2(setActionData, (id, data));
m_wnd->setActionData(id, data);
}
void ScriptableProxy::exit()
{
INVOKE2(exit, ());
qApp->quit();
}
void ScriptableProxy::close()
{
INVOKE2(close, ());
m_wnd->close();
}
bool ScriptableProxy::focusPrevious()
{
INVOKE(focusPrevious, ());
return m_wnd->focusPrevious();
}
bool ScriptableProxy::showWindow()
{
INVOKE(showWindow, ());
m_wnd->showWindow();
return m_wnd->isVisible();
}
bool ScriptableProxy::showWindowAt(QRect rect)
{
INVOKE(showWindowAt, (rect));
setGeometryWithoutSave(m_wnd, rect);
return showWindow();
}
bool ScriptableProxy::pasteToCurrentWindow()
{
INVOKE(pasteToCurrentWindow, ());
PlatformWindowPtr window = platformNativeInterface()->getCurrentWindow();
if (!window)
return false;
window->pasteClipboard();
return true;
}
bool ScriptableProxy::copyFromCurrentWindow()
{
INVOKE(copyFromCurrentWindow, ());
PlatformWindowPtr window = platformNativeInterface()->getCurrentWindow();
if (!window)
return false;
window->copy();
return true;
}
bool ScriptableProxy::isMonitoringEnabled()
{
INVOKE(isMonitoringEnabled, ());
return m_wnd->isMonitoringEnabled();
}
bool ScriptableProxy::isMainWindowVisible()
{
INVOKE(isMainWindowVisible, ());
return !m_wnd->isMinimized() && m_wnd->isVisible();
}
bool ScriptableProxy::isMainWindowFocused()
{
INVOKE(isMainWindowFocused, ());
return m_wnd->isActiveWindow();
}
bool ScriptableProxy::preview(const QVariant &arg)
{
INVOKE(preview, (arg));
const bool wasVisible = m_wnd->isItemPreviewVisible();
if ( arg.isValid() ) {
const bool enable =
arg.canConvert<bool>() ? arg.toBool()
: arg.canConvert<int>() ? arg.toInt() != 0
: arg.toString() == QLatin1String("true");
m_wnd->setItemPreviewVisible(enable);
}
return wasVisible;
}
void ScriptableProxy::disableMonitoring(bool arg1)
{
INVOKE2(disableMonitoring, (arg1));
m_wnd->disableClipboardStoring(arg1);
}
void ScriptableProxy::setClipboard(const QVariantMap &data, ClipboardMode mode)
{
INVOKE2(setClipboard, (data, mode));
m_wnd->setClipboard(data, mode);
}
QString ScriptableProxy::renameTab(const QString &arg1, const QString &arg2)
{
INVOKE(renameTab, (arg1, arg2));
if ( arg1.isEmpty() || arg2.isEmpty() )
return tabNameEmptyError();
const int i = m_wnd->findTabIndex(arg2);
if (i == -1)
return tabNotFoundError();
if ( m_wnd->findTabIndex(arg1) != -1 )
return ScriptableProxy::tr("Tab with given name already exists!");
m_wnd->renameTab(arg1, i);
return QString();
}
QString ScriptableProxy::removeTab(const QString &arg1)
{
INVOKE(removeTab, (arg1));
if ( arg1.isEmpty() )
return tabNameEmptyError();
const int i = m_wnd->findTabIndex(arg1);
if (i == -1)
return tabNotFoundError();
m_wnd->removeTab(false, i);
return QString();
}
QString ScriptableProxy::tabIcon(const QString &tabName)
{
INVOKE(tabIcon, (tabName));
return getIconNameForTabName(tabName);
}
void ScriptableProxy::setTabIcon(const QString &tabName, const QString &icon)
{
INVOKE2(setTabIcon, (tabName, icon));
m_wnd->setTabIcon(tabName, icon);
}
QStringList ScriptableProxy::unloadTabs(const QStringList &tabs)
{
INVOKE(unloadTabs, (tabs));
QStringList unloaded;
for (const auto &tab : tabs) {
if ( m_wnd->unloadTab(tab) )
unloaded.append(tab);
}
return unloaded;
}
void ScriptableProxy::forceUnloadTabs(const QStringList &tabs)
{
INVOKE2(forceUnloadTabs, (tabs));
for (const auto &tab : tabs)
m_wnd->forceUnloadTab(tab);
}
bool ScriptableProxy::showBrowser(const QString &tabName)
{
INVOKE(showBrowser, (tabName));
ClipboardBrowser *c = fetchBrowser(tabName);
if (c)
m_wnd->showBrowser(c);
return m_wnd->isVisible();
}
bool ScriptableProxy::showBrowserAt(const QString &tabName, QRect rect)
{
INVOKE(showBrowserAt, (tabName, rect));
setGeometryWithoutSave(m_wnd, rect);
return showBrowser(tabName);
}
void ScriptableProxy::action(const QVariantMap &arg1, const Command &arg2)
{
INVOKE2(action, (arg1, arg2));
m_wnd->action(arg1, arg2, QModelIndex());
}
void ScriptableProxy::runInternalAction(const QVariantMap &data, const QString &command)
{
INVOKE2(runInternalAction, (data, command));
auto action = new Action();
action->setCommand(command);
action->setData(data);
m_wnd->runInternalAction(action);
}
void ScriptableProxy::showMessage(const QString &title,
const QString &msg,
const QString &icon,
int msec,
const QString ¬ificationId,
const NotificationButtonList &buttons)
{
INVOKE2(showMessage, (title, msg, icon, msec, notificationId, buttons));
auto notification = m_wnd->createNotification(notificationId);
notification->setTitle(title);
notification->setMessage(msg, Qt::AutoText);
notification->setIcon(icon);
notification->setInterval(msec);
notification->setButtons(buttons.items);
}
QVariantMap ScriptableProxy::nextItem(const QString &tabName, int where)
{
INVOKE(nextItem, (tabName, where));
ClipboardBrowser *c = fetchBrowser(tabName);
if (!c)
return QVariantMap();
const int row = qMax(0, c->currentIndex().row()) + where;
const QModelIndex index = c->index(row);
if (!index.isValid())
return QVariantMap();
c->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
return c->copyIndex(index);
}
void ScriptableProxy::browserMoveToClipboard(const QString &tabName, int row)
{
INVOKE2(browserMoveToClipboard, (tabName, row));
ClipboardBrowser *c = fetchBrowser(tabName);
m_wnd->moveToClipboard(c, row);
}
void ScriptableProxy::browserSetCurrent(const QString &tabName, int arg1)
{
INVOKE2(browserSetCurrent, (tabName, arg1));
BROWSER(tabName, setCurrent(arg1));
}
QString ScriptableProxy::browserRemoveRows(const QString &tabName, QVector<int> rows)
{
INVOKE(browserRemoveRows, (tabName, rows));
ClipboardBrowser *c = fetchBrowser(tabName);
if (!c)
return QStringLiteral("Invalid tab");
std::sort( rows.begin(), rows.end(), std::greater<int>() );
QModelIndexList indexes;
indexes.reserve(rows.size());
for (int row : rows) {
const QModelIndex indexToRemove = c->index(row);
if ( indexToRemove.isValid() )
indexes.append(indexToRemove);
}
QString error;
c->removeIndexes(indexes, &error);
if ( !error.isEmpty() )
return error;
return QString();
}
void ScriptableProxy::browserMoveSelected(int targetRow)
{
INVOKE2(browserMoveSelected, (targetRow));
QList<QPersistentModelIndex> selected = selectedIndexes();
selectionRemoveInvalid(&selected);
ClipboardBrowser *c = browserForIndexes(selected);
if (c == nullptr)
return;
QModelIndexList indexes;
indexes.reserve(selected.size());
for (const auto &index : selected)
indexes.append(index);
c->move(indexes, targetRow);
}
void ScriptableProxy::browserEditRow(const QString &tabName, int row, const QString &format)
{
INVOKE2(browserEditRow, (tabName, row, format));
BROWSER(tabName, editRow(row, format));
}
void ScriptableProxy::browserEditNew(const QString &tabName, const QString &format, const QByteArray &content, bool changeClipboard)
{
INVOKE2(browserEditNew, (tabName, format, content, changeClipboard));
BROWSER(tabName, editNew(format, content, changeClipboard));
}
QStringList ScriptableProxy::tabs()
{
INVOKE(tabs, ());
return m_wnd->tabs();
}
bool ScriptableProxy::toggleVisible()
{
INVOKE(toggleVisible, ());
return m_wnd->toggleVisible();
}
bool ScriptableProxy::toggleMenu(const QString &tabName, int maxItemCount, QPoint position)
{
INVOKE(toggleMenu, (tabName, maxItemCount, position));
return m_wnd->toggleMenu(tabName, maxItemCount, position);
}
bool ScriptableProxy::toggleCurrentMenu()
{
INVOKE(toggleCurrentMenu, ());
return m_wnd->toggleMenu();
}
int ScriptableProxy::findTabIndex(const QString &arg1)
{
INVOKE(findTabIndex, (arg1));
return m_wnd->findTabIndex(arg1);
}
int ScriptableProxy::menuItems(const VariantMapList &items)
{
INVOKE(menuItems, (items));
TrayMenu menu;
menu.setObjectName("CustomMenu");
menu.setRowIndexFromOne( AppConfig().option<Config::row_index_from_one>() );
const auto addMenuItems = [&](const QString &searchText) {
menu.clearClipboardItems();
for (const QVariantMap &data : items.items) {
const QString text = getTextData(data);
if ( text.contains(searchText, Qt::CaseInsensitive) )
menu.addClipboardItemAction(data, true);
}
};
addMenuItems(QString());
connect(&menu, &TrayMenu::searchRequest, addMenuItems);
const QPoint pos = QCursor::pos();
QAction *act = menu.exec(pos);
if (act == nullptr)
return -1;
return items.items.indexOf(act->data().toMap());
}
void ScriptableProxy::openActionDialog(const QVariantMap &arg1)
{
INVOKE2(openActionDialog, (arg1));
m_wnd->openActionDialog(arg1);
}
bool ScriptableProxy::loadTab(const QString &arg1)
{
INVOKE(loadTab, (arg1));
return m_wnd->loadTab(arg1);
}
bool ScriptableProxy::saveTab(const QString &tabName, const QString &arg1)
{
INVOKE(saveTab, (tabName, arg1));
ClipboardBrowser *c = fetchBrowser(tabName);
if (!c)
return false;
const int i = m_wnd->findTabIndex( c->tabName() );
return m_wnd->saveTab(arg1, i);
}
bool ScriptableProxy::importData(const QString &fileName)
{
INVOKE(importData, (fileName));
return m_wnd->importDataFrom(fileName, ImportOptions::All);
}
bool ScriptableProxy::exportData(const QString &fileName)
{
INVOKE(exportData, (fileName));
return m_wnd->exportAllData(fileName);
}
QVariant ScriptableProxy::config(const QVariantList &nameValue)
{
INVOKE(config, (nameValue));
return m_wnd->config(nameValue);
}
QString ScriptableProxy::configDescription()
{
INVOKE(configDescription, ());
return m_wnd->configDescription();
}
QVariant ScriptableProxy::toggleConfig(const QString &optionName)
{
INVOKE(toggleConfig, (optionName));
QVariantList nameValue;
nameValue.append(optionName);
const auto values = m_wnd->config(nameValue);
if ( values.type() == QVariant::StringList )
return values;
const auto oldValue = values.toMap().constBegin().value();
if ( oldValue.type() != QVariant::Bool )
return QVariant();
const auto newValue = !QVariant(oldValue).toBool();
nameValue.append(newValue);
return m_wnd->config(nameValue).toMap().constBegin().value();
}
int ScriptableProxy::browserLength(const QString &tabName)
{
INVOKE(browserLength, (tabName));
ClipboardBrowser *c = fetchBrowser(tabName);
return c ? c->length() : 0;
}
bool ScriptableProxy::browserOpenEditor(
const QString &tabName, int row, const QString &format, const QByteArray &content, bool changeClipboard)
{
INVOKE(browserOpenEditor, (tabName, row, format, content, changeClipboard));
ClipboardBrowser *c = fetchBrowser(tabName);
if (!c)
return false;
const auto index = c->index(row);
return c->openEditor(index, format, content, changeClipboard);
}
QString ScriptableProxy::browserInsert(const QString &tabName, int row, const VariantMapList &items)
{
INVOKE(browserInsert, (tabName, row, items));
ClipboardBrowser *c = fetchBrowser(tabName);
if (!c)
return QStringLiteral("Invalid tab");
if ( !c->allocateSpaceForNewItems(items.items.size()) )
return QStringLiteral("Tab is full (cannot remove any items)");
if ( !c->addReversed(items.items, row) )
return QStringLiteral("Failed to add items");
return QString();
}
QString ScriptableProxy::browserChange(const QString &tabName, int row, const VariantMapList &items)
{
INVOKE(browserChange, (tabName, row, items));
ClipboardBrowser *c = fetchBrowser(tabName);
if (!c)
return QStringLiteral("Invalid tab");
QMap<QPersistentModelIndex, QVariantMap> itemsData;
int currentRow = row;
for (const auto &data : items.items) {
const auto index = c->index(currentRow);
QVariantMap itemData = index.data(contentType::data).toMap();
for (auto it = data.constBegin(); it != data.constEnd(); ++it) {
if ( it.value().isValid() )
itemData.insert( it.key(), it.value() );
else
itemData.remove( it.key() );
}
itemsData[index] = itemData;
++currentRow;
}
c->setItemsData(itemsData);
return QString();
}
QByteArray ScriptableProxy::browserItemData(const QString &tabName, int arg1, const QString &arg2)
{
INVOKE(browserItemData, (tabName, arg1, arg2));
return itemData(tabName, arg1, arg2);
}
QVariantMap ScriptableProxy::browserItemData(const QString &tabName, int arg1)
{
INVOKE(browserItemData, (tabName, arg1));
return itemData(tabName, arg1);
}
void ScriptableProxy::setCurrentTab(const QString &tabName)
{
INVOKE2(setCurrentTab, (tabName));
m_wnd->addAndFocusTab(tabName);
}
QString ScriptableProxy::tab(const QString &tabName)
{
INVOKE(tab, (tabName));
ClipboardBrowser *c = fetchBrowser(tabName);
return c ? c->tabName() : QString();
}
int ScriptableProxy::currentItem()
{
INVOKE(currentItem, ());
const QPersistentModelIndex current = currentIndex();
return current.isValid() ? current.row() : -1;
}
bool ScriptableProxy::selectItems(const QString &tabName, const QVector<int> &rows)
{
INVOKE(selectItems, (tabName, rows));
ClipboardBrowser *c = fetchBrowser(tabName);
if (!c)
return false;
c->clearSelection();
if ( !rows.isEmpty() ) {
c->setCurrent(rows.last());
for (int i : rows) {
const QModelIndex index = c->index(i);
if ( index.isValid() && !c->isFiltered(i) )
c->selectionModel()->select(index, QItemSelectionModel::Select);
}
}
return true;
}
QVector<int> ScriptableProxy::selectedItems()
{
INVOKE(selectedItems, ());
QVector<int> selectedRows;
QList<QPersistentModelIndex> selected = selectedIndexes();
selectedRows.reserve(selected.count());
for (const auto &index : selected)
selectedRows.append(index.row());
return selectedRows;
}
QString ScriptableProxy::selectedTab()
{
INVOKE(selectedTab, ());
const QPersistentModelIndex current = currentIndex();
ClipboardBrowser *c = m_wnd->browserForItem(current);
if (c != nullptr)
return c->tabName();
const QList<QPersistentModelIndex> selected = selectedIndexes();
c = m_wnd->browserForItem(current);
if (c != nullptr)
return c->tabName();
return m_actionData.value(mimeCurrentTab).toString();
}
QVariantMap ScriptableProxy::selectedItemData(int selectedIndex)
{
INVOKE(selectedItemData, (selectedIndex));
const auto index = selectedIndexes().value(selectedIndex);
if ( !index.isValid() )
return {};
ClipboardBrowser *c = m_wnd->browserForItem(index);
if (c == nullptr)
return {};
return c->copyIndex(index);
}
bool ScriptableProxy::setSelectedItemData(int selectedIndex, const QVariantMap &data)
{
INVOKE(setSelectedItemData, (selectedIndex, data));
const auto index = selectedIndexes().value(selectedIndex);
if ( !index.isValid() )
return false;
ClipboardBrowser *c = m_wnd->browserForItem(index);
if (c == nullptr)
return false;
return c->model()->setData(index, data, contentType::data);
}
VariantMapList ScriptableProxy::selectedItemsData()
{
INVOKE(selectedItemsData, ());
QList<QPersistentModelIndex> selected = selectedIndexes();
ClipboardBrowser *c = browserForIndexes(selected);
if (c == nullptr)
return {QVector<QVariantMap>(selected.size(), {})};
QVector<QVariantMap> dataList;
dataList.reserve(selected.size());
for (const auto &index : selected)
dataList.append( c->copyIndex(index) );
return {dataList};
}
void ScriptableProxy::setSelectedItemsData(const VariantMapList &dataList)
{
INVOKE2(setSelectedItemsData, (dataList));
const QList<QPersistentModelIndex> selected = selectedIndexes();
ClipboardBrowser *c = nullptr;
QMap<QPersistentModelIndex, QVariantMap> itemsData;
const auto count = std::min( selected.size(), dataList.items.size() );
for ( int i = 0; i < count; ++i ) {
const auto &index = selected[i];
if ( !index.isValid() )
continue;
if (c == nullptr)
c = m_wnd->browserForItem(index);
itemsData[index] = dataList.items[i];
}
if (c != nullptr)
c->setItemsData(itemsData);
}
int ScriptableProxy::createSelection(const QString &tabName)
{
INVOKE(createSelection, (tabName));
const int newSelectionId = ++m_lastSelectionId;
ClipboardBrowser *c = fetchBrowser(tabName);
if (c)
m_selections[newSelectionId] = {c, {}};
return newSelectionId;
}
int ScriptableProxy::selectionCopy(int id)
{
INVOKE(selectionCopy, (id));
const int newSelectionId = ++m_lastSelectionId;
auto selection = m_selections.value(id);
if (selection.browser)
m_selections[newSelectionId] = selection;
return newSelectionId;
}
void ScriptableProxy::destroySelection(int id)
{
INVOKE2(destroySelection, (id));
m_selections.remove(id);
}
void ScriptableProxy::selectionRemoveAll(int id)
{
INVOKE2(selectionRemoveAll, (id));
auto selection = m_selections.take(id);
if (!selection.browser)
return;
selectionRemoveInvalid(&selection.indexes);
QModelIndexList indexes;
for (const auto &index : selection.indexes)
indexes.append(index);
selection.browser->removeIndexes(indexes);
selectionRemoveInvalid(&selection.indexes);
m_selections[id] = selection;
}
void ScriptableProxy::selectionSelectRemovable(int id)
{
INVOKE2(selectionSelectRemovable, (id));
auto selection = m_selections.take(id);
if (!selection.browser)
return;
// Use error argument for canRemoveItems() to ensure that a message dialog is not shown.
QString error;
QList<QPersistentModelIndex> indexes;
for (int row = 0; row < selection.browser->length(); ++row) {
const auto index = selection.browser->index(row);
if ( !selection.indexes.contains(index) && selection.browser->canRemoveItems({index}, &error) )
indexes.append(index);
}
selection.indexes.append(indexes);
m_selections[id] = selection;
}
void ScriptableProxy::selectionInvert(int id)
{
INVOKE2(selectionInvert, (id));
auto selection = m_selections.take(id);
if (!selection.browser)
return;
QList<QPersistentModelIndex> indexes;
for (int row = 0; row < selection.browser->length(); ++row) {
const auto index = selection.browser->index(row);
if ( !selection.indexes.contains(index) )
indexes.append(index);
}
selection.indexes = indexes;
m_selections[id] = selection;
}
void ScriptableProxy::selectionSelectAll(int id)
{
INVOKE2(selectionSelectAll, (id));
auto selection = m_selections.take(id);
if (!selection.browser)
return;
selection.indexes.clear();
for (int row = 0; row < selection.browser->length(); ++row)
selection.indexes.append(selection.browser->index(row));
m_selections[id] = selection;
}
void ScriptableProxy::selectionSelect(int id, const QVariant &maybeRe, const QString &mimeFormat)
{
INVOKE2(selectionSelect, (id, maybeRe, mimeFormat));
auto selection = m_selections.take(id);
if (!selection.browser)
return;
const QRegularExpression re = maybeRe.toRegularExpression();
QList<QPersistentModelIndex> indexes;
for (int row = 0; row < selection.browser->length(); ++row) {
const auto index = selection.browser->index(row);
if ( selection.indexes.contains(index) )
continue;
const QVariantMap dataMap = index.data(contentType::data).toMap();
if ( mimeFormat.isEmpty() ) {
if ( !maybeRe.isValid() )
continue;
const QString text = getTextData(dataMap);
if ( text.contains(re) )
indexes.append(index);
} else if ( dataMap.contains(mimeFormat) == maybeRe.isValid() ) {
const QString text = getTextData(dataMap, mimeFormat);
if ( text.contains(re) )
indexes.append(index);
}
}
selection.indexes.append(indexes);
m_selections[id] = selection;
}
void ScriptableProxy::selectionDeselectIndexes(int id, const QVector<int> &indexes)
{
INVOKE2(selectionDeselectIndexes, (id, indexes));
auto selection = m_selections.take(id);
auto indexesSorted = indexes;
std::sort(indexesSorted.begin(), indexesSorted.end(), std::greater<int>());
for (int index : indexesSorted)
selection.indexes.removeAt(index);
m_selections[id] = selection;
}
void ScriptableProxy::selectionDeselectSelection(int id, int toDeselectId)
{
INVOKE2(selectionDeselectSelection, (id, toDeselectId));
auto selection = m_selections.take(id);
const auto deselection = m_selections.value(toDeselectId);
selectionRemoveIf(
&selection.indexes,
[&](const QPersistentModelIndex &index){
return !index.isValid() || deselection.indexes.contains(index);
});
m_selections[id] = selection;
}
void ScriptableProxy::selectionGetCurrent(int id)
{
INVOKE2(selectionGetCurrent, (id));
QList<QPersistentModelIndex> selected = selectedIndexes();
ClipboardBrowser *c = browserForIndexes(selected);
if (c == nullptr) {
const QString currentTab = m_actionData.value(mimeCurrentTab).toString();
c = fetchBrowser(currentTab);
}
m_selections[id] = {c, selected};
}
int ScriptableProxy::selectionGetSize(int id)
{
INVOKE(selectionGetSize, (id));
return m_selections.value(id).indexes.size();
}
QString ScriptableProxy::selectionGetTabName(int id)
{
INVOKE(selectionGetTabName, (id));
const auto selection = m_selections.value(id);
return selection.browser ? selection.browser->tabName() : QString();
}
QVector<int> ScriptableProxy::selectionGetRows(int id)
{
INVOKE(selectionGetRows, (id));
auto selection = m_selections.value(id);
QVector<int> rows;
rows.reserve(selection.indexes.size());
for (const auto &index : selection.indexes)
rows.append(index.row());
return rows;
}
QVariantMap ScriptableProxy::selectionGetItemIndex(int id, int index)
{
INVOKE(selectionGetItemIndex, (id, index));
auto selection = m_selections.value(id);
if ( selection.indexes.isEmpty() || index < 0 || index >= selection.indexes.size() )
return {};
return selection.indexes[index].data(contentType::data).toMap();
}
void ScriptableProxy::selectionSetItemIndex(int id, int index, const QVariantMap &item)
{
INVOKE2(selectionSetItemIndex, (id, index, item));
const auto selection = m_selections.value(id);
if ( !selection.browser || index < 0 || index >= selection.indexes.size() )
return;
const QModelIndex ind = selection.indexes[index];
selection.browser->model()->setData(ind, item, contentType::data);
}
QVariantList ScriptableProxy::selectionGetItemsData(int id)
{
INVOKE(selectionGetItemsData, (id));
QVariantList dataList;
const auto selection = m_selections.value(id);
for (const auto &index : selection.indexes) {
const auto data = index.data(contentType::data).toMap();
dataList.append(data);
}
return dataList;
}
void ScriptableProxy::selectionSetItemsData(int id, const QVariantList &dataList)
{
INVOKE2(selectionSetItemsData, (id, dataList));
QMap<QPersistentModelIndex, QVariantMap> itemsData;
const auto selection = m_selections.value(id);
const auto count = std::min( selection.indexes.size(), dataList.size() );
for ( int i = 0; i < count; ++i ) {
const auto &index = selection.indexes[i];
if ( index.isValid() )
itemsData[index] = dataList[i].toMap();
}
selection.browser->setItemsData(itemsData);
}
QVariantList ScriptableProxy::selectionGetItemsFormat(int id, const QString &format)
{
INVOKE(selectionGetItemsFormat, (id, format));
QVariantList dataList;
const auto selection = m_selections.value(id);
for (const auto &index : selection.indexes) {
const auto data = index.data(contentType::data).toMap();
dataList.append( data.value(format) );
}
return dataList;
}
void ScriptableProxy::selectionSetItemsFormat(int id, const QString &mime, const QVariant &value)
{
INVOKE2(selectionSetItemsFormat, (id, mime, value));
const auto selection = m_selections.value(id);
setItemsData(selection.browser, selection.indexes, mime, value);
}
void ScriptableProxy::selectionMove(int id, int row)
{
INVOKE2(selectionMove, (id, row));
auto selection = m_selections.value(id);
if (!selection.browser)
return;
QModelIndexList indexes;
indexes.reserve(selection.indexes.size());
for (const auto &index : selection.indexes) {
if (index.isValid())
indexes.append(index);
}
if ( !indexes.isEmpty() )
selection.browser->move(indexes, row);
}
void ScriptableProxy::selectionSort(int id, const QVector<int> &indexes)
{
INVOKE2(selectionSort, (id, indexes));
auto selection = m_selections.value(id);
QList<QPersistentModelIndex> sorted;
sorted.reserve( indexes.size() );
for (const int i : indexes) {
if (i < 0 || i >= selection.indexes.size())
continue;
const auto index = selection.indexes[i];
if ( index.isValid() )
sorted.append(index);
}
selection.indexes = sorted;
if ( !sorted.isEmpty() )
selection.browser->sortItems(sorted);
}
#ifdef HAS_TESTS
void ScriptableProxy::sendKeys(const QString &expectedWidgetName, const QString &keys, int delay)
{
INVOKE2(sendKeys, (expectedWidgetName, keys, delay));
Q_ASSERT( keyClicker()->succeeded() || keyClicker()->failed() );
keyClicker()->sendKeyClicks(expectedWidgetName, keys, delay, 10);
}
bool ScriptableProxy::sendKeysSucceeded()
{
INVOKE(sendKeysSucceeded, ());
return keyClicker()->succeeded();
}
bool ScriptableProxy::sendKeysFailed()
{
INVOKE(sendKeysFailed, ());
return keyClicker()->failed();
}
QString ScriptableProxy::testSelected()
{
INVOKE(testSelected, ());
ClipboardBrowser *browser = m_wnd->browser();
if (!browser)
return QString();
if (browser->length() == 0)
return browser->tabName();
QModelIndexList selectedIndexes = browser->selectionModel()->selectedIndexes();
QStringList result;
result.reserve( selectedIndexes.size() + 1 );
const QModelIndex currentIndex = browser->currentIndex();
result.append(currentIndex.isValid() ? QString::number(currentIndex.row()) : "_");
QList<int> selectedRows;
selectedRows.reserve( selectedIndexes.size() );
for (const auto &index : selectedIndexes)
selectedRows.append(index.row());
std::sort( selectedRows.begin(), selectedRows.end() );
for (int row : selectedRows)
result.append(QString::number(row));
return browser->tabName() + " " + result.join(" ");
}
#endif // HAS_TESTS
void ScriptableProxy::serverLog(const QString &text)
{
INVOKE2(serverLog, (text));
log(text, LogAlways);
}
QString ScriptableProxy::currentWindowTitle()
{
INVOKE(currentWindowTitle, ());
PlatformWindowPtr window = platformNativeInterface()->getCurrentWindow();
return window ? window->getTitle() : QString();
}
int ScriptableProxy::inputDialog(const NamedValueList &values)
{
INVOKE(inputDialog, (values));
InputDialog inputDialog;
inputDialog.dialog = new QDialog(m_wnd);
QDialog &dialog = *inputDialog.dialog;
QString dialogTitle;
QIcon icon;
QVBoxLayout layout(&dialog);
QWidgetList widgets;
widgets.reserve(values.items.size());
QString styleSheet;
QRect geometry(-1, -1, 0, 0);
for (const auto &value : values.items) {
if (value.name == ".title")
dialogTitle = value.value.toString();
else if (value.name == ".icon")
icon = loadIcon(value.value.toString());
else if (value.name == ".style")
styleSheet = value.value.toString();
else if (value.name == ".height")
geometry.setHeight( pointsToPixels(value.value.toInt()) );
else if (value.name == ".width")
geometry.setWidth( pointsToPixels(value.value.toInt()) );
else if (value.name == ".x")
geometry.setX(value.value.toInt());
else if (value.name == ".y")
geometry.setY(value.value.toInt());
else if (value.name == ".label")
createAndSetWidget<QLabel>("text", value.value, &dialog);
else if (value.name == ".defaultChoice")
inputDialog.defaultChoice = value.value.toString();
else
widgets.append( createWidget(value.name, value.value, &inputDialog) );
}
// WORKAROUND for broken initial focus in Qt 6.6 (QTBUG-121514)
if (!widgets.isEmpty())
widgets.first()->setFocus();
dialog.adjustSize();
if (geometry.height() == 0)
geometry.setHeight(dialog.height());
if (geometry.width() == 0)
geometry.setWidth(dialog.width());
if (geometry.isValid())
dialog.resize(geometry.size());
if (geometry.x() >= 0 && geometry.y() >= 0)
dialog.move(geometry.topLeft());
if ( !styleSheet.isEmpty() )
dialog.setStyleSheet(styleSheet);
auto buttons = new QDialogButtonBox(
QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dialog);
QObject::connect( buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept );
QObject::connect( buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject );
layout.addWidget(buttons);
installShortcutToCloseDialog(&dialog, &dialog, Qt::ControlModifier | Qt::Key_Enter);
installShortcutToCloseDialog(&dialog, &dialog, Qt::ControlModifier | Qt::Key_Return);
if (icon.isNull())
icon = appIcon();
dialog.setWindowIcon(icon);
const int dialogId = ++m_lastInputDialogId;
connect(&dialog, &QDialog::finished, this, [this, dialogId, inputDialog, widgets]() {
if (inputDialog.dialog == nullptr)
return;
NamedValueList result;
result.items.reserve( widgets.size() );
if ( inputDialog.dialog->result() ) {
for ( auto w : widgets ) {
const QString propertyName = w->property(propertyWidgetProperty).toString();
const QString name = w->property(propertyWidgetName).toString();
const QVariant value = w->property(propertyName.toUtf8().constData());
result.items.append( NamedValue(name, value) );
}
if ( widgets.isEmpty() )
result.items.append( NamedValue(QString(), true) );
}
QByteArray bytes;
{
QDataStream stream(&bytes, QIODevice::WriteOnly);
stream << dialogId << result;
}
inputDialog.dialog->deleteLater();
emit sendMessage(bytes, CommandInputDialogFinished);
});
// Connecting this directly to QEventLoop::quit() doesn't seem to work always.
connect(this, &ScriptableProxy::abortEvaluation, &dialog, &QDialog::reject);
if ( !dialogTitle.isNull() ) {
dialog.setWindowTitle(dialogTitle);
dialog.setObjectName(QStringLiteral("dialog_") + dialogTitle);
WindowGeometryGuard::create(&dialog);
}
dialog.show();
raiseWindow(&dialog);
return dialogId;
}
void ScriptableProxy::setSelectedItemsData(const QString &mime, const QVariant &value)
{
INVOKE2(setSelectedItemsData, (mime, value));
QList<QPersistentModelIndex> selected = selectedIndexes();
selectionRemoveInvalid(&selected);
ClipboardBrowser *c = browserForIndexes(selected);
if (c == nullptr)
return;
setItemsData(c, selected, mime, value);
}
void ScriptableProxy::filter(const QString &text)
{
INVOKE2(filter, (text));
m_wnd->setFilter(text);
}
QString ScriptableProxy::filter()
{
INVOKE(filter, ());
return m_wnd->filter();
}
QVector<Command> ScriptableProxy::commands()
{
INVOKE(commands, ());
return loadAllCommands();
}
void ScriptableProxy::setCommands(const QVector<Command> &commands)
{
INVOKE2(setCommands, (commands));
m_wnd->setCommands(commands);
}
void ScriptableProxy::addCommands(const QVector<Command> &commands)
{
INVOKE2(addCommands, (commands));
m_wnd->addCommands(commands);
}
QByteArray ScriptableProxy::screenshot(const QString &format, const QString &screenName, bool select)
{
INVOKE(screenshot, (format, screenName, select));
QScreen *selectedScreen = nullptr;
if ( screenName.isEmpty() ) {
const auto mousePosition = QCursor::pos();
const int screenNumber = ::screenNumberAt(mousePosition);
if (screenNumber != -1)
selectedScreen = QGuiApplication::screens().value(screenNumber);
} else {
for ( const auto screen : QApplication::screens() ) {
if (screen->name() == screenName) {
selectedScreen = screen;
break;
}
}
}
if (!selectedScreen)
return QByteArray();
auto pixmap = selectedScreen->grabWindow(0);
const auto geometry = selectedScreen->geometry();
if (select) {
ScreenshotRectWidget rectWidget(pixmap);
rectWidget.setGeometry(geometry);
rectWidget.setWindowState(Qt::WindowFullScreen);
rectWidget.setWindowModality(Qt::ApplicationModal);
rectWidget.show();
raiseWindow(&rectWidget);
while ( !rectWidget.isHidden() )
QCoreApplication::processEvents();
const auto rect = rectWidget.selectionRect;
if ( rect.isValid() ) {
const auto ratio = pixelRatio(&pixmap);
const QRect rect2( rect.topLeft() * ratio, rect.size() * ratio );
pixmap = pixmap.copy(rect2);
}
}
QByteArray bytes;
{
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
if ( !pixmap.save(&buffer, format.toUtf8().constData()) )
return QByteArray();
}
return bytes;
}
QStringList ScriptableProxy::screenNames()
{
INVOKE(screenNames, ());
QStringList result;
const auto screens = QApplication::screens();
result.reserve( screens.size() );
for ( const auto screen : screens )
result.append(screen->name());
return result;
}
KeyboardModifierList ScriptableProxy::queryKeyboardModifiers()
{
INVOKE(queryKeyboardModifiers, ());
return {QApplication::queryKeyboardModifiers()};
}
QPoint ScriptableProxy::pointerPosition()
{
INVOKE(pointerPosition, ());
return QCursor::pos();
}
void ScriptableProxy::setPointerPosition(int x, int y)
{
INVOKE2(setPointerPosition, (x, y));
const QPoint pos(x, y);
#if QT_VERSION < QT_VERSION_CHECK(5,10,0)
const auto screens = QApplication::screens();
const auto found = std::find_if(
std::begin(screens), std::end(screens),
[pos](QScreen *screen) { return screen->geometry().contains(pos); });
if (found == std::end(screens))
return;
QScreen *screen = *found;
#else
QScreen *screen = QGuiApplication::screenAt(pos);
#endif
if (screen)
QCursor::setPos(screen, pos);
}
QString ScriptableProxy::pluginsPath()
{
INVOKE(pluginsPath, ());
return ::pluginsPath();
}
QString ScriptableProxy::themesPath()
{
INVOKE(themesPath, ());
return ::themesPath();
}
QString ScriptableProxy::translationsPath()
{
INVOKE(translationsPath, ());
return ::translationsPath();
}
QString ScriptableProxy::iconColor()
{
INVOKE(iconColor, ());
const auto color = m_wnd->sessionIconColor();
return color.isValid() ? color.name() : QString();
}
bool ScriptableProxy::setIconColor(const QString &colorName)
{
INVOKE(setIconColor, (colorName));
QColor color(colorName);
if ( !colorName.isEmpty() && !color.isValid() )
return false;
m_wnd->setSessionIconColor(color);
return true;
}
QString ScriptableProxy::iconTag()
{
INVOKE(iconTag, ());
return m_wnd->sessionIconTag();
}
void ScriptableProxy::setIconTag(const QString &tag)
{
INVOKE2(setIconTag, (tag));
m_wnd->setSessionIconTag(tag);
}
QString ScriptableProxy::iconTagColor()
{
INVOKE(iconTagColor, ());
return m_wnd->sessionIconTagColor().name();
}
bool ScriptableProxy::setIconTagColor(const QString &colorName)
{
INVOKE(setIconTagColor, (colorName));
QColor color(colorName);
if ( !color.isValid() )
return false;
m_wnd->setSessionIconTagColor(color);
return true;
}
void ScriptableProxy::setClipboardData(const QVariantMap &data)
{
INVOKE2(setClipboardData, (data));
m_wnd->setClipboardData(data);
}
void ScriptableProxy::setTitle(const QString &title)
{
INVOKE2(setTitle, (title));
if (title.isEmpty()) {
const QString defaultTitle = isMonitoringEnabled()
? QString()
: tr("*Clipboard Storing Disabled*", "Main window title if clipboard storing is disabled");
m_wnd->setWindowTitle(defaultTitle);
m_wnd->setTrayTooltip(defaultTitle);
} else {
m_wnd->setWindowTitle(title);
m_wnd->setTrayTooltip(title);
}
}
void ScriptableProxy::setTitleForData(const QVariantMap &data)
{
INVOKE2(setTitleForData, (data));
const QString clipboardContent = textLabelForData(data);
setTitle(clipboardContent);
}
void ScriptableProxy::saveData(const QString &tab, const QVariantMap &data, ClipboardMode mode)
{
INVOKE2(saveData, (tab, data, mode));
auto c = m_wnd->tab(tab);
if (c)
c->addUnique(data, mode);
}
void ScriptableProxy::showDataNotification(const QVariantMap &data)
{
INVOKE2(showDataNotification, (data));
const AppConfig appConfig;
const auto maxLines = appConfig.option<Config::clipboard_notification_lines>();
if (maxLines <= 0)
return;
const auto intervalSeconds = appConfig.option<Config::item_popup_interval>();
if (intervalSeconds == 0)
return;
auto notification = m_wnd->createNotification("CopyQ_clipboard_notification");
notification->setIcon(IconPaste);
notification->setInterval(intervalSeconds * 1000);
const int maximumWidthPoints = appConfig.option<Config::notification_maximum_width>();
const int width = pointsToPixels(maximumWidthPoints) - 16 - 8;
const QStringList formats = data.keys();
const int imageIndex = formats.indexOf(QRegularExpression("^image/.*"));
const QFont &font = notification->widget()
? notification->widget()->font()
: qApp->font();
const bool isHidden = data.contains(mimeHidden);
QString title;
if (data.isEmpty()) {
notification->setInterval(0);
} if ( !isHidden && data.contains(mimeText) ) {
QString text = getTextData(data);
const int n = text.count('\n') + 1;
if (n > 1) {
title = QObject::tr("Text Copied (%n lines)",
"Notification title for multi-line text in clipboard", n);
} else {
title = QObject::tr("Text Copied", "Notification title for single-line text in clipboard");
}
text = elideText(text, font, QString(), false, width, maxLines);
notification->setMessage(text);
} else if (!isHidden && imageIndex != -1) {
QPixmap pix;
const QString &imageFormat = formats[imageIndex];
pix.loadFromData( data[imageFormat].toByteArray(), imageFormat.toLatin1() );
const int height = maxLines * QFontMetrics(font).lineSpacing();
if (pix.width() > width || pix.height() > height)
pix = pix.scaled(QSize(width, height), Qt::KeepAspectRatio);
notification->setPixmap(pix);
} else {
title = QObject::tr("Data Copied", "Notification title for a copied data in clipboard");
const QString text = textLabelForData(data, font, QString(), false, width, maxLines);
notification->setMessage(text);
}
notification->setTitle(title);
}
bool ScriptableProxy::enableMenuItem(int actionId, int currentRun, int menuItemMatchCommandIndex, const QVariantMap &menuItem)
{
INVOKE(enableMenuItem, (actionId, currentRun, menuItemMatchCommandIndex, menuItem));
return m_wnd->setMenuItemEnabled(actionId, currentRun, menuItemMatchCommandIndex, menuItem);
}
QVariantMap ScriptableProxy::setDisplayData(int actionId, const QVariantMap &displayData)
{
INVOKE(setDisplayData, (actionId, displayData));
m_actionData = m_wnd->setDisplayData(actionId, displayData);
return m_actionData;
}
QVector<Command> ScriptableProxy::automaticCommands()
{
INVOKE(automaticCommands, ());
return m_wnd->automaticCommands();
}
QVector<Command> ScriptableProxy::displayCommands()
{
INVOKE(displayCommands, ());
return m_wnd->displayCommands();
}
QVector<Command> ScriptableProxy::scriptCommands()
{
INVOKE(scriptCommands, ());
return m_wnd->scriptCommands();
}
bool ScriptableProxy::openUrls(const QStringList &urls)
{
INVOKE(openUrls, (urls));
for (const auto &url : urls) {
if ( !QDesktopServices::openUrl(QUrl(url)) )
return false;
}
return true;
}
QString ScriptableProxy::loadTheme(const QString &path)
{
INVOKE(loadTheme, (path));
{
const QFileInfo fileInfo(path);
if ( !fileInfo.isFile() || !fileInfo.isReadable() )
return "Failed to read theme";
}
const QSettings settings(path, QSettings::IniFormat);
if ( settings.status() != QSettings::NoError )
return "Failed to load theme";
m_wnd->loadTheme(settings);
if ( settings.status() != QSettings::NoError )
return "Failed to parse theme";
return QString();
}
QByteArray ScriptableProxy::getClipboardData(const QString &mime, ClipboardMode mode)
{
INVOKE(getClipboardData, (mime, mode));
const QMimeData *data = m_wnd->getClipboardData(mode);
if (!data)
return QByteArray();
if (mime == "?")
return data->formats().join("\n").toUtf8() + '\n';
return cloneData(*data, QStringList(mime)).value(mime).toByteArray();
}
bool ScriptableProxy::hasClipboardFormat(const QString &mime, ClipboardMode mode)
{
INVOKE(hasClipboardFormat, (mime, mode));
const QMimeData *data = m_wnd->getClipboardData(mode);
return data && data->hasFormat(mime);
}
QStringList ScriptableProxy::styles()
{
INVOKE(styles, ());
return QStyleFactory::keys();
}
void ScriptableProxy::setScriptOverrides(const QVector<int> &overrides)
{
INVOKE2(setScriptOverrides, (overrides));
m_wnd->setScriptOverrides(overrides, m_actionId);
}
ClipboardBrowser *ScriptableProxy::fetchBrowser(const QString &tabName)
{
if (tabName.isEmpty()) {
const QString defaultTabName = m_actionData.value(mimeCurrentTab).toString();
if (!defaultTabName.isEmpty())
return fetchBrowser(defaultTabName);
}
return tabName.isEmpty() ? m_wnd->browser(0) : m_wnd->tab(tabName);
}
QVariantMap ScriptableProxy::itemData(const QString &tabName, int i)
{
auto c = fetchBrowser(tabName);
return c ? c->copyIndex( c->index(i) ) : QVariantMap();
}
QByteArray ScriptableProxy::itemData(const QString &tabName, int i, const QString &mime)
{
const QVariantMap data = itemData(tabName, i);
if ( data.isEmpty() )
return QByteArray();
if (mime == "?")
return QStringList(data.keys()).join("\n").toUtf8() + '\n';
if (mime == mimeItems)
return serializeData(data);
return data.value(mime).toByteArray();
}
void ScriptableProxy::setItemsData(
ClipboardBrowser *c, const QList<QPersistentModelIndex> &indexes, const QString &mime, const QVariant &value)
{
QMap<QPersistentModelIndex, QVariantMap> itemsData;
for (const auto &index : indexes) {
if ( !index.isValid() )
continue;
QVariantMap data = index.data(contentType::data).toMap();
if (value.isValid())
data[mime] = value;
else
data.remove(mime);
itemsData[index] = data;
}
c->setItemsData(itemsData);
}
template<typename T>
T ScriptableProxy::getSelectionData(const QString &mime)
{
QVariant value = m_actionData.value(mime);
if ( !value.isValid() && !m_actionData.contains(mimeCurrentTab) && getSelectionData() )
value = m_actionData.value(mime);
return value.value<T>();
}
QPersistentModelIndex ScriptableProxy::currentIndex()
{
return getSelectionData<QPersistentModelIndex>(mimeCurrentItem);
}
QList<QPersistentModelIndex> ScriptableProxy::selectedIndexes()
{
return getSelectionData<QList<QPersistentModelIndex>>(mimeSelectedItems);
}
ClipboardBrowser *ScriptableProxy::browserForIndexes(const QList<QPersistentModelIndex> &indexes) const
{
for (const auto &index : indexes) {
if ( index.isValid() )
return m_wnd->browserForItem(index);
}
return nullptr;
}
QVariant ScriptableProxy::waitForFunctionCallFinished(int functionCallId)
{
if (m_disconnected)
return QVariant();
QVariant result;
QEventLoop loop;
connect(this, &ScriptableProxy::functionCallFinished, &loop,
[&](int receivedFunctionCallId, const QVariant &returnValue) {
if (receivedFunctionCallId != functionCallId)
return;
result = returnValue;
loop.quit();
});
connect(this, &ScriptableProxy::abortEvaluation, &loop, &QEventLoop::quit);
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, &loop, &QEventLoop::quit);
loop.exec();
return result;
}
bool ScriptableProxy::getSelectionData()
{
auto c = m_wnd->browser();
if (c == nullptr)
return false;
const QVariantMap data = selectionData(*c);
for (auto it = data.constBegin(); it != data.constEnd(); ++it)
m_actionData[it.key()] = it.value();
return true;
}
#ifdef HAS_TESTS
KeyClicker *ScriptableProxy::keyClicker()
{
if (!m_keyClicker)
m_keyClicker = new KeyClicker(m_wnd, this);
return m_keyClicker;
}
#endif // HAS_TESTS
QString pluginsPath()
{
QDir dir;
if (platformNativeInterface()->findPluginDir(&dir))
return dir.absolutePath();
return QString();
}
QString themesPath()
{
return platformNativeInterface()->themePrefix();
}
QString translationsPath()
{
return platformNativeInterface()->translationPrefix();
}
void setClipboardMonitorRunning(bool running)
{
QSettings settings(
QSettings::IniFormat,
QSettings::UserScope,
QCoreApplication::organizationName(),
QCoreApplication::applicationName() + "-monitor");
settings.setValue(QStringLiteral("running"), running);
}
bool isClipboardMonitorRunning()
{
const QSettings settings(
QSettings::IniFormat,
QSettings::UserScope,
QCoreApplication::organizationName(),
QCoreApplication::applicationName() + "-monitor");
return settings.value(QStringLiteral("running")).toBool();
}
| 80,049
|
C++
|
.cpp
| 2,260
| 29.659292
| 132
| 0.673125
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,183
|
platformcommon.cpp
|
hluk_CopyQ/src/platform/platformcommon.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "platformcommon.h"
#include "platformwindow.h"
#include "common/log.h"
#include "common/appconfig.h"
#include <QEventLoop>
#include <QRegularExpression>
#include <QSettings>
#include <QTimer>
namespace {
const QLatin1String optionName("paste_with_ctrl_v_windows");
} // namespace
bool pasteWithCtrlV(PlatformWindow &window, const AppConfig &config)
{
const auto value = config.option<Config::window_paste_with_ctrl_v_regex>();
const auto pattern = value.isEmpty() ? QSettings().value(optionName).toString() : value;
if (pattern.isEmpty())
return false;
const QRegularExpression re(pattern);
if (!re.isValid()) {
log(QString("Invalid regular expression in option \"%1\": %2")
.arg(optionName, re.errorString()), LogWarning);
return false;
}
const QString windowTitle = window.getTitle();
if ( !windowTitle.contains(re) ) {
COPYQ_LOG(QString("Paste with standard shortcut to window \"%1\".")
.arg(windowTitle));
return false;
}
COPYQ_LOG(QString("Paste with Ctrl+V requested with option \"%1\" for window \"%2\".")
.arg(optionName, windowTitle));
return true;
}
void waitMs(int msec)
{
if (msec <= 0)
return;
QEventLoop loop;
QTimer t;
QObject::connect(&t, &QTimer::timeout, &loop, &QEventLoop::quit);
t.start(msec);
loop.exec();
}
| 1,457
|
C++
|
.cpp
| 44
| 28.181818
| 92
| 0.67
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,184
|
dummyclipboard.cpp
|
hluk_CopyQ/src/platform/dummy/dummyclipboard.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "dummyclipboard.h"
#include "common/common.h"
#include "common/log.h"
#include "common/mimetypes.h"
#include <QGuiApplication>
#include <QMimeData>
#include <QStringList>
QClipboard::Mode modeToQClipboardMode(ClipboardMode mode)
{
switch (mode) {
case ClipboardMode::Selection:
return QClipboard::Selection;
case ClipboardMode::Clipboard:
return QClipboard::Clipboard;
}
Q_ASSERT(false);
return QClipboard::Clipboard;
}
void DummyClipboard::startMonitoring(const QStringList &)
{
connect(QGuiApplication::clipboard(), &QClipboard::changed,
this, &DummyClipboard::onClipboardChanged);
}
QVariantMap DummyClipboard::data(ClipboardMode mode, const QStringList &formats) const
{
const QMimeData *data = mimeData(mode);
if (data == nullptr)
return {};
const bool isDataSecret = isHidden(*data);
QVariantMap dataMap = cloneData(*data, formats, clipboardSequenceNumber(mode));
if (isDataSecret)
dataMap[mimeSecret] = QByteArrayLiteral("1");
return dataMap;
}
void DummyClipboard::setData(ClipboardMode mode, const QVariantMap &dataMap)
{
QGuiApplication::clipboard()->setMimeData( createMimeData(dataMap), modeToQClipboardMode(mode) );
}
void DummyClipboard::setRawData(ClipboardMode mode, QMimeData *mimeData)
{
QGuiApplication::clipboard()->setMimeData( mimeData, modeToQClipboardMode(mode) );
}
const QMimeData *DummyClipboard::rawMimeData(ClipboardMode mode) const
{
return QGuiApplication::clipboard()->mimeData( modeToQClipboardMode(mode) );
}
const QMimeData *DummyClipboard::mimeData(ClipboardMode mode) const
{
const auto modeText = mode == ClipboardMode::Clipboard ? "clipboard" : "selection";
COPYQ_LOG_VERBOSE( QStringLiteral("Getting %1 data").arg(modeText) );
const QMimeData *data = rawMimeData(mode);
if (!data) {
log( QStringLiteral("Null data in %1").arg(modeText), LogError );
return nullptr;
}
COPYQ_LOG_VERBOSE( QStringLiteral("Got %1 data").arg(modeText) );
return data;
}
bool DummyClipboard::isHidden(const QMimeData &data) const
{
const QByteArray passwordManagerHint = data.data(QStringLiteral("x-kde-passwordManagerHint"));
return passwordManagerHint == QByteArrayLiteral("secret");
}
void DummyClipboard::onChanged(int mode)
{
if (mode == QClipboard::Clipboard)
emit changed(ClipboardMode::Clipboard);
}
void DummyClipboard::onClipboardChanged(QClipboard::Mode mode)
{
onChanged(static_cast<int>(mode));
}
| 2,576
|
C++
|
.cpp
| 73
| 31.616438
| 101
| 0.748792
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
18,185
|
dummyplatform.cpp
|
hluk_CopyQ/src/platform/dummy/dummyplatform.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "dummyplatform.h"
#include "dummyclipboard.h"
#include "app/applicationexceptionhandler.h"
#include <QApplication>
#include <QCoreApplication>
#include <QDir>
#include <QStringList>
PlatformNativeInterface *platformNativeInterface()
{
static DummyPlatform platform;
return &platform;
}
QCoreApplication *DummyPlatform::createConsoleApplication(int &argc, char **argv)
{
return new ApplicationExceptionHandler<QCoreApplication>(argc, argv);
}
QApplication *DummyPlatform::createServerApplication(int &argc, char **argv)
{
return new ApplicationExceptionHandler<QApplication>(argc, argv);
}
QGuiApplication *DummyPlatform::createMonitorApplication(int &argc, char **argv)
{
return new ApplicationExceptionHandler<QGuiApplication>(argc, argv);
}
QGuiApplication *DummyPlatform::createClipboardProviderApplication(int &argc, char **argv)
{
return new ApplicationExceptionHandler<QGuiApplication>(argc, argv);
}
QCoreApplication *DummyPlatform::createClientApplication(int &argc, char **argv)
{
return new ApplicationExceptionHandler<QCoreApplication>(argc, argv);
}
QGuiApplication *DummyPlatform::createTestApplication(int &argc, char **argv)
{
return new ApplicationExceptionHandler<QGuiApplication>(argc, argv);
}
PlatformClipboardPtr DummyPlatform::clipboard()
{
return PlatformClipboardPtr(new DummyClipboard());
}
bool DummyPlatform::findPluginDir(QDir *pluginsDir)
{
pluginsDir->setPath( qApp->applicationDirPath() );
return pluginsDir->cd("plugins");
}
QString DummyPlatform::defaultEditorCommand()
{
return "gedit %1";
}
QString DummyPlatform::translationPrefix()
{
return QString();
}
QStringList DummyPlatform::getCommandLineArguments(int argc, char **argv)
{
QStringList arguments;
for (int i = 1; i < argc; ++i)
arguments.append( QString::fromUtf8(argv[i]) );
return arguments;
}
| 1,933
|
C++
|
.cpp
| 61
| 29.213115
| 90
| 0.793959
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,186
|
unixsignalhandler.cpp
|
hluk_CopyQ/src/platform/unix/unixsignalhandler.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "unixsignalhandler.h"
#include "common/log.h"
#include <QCoreApplication>
#include <QSocketNotifier>
#include <csignal>
#include <sys/socket.h>
#include <unistd.h>
namespace {
namespace SignalAction {
enum SignalAction { Write, Read, Count };
}
int signalFd[SignalAction::Count];
QSocketNotifier *signalFdNotifier = nullptr;
/**
* Catch Unix signal.
*
* Since this can be called at any time, Qt code cannot be handled here. For example,
* this can be called from QString constructor which can easily deadlock the application on
* a mutex when trying to create new QString from this handler. Also note that creating
* QSettings recursively can result in resetting application settings.
*/
void exitSignalHandler(int)
{
const qint64 pid = QCoreApplication::applicationPid();
const auto written = ::write(signalFd[SignalAction::Write], &pid, sizeof(pid));
if (written == -1)
log("Failed to handle signal!", LogError);
}
void handleSignal()
{
signalFdNotifier->setEnabled(false);
qint64 pid;
if ( ::read(signalFd[SignalAction::Read], &pid, sizeof(pid)) != sizeof(pid) ) {
COPYQ_LOG("Incorrect number of bytes read from Unix signal socket!");
signalFdNotifier->setEnabled(true);
} else if (pid != QCoreApplication::applicationPid()) {
COPYQ_LOG("Wrong PID written to Unix signal socket!");
signalFdNotifier->setEnabled(true);
} else {
COPYQ_LOG("Terminating application on signal.");
QCoreApplication::exit();
}
}
} // namespace
bool initUnixSignalHandler()
{
// Safely quit application on TERM and HUP signals.
struct sigaction sigact{};
sigact.sa_handler = exitSignalHandler;
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = 0;
sigact.sa_flags |= SA_RESTART;
if ( sigaction(SIGINT, &sigact, nullptr) > 0
|| sigaction(SIGTERM, &sigact, nullptr) > 0 )
{
log("sigaction() failed!", LogError);
return false;
}
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, signalFd)) {
log("socketpair() failed!", LogError);
return false;
}
return true;
}
void startUnixSignalHandler()
{
signalFdNotifier = new QSocketNotifier(signalFd[SignalAction::Read], QSocketNotifier::Read);
QObject::connect(signalFdNotifier, &QSocketNotifier::activated, handleSignal);
}
| 2,400
|
C++
|
.cpp
| 70
| 30.242857
| 96
| 0.709468
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
18,187
|
x11platform.cpp
|
hluk_CopyQ/src/platform/x11/x11platform.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "x11platform.h"
#include "x11info.h"
#include "app/applicationexceptionhandler.h"
#include "common/log.h"
#include "common/textdata.h"
#include <QApplication>
#include <QCoreApplication>
#include <QDir>
#include <QRegularExpression>
#include <QStringList>
#include <QVariant>
#include <QWidget>
#include "x11platformclipboard.h"
#ifdef COPYQ_WITH_X11
# include "x11platformwindow.h"
# include <X11/Xatom.h>
# include <X11/Xlib.h>
#endif
#include <memory>
namespace {
const char *defaultDesktopFileContent =
R"([Desktop Entry]
Name=CopyQ
Icon=copyq
GenericName=Clipboard Manager
Type=Application
Terminal=false
X-KDE-autostart-after=panel
X-KDE-StartupNotify=false
X-KDE-UniqueApplet=true
)";
#ifdef COPYQ_WITH_X11
int (*old_xio_errhandler)(Display *) = nullptr;
// Try to handle X11 fatal error gracefully.
int copyq_xio_errhandler(Display *display)
{
// Try to call MainWindow::saveTabs().
if ( QCoreApplication::instance() ) {
for ( auto obj : qApp->topLevelWidgets() ) {
if (obj->objectName() == "MainWindow") {
QMetaObject::invokeMethod(obj, "saveTabs");
break;
}
}
}
// Call the old handler (possibly for Qt).
if (old_xio_errhandler)
old_xio_errhandler(display);
// As documentation for XSetIOErrorHandler states, this function should not return.
exit(1);
}
#endif
#ifdef COPYQ_DESKTOP_FILE
QString getDesktopFilename()
{
const char *path = getenv("XDG_CONFIG_HOME");
QString filename = path ? getTextData(path) : QDir::homePath() + "/.config";
filename.append("/autostart/" + QCoreApplication::applicationName() + ".desktop");
return filename;
}
#endif
void printFileError(const QFile &file, const char *message, LogLevel logLevel = LogError)
{
log( QString("%1 \"%2\": %3")
.arg( QString::fromLatin1(message), file.fileName(), file.errorString()),
logLevel );
}
void maybePrintFileError(const QFile &file, const char *message)
{
if (file.error() != QFile::NoError)
printFileError(file, message);
}
} // namespace
PlatformNativeInterface *platformNativeInterface()
{
static X11Platform platform;
return &platform;
}
X11Platform::~X11Platform() = default;
PlatformWindowPtr X11Platform::getWindow(WId winId)
{
#ifdef COPYQ_WITH_X11
if (!X11Info::isPlatformX11())
return PlatformWindowPtr();
std::unique_ptr<X11PlatformWindow> window(new X11PlatformWindow(winId));
return PlatformWindowPtr(window->isValid() ? window.release() : nullptr);
#else
Q_UNUSED(winId)
return PlatformWindowPtr();
#endif
}
PlatformWindowPtr X11Platform::getCurrentWindow()
{
#ifdef COPYQ_WITH_X11
if (!X11Info::isPlatformX11())
return PlatformWindowPtr();
std::unique_ptr<X11PlatformWindow> window(new X11PlatformWindow());
return PlatformWindowPtr(window->isValid() ? window.release() : nullptr);
#else
return PlatformWindowPtr();
#endif
}
bool X11Platform::canAutostart()
{
#if defined(COPYQ_AUTOSTART) && defined(COPYQ_DESKTOP_FILE)
return true;
#else
return false;
#endif
}
bool X11Platform::isAutostartEnabled()
{
#if defined(COPYQ_AUTOSTART) && defined(COPYQ_DESKTOP_FILE)
const QString filename = getDesktopFilename();
QFile desktopFile(filename);
if ( !desktopFile.exists() )
return false;
if ( !desktopFile.open(QIODevice::ReadOnly | QIODevice::Text) )
return false;
const QRegularExpression re("^Hidden\\s*=\\s*([a-zA-Z01]+)");
while ( !desktopFile.atEnd() ) {
const QString line = getTextData(desktopFile.readLine());
const auto m = re.match(line);
if (m.hasMatch()) {
const QString value = m.captured(1);
return !(value.startsWith("True") || value.startsWith("true") || value.startsWith("0"));
}
}
return true;
#else
return false;
#endif
}
void X11Platform::setAutostartEnabled(bool enable)
{
#if defined(COPYQ_AUTOSTART) && defined(COPYQ_DESKTOP_FILE)
if ( isAutostartEnabled() == enable )
return;
const QString filename = getDesktopFilename();
const auto autostartPath = QDir::cleanPath(filename + "/..");
QDir autostartDir(autostartPath);
if ( !autostartDir.mkpath(".") ) {
log( QString("Failed to create autostart path \"%1\"").arg(autostartPath) );
return;
}
QFile desktopFile2(filename + ".new");
if ( !desktopFile2.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text) ) {
printFileError(desktopFile2, "Failed to create new desktop file");
return;
}
const QRegularExpression re("^(Hidden|X-GNOME-Autostart-enabled|Exec)\\s*=\\s*");
QFile desktopFile(filename);
bool createUserDesktopFile = !desktopFile.exists();
if (createUserDesktopFile)
desktopFile.setFileName(COPYQ_DESKTOP_FILE);
if ( desktopFile.open(QIODevice::ReadOnly | QIODevice::Text) ) {
while ( !desktopFile.atEnd() ) {
const QString line = getTextData(desktopFile.readLine());
if ( !line.contains(re) )
desktopFile2.write(line.toUtf8());
}
desktopFile.close();
maybePrintFileError(desktopFile, "Failed to read desktop file");
} else {
// Installed desktop file not found (can happen when running tests).
printFileError(desktopFile, "Failed to open desktop file", LogNote);
desktopFile2.write(defaultDesktopFileContent);
}
#ifdef COPYQ_AUTOSTART_COMMAND
QString cmd = COPYQ_AUTOSTART_COMMAND;
#else
QString cmd = "\"" + QApplication::applicationFilePath() + "\"";
#endif
const QString sessionName = qApp->property("CopyQ_session_name").toString();
if ( !sessionName.isEmpty() )
cmd.append(" -s " + sessionName);
desktopFile2.write("Exec=" + cmd.toUtf8() + "\n");
desktopFile2.write("Hidden=");
desktopFile2.write(enable ? "false" : "true");
desktopFile2.write("\n");
desktopFile2.write("X-GNOME-Autostart-enabled=");
desktopFile2.write(enable ? "true" : "false");
desktopFile2.write("\n");
QFile::remove(filename);
desktopFile2.rename(filename);
maybePrintFileError(desktopFile2, "Failed to write desktop file");
#else
Q_UNUSED(enable)
#endif
}
QCoreApplication *X11Platform::createConsoleApplication(int &argc, char **argv)
{
return new ApplicationExceptionHandler<QCoreApplication>(argc, argv);
}
QApplication *X11Platform::createServerApplication(int &argc, char **argv)
{
#ifdef COPYQ_WITH_X11
if (X11Info::isPlatformX11())
old_xio_errhandler = XSetIOErrorHandler(copyq_xio_errhandler);
#endif
return new ApplicationExceptionHandler<QApplication>(argc, argv);
}
QGuiApplication *X11Platform::createMonitorApplication(int &argc, char **argv)
{
return new ApplicationExceptionHandler<QGuiApplication>(argc, argv);
}
QGuiApplication *X11Platform::createClipboardProviderApplication(int &argc, char **argv)
{
return new ApplicationExceptionHandler<QGuiApplication>(argc, argv);
}
QCoreApplication *X11Platform::createClientApplication(int &argc, char **argv)
{
return new ApplicationExceptionHandler<QCoreApplication>(argc, argv);
}
QGuiApplication *X11Platform::createTestApplication(int &argc, char **argv)
{
return new ApplicationExceptionHandler<QGuiApplication>(argc, argv);
}
PlatformClipboardPtr X11Platform::clipboard()
{
return PlatformClipboardPtr(new X11PlatformClipboard());
}
QStringList X11Platform::getCommandLineArguments(int argc, char **argv)
{
if (argc == 0)
return QStringList();
QStringList arguments;
arguments.reserve(argc - 1);
for (int i = 1; i < argc; ++i)
arguments.append( QString::fromUtf8(argv[i]) );
return arguments;
}
bool X11Platform::findPluginDir(QDir *pluginsDir)
{
pluginsDir->setPath( qApp->applicationDirPath() );
if ( pluginsDir->dirName() == QLatin1String("bin")
&& pluginsDir->cdUp()
&& (pluginsDir->cd(QLatin1String("lib64")) || pluginsDir->cd(QLatin1String("lib")))
&& pluginsDir->cd(QLatin1String("copyq")) )
{
// OK, installed in /usr/local/bin or /usr/bin.
return true;
}
pluginsDir->setPath( qApp->applicationDirPath() );
if ( pluginsDir->cd(QLatin1String("plugins")) ) {
// OK, plugins in same directory as executable.
pluginsDir->cd(QLatin1String("copyq"));
return true;
}
return false;
}
QString X11Platform::defaultEditorCommand()
{
return QLatin1String("gedit --standalone -- %1");
}
QString X11Platform::translationPrefix()
{
return QString();
}
| 8,689
|
C++
|
.cpp
| 260
| 29.134615
| 100
| 0.704708
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,188
|
x11platformwindow.cpp
|
hluk_CopyQ/src/platform/x11/x11platformwindow.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "x11platformwindow.h"
#include "x11info.h"
#include "common/appconfig.h"
#include "common/log.h"
#include "common/sleeptimer.h"
#include "gui/clipboardspy.h"
#include "platform/platformcommon.h"
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/keysym.h>
#ifdef HAS_X11TEST
# include <X11/extensions/XTest.h>
#endif
#include <unistd.h> // usleep()
namespace {
class KeyPressTester final {
public:
explicit KeyPressTester(Display *display)
: m_display(display)
{
XQueryKeymap(m_display, m_keyMap);
}
bool isPressed(KeySym key) const
{
const KeyCode keyCode = XKeysymToKeycode(m_display, key);
return (m_keyMap[keyCode >> 3] >> (keyCode & 7)) & 1;
}
private:
Display *m_display;
char m_keyMap[32]{};
};
#ifdef HAS_X11TEST
void fakeKeyEvent(Display* display, unsigned int keyCode, Bool isPress, unsigned long delayMs = CurrentTime)
{
XTestFakeKeyEvent(display, keyCode, isPress, delayMs);
XSync(display, False);
}
void simulateModifierKeyPress(Display *display, const QList<int> &modCodes, Bool keyDown)
{
for (int modCode : modCodes) {
const auto keySym = static_cast<KeySym>(modCode);
KeyCode keyCode = XKeysymToKeycode(display, keySym);
fakeKeyEvent(display, keyCode, keyDown);
}
}
bool isModifierPressed(Display *display)
{
KeyPressTester tester(display);
return tester.isPressed(XK_Shift_L)
|| tester.isPressed(XK_Shift_R)
|| tester.isPressed(XK_Control_L)
|| tester.isPressed(XK_Control_R)
|| tester.isPressed(XK_Meta_L)
|| tester.isPressed(XK_Meta_R)
|| tester.isPressed(XK_Alt_L)
|| tester.isPressed(XK_Alt_R)
|| tester.isPressed(XK_Super_L)
|| tester.isPressed(XK_Super_R)
|| tester.isPressed(XK_Hyper_L)
|| tester.isPressed(XK_Hyper_R);
}
bool waitForModifiersReleased(Display *display, const AppConfig &config)
{
const int maxWaitForModsReleaseMs = config.option<Config::window_wait_for_modifier_released_ms>();
if (maxWaitForModsReleaseMs >= 0) {
SleepTimer t(maxWaitForModsReleaseMs);
while (t.sleep()) {
if (!isModifierPressed(display))
return true;
}
}
return !isModifierPressed(display);
}
void simulateKeyPress(Display *display, const QList<int> &modCodes, unsigned int key, const AppConfig &config)
{
// Wait for user to release modifiers.
if (!waitForModifiersReleased(display, config))
return;
simulateModifierKeyPress(display, modCodes, True);
const KeyCode keyCode = XKeysymToKeycode(display, key);
fakeKeyEvent(display, keyCode, True);
// This is needed to paste into URL bar in Chrome.
const unsigned long delayMs = config.option<Config::window_key_press_time_ms>();
fakeKeyEvent(display, keyCode, False, delayMs);
simulateModifierKeyPress(display, modCodes, False);
XSync(display, False);
}
#else
void simulateKeyPress(Display *display, Window window, unsigned int modifiers, unsigned int key)
{
XKeyEvent event;
XEvent *xev = reinterpret_cast<XEvent *>(&event);
event.display = display;
event.window = window;
event.root = DefaultRootWindow(display);
event.subwindow = None;
event.time = CurrentTime;
event.x = 1;
event.y = 1;
event.x_root = 1;
event.y_root = 1;
event.same_screen = True;
event.keycode = XKeysymToKeycode(display, key);
event.state = modifiers;
event.type = KeyPress;
XSendEvent(display, window, True, KeyPressMask, xev);
XSync(display, False);
event.type = KeyRelease;
XSendEvent(display, window, True, KeyPressMask, xev);
XSync(display, False);
}
#endif
class X11WindowProperty final {
public:
X11WindowProperty(Display *display, Window w, Atom property, long longOffset,
long longLength, Atom reqType)
{
if ( XGetWindowProperty(display, w, property, longOffset, longLength, false,
reqType, &type, &format, &len, &remain, &data) != Success )
{
data = nullptr;
}
}
~X11WindowProperty()
{
if (data != nullptr)
XFree(data);
}
bool isValid() const { return data != nullptr; }
X11WindowProperty(const X11WindowProperty &) = delete;
X11WindowProperty &operator=(const X11WindowProperty &) = delete;
Atom type{};
int format{};
unsigned long len{};
unsigned long remain{};
unsigned char *data;
};
Window getCurrentWindow()
{
if (!X11Info::isPlatformX11())
return 0L;
auto display = X11Info::display();
if (!display)
return 0L;
XSync(display, False);
static Atom atomWindow = XInternAtom(display, "_NET_ACTIVE_WINDOW", true);
X11WindowProperty property(display, DefaultRootWindow(display), atomWindow, 0l, 1l, XA_WINDOW);
if ( property.isValid() && property.type == XA_WINDOW && property.format == 32 && property.len == 1)
return *reinterpret_cast<Window *>(property.data);
return 0L;
}
} // namespace
X11PlatformWindow::X11PlatformWindow()
: m_window(getCurrentWindow())
{
}
X11PlatformWindow::X11PlatformWindow(quintptr winId)
: m_window(winId)
{
}
QString X11PlatformWindow::getTitle()
{
Q_ASSERT( isValid() );
if (!X11Info::isPlatformX11())
return QString();
auto display = X11Info::display();
if (!display)
return QString();
static Atom atomName = XInternAtom(display, "_NET_WM_NAME", false);
static Atom atomUTF8 = XInternAtom(display, "UTF8_STRING", false);
X11WindowProperty property(display, m_window, atomName, 0, (~0L), atomUTF8);
if ( property.isValid() ) {
const auto len = static_cast<int>(property.len);
QByteArray result(reinterpret_cast<const char *>(property.data), len);
return QString::fromUtf8(result);
}
return QString();
}
void X11PlatformWindow::raise()
{
Q_ASSERT( isValid() );
if (!X11Info::isPlatformX11())
return;
auto display = X11Info::display();
if (!display)
return;
COPYQ_LOG( QString("Raising window \"%1\"").arg(getTitle()) );
XClientMessageEvent e{};
memset(&e, 0, sizeof(e));
e.type = ClientMessage;
e.display = display;
e.window = m_window;
e.message_type = XInternAtom(display, "_NET_ACTIVE_WINDOW", False);
e.format = 32;
e.data.l[0] = 2;
e.data.l[1] = CurrentTime;
e.data.l[2] = 0;
e.data.l[3] = 0;
e.data.l[4] = 0;
XWindowAttributes wattr{};
XGetWindowAttributes(display, m_window, &wattr);
if (wattr.map_state == IsViewable) {
XSendEvent(display, wattr.screen->root, False,
SubstructureNotifyMask | SubstructureRedirectMask,
reinterpret_cast<XEvent*>(&e));
XSync(display, False);
XRaiseWindow(display, m_window);
XSetInputFocus(display, m_window, RevertToPointerRoot, CurrentTime);
XSync(display, False);
}
}
void X11PlatformWindow::pasteClipboard()
{
const AppConfig config;
if ( pasteWithCtrlV(*this, config) )
sendKeyPress(XK_Control_L, XK_V, config);
else
sendKeyPress(XK_Shift_L, XK_Insert, config);
}
void X11PlatformWindow::copy()
{
const AppConfig config;
ClipboardSpy spy(ClipboardMode::Clipboard, QByteArray());
sendKeyPress(XK_Control_L, XK_C, config);
spy.wait();
}
bool X11PlatformWindow::isValid() const
{
return m_window != 0L;
}
bool X11PlatformWindow::waitForFocus(int ms)
{
Q_ASSERT( isValid() );
if (ms >= 0) {
SleepTimer t(ms);
while (t.sleep()) {
const auto currentWindow = getCurrentWindow();
if (currentWindow == m_window)
return true;
}
}
return m_window == getCurrentWindow();
}
void X11PlatformWindow::sendKeyPress(int modifier, int key, const AppConfig &config)
{
Q_ASSERT( isValid() );
if ( !waitForFocus(config.option<Config::window_wait_before_raise_ms>()) ) {
raise();
if ( !waitForFocus(config.option<Config::window_wait_raised_ms>()) ) {
COPYQ_LOG( QString("Failed to focus window \"%1\"").arg(getTitle()) );
return;
}
}
waitMs(config.option<Config::window_wait_after_raised_ms>());
if (!X11Info::isPlatformX11())
return;
auto display = X11Info::display();
if (!display)
return;
#ifdef HAS_X11TEST
simulateKeyPress(display, QList<int>() << modifier, static_cast<uint>(key), config);
#else
const int modifierMask = (modifier == XK_Control_L) ? ControlMask : ShiftMask;
simulateKeyPress(display, m_window, modifierMask, key);
#endif
}
| 8,852
|
C++
|
.cpp
| 267
| 27.734082
| 110
| 0.661425
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,189
|
x11platformclipboard.cpp
|
hluk_CopyQ/src/platform/x11/x11platformclipboard.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include <QApplication>
#include "x11platformclipboard.h"
#include "x11info.h"
#include "common/common.h"
#include "common/mimetypes.h"
#include "common/log.h"
#include "common/timer.h"
#include "systemclipboard/waylandclipboard.h"
#include <QDataStream>
#ifdef COPYQ_WITH_X11
# include <X11/Xlib.h>
# include <X11/Xatom.h>
#endif
#include <QClipboard>
#include <QMimeData>
#include <QPointer>
namespace {
constexpr auto minCheckAgainIntervalMs = 50;
constexpr auto maxCheckAgainIntervalMs = 500;
constexpr auto maxRetryCount = 3;
/// Return true only if selection is incomplete, i.e. mouse button or shift key is pressed.
bool isSelectionIncomplete()
{
#ifdef COPYQ_WITH_X11
if (!X11Info::isPlatformX11())
return false;
auto display = X11Info::display();
if (!display)
return false;
// If mouse button or shift is pressed then assume that user is selecting text.
XButtonEvent event{};
XQueryPointer(display, DefaultRootWindow(display),
&event.root, &event.window,
&event.x_root, &event.y_root,
&event.x, &event.y,
&event.state);
return event.state & (Button1Mask | ShiftMask);
#else
return true;
#endif
}
} // namespace
X11PlatformClipboard::X11PlatformClipboard()
{
m_clipboardData.mode = ClipboardMode::Clipboard;
m_selectionData.mode = ClipboardMode::Selection;
// Create Wayland clipboard instance so it can start receiving new data.
if ( !X11Info::isPlatformX11() ) {
m_selectionSupported = WaylandClipboard::instance()->isSelectionSupported();
}
}
void X11PlatformClipboard::startMonitoring(const QStringList &formats)
{
m_clipboardData.formats = formats;
// Avoid asking apps for bigger data when mouse selection changes.
// This could make the app hang for a moment.
m_selectionData.formats.append(mimeText);
m_selectionData.formats.append(mimeTextUtf8);
for (auto &format : formats) {
if (!format.startsWith(QLatin1String("image/")) && !format.startsWith(QLatin1String("text/")))
m_selectionData.formats.append(format);
}
if ( m_selectionData.enabled && !QGuiApplication::clipboard()->supportsSelection() ) {
log("X11 selection is not supported, disabling.");
m_selectionData.enabled = false;
}
if ( !X11Info::isPlatformX11() ) {
connect(WaylandClipboard::instance(), &WaylandClipboard::changed,
this, [this](QClipboard::Mode mode){ onClipboardChanged(mode); });
}
// Ignore the initial clipboard content since
// it won't have the correct owner's window title.
m_clipboardData.ignoreNext = true;
m_selectionData.ignoreNext = true;
QTimer::singleShot(5000, this, [this](){
m_clipboardData.ignoreNext = false;
m_selectionData.ignoreNext = false;
});
for (auto clipboardData : {&m_clipboardData, &m_selectionData}) {
clipboardData->owner.clear();
clipboardData->newOwner.clear();
if ( X11Info::isPlatformX11() ) {
updateClipboardData(clipboardData);
useNewClipboardData(clipboardData);
}
}
initSingleShotTimer( &m_timerCheckAgain, 0, this, &X11PlatformClipboard::check );
initSingleShotTimer( &m_clipboardData.timerEmitChange, 0, this, [this](){
useNewClipboardData(&m_clipboardData);
} );
initSingleShotTimer( &m_selectionData.timerEmitChange, 0, this, [this](){
useNewClipboardData(&m_selectionData);
} );
m_monitoring = true;
DummyClipboard::startMonitoring(formats);
}
void X11PlatformClipboard::setMonitoringEnabled(ClipboardMode mode, bool enable)
{
auto &clipboardData = mode == ClipboardMode::Clipboard ? m_clipboardData : m_selectionData;
clipboardData.enabled = enable;
}
QVariantMap X11PlatformClipboard::data(ClipboardMode mode, const QStringList &formats) const
{
if (!m_monitoring)
return DummyClipboard::data(mode, formats);
const auto &clipboardData = mode == ClipboardMode::Clipboard ? m_clipboardData : m_selectionData;
auto data = clipboardData.data;
if ( !data.contains(mimeOwner) )
data[mimeWindowTitle] = clipboardData.owner.toUtf8();
return data;
}
void X11PlatformClipboard::setData(ClipboardMode mode, const QVariantMap &dataMap)
{
if ( X11Info::isPlatformX11() ) {
// WORKAROUND: Avoid getting X11 warning "QXcbClipboard: SelectionRequest too old".
QCoreApplication::processEvents();
DummyClipboard::setData(mode, dataMap);
} else {
const auto data = createMimeData(dataMap);
const auto qmode = modeToQClipboardMode(mode);
WaylandClipboard::instance()->setMimeData(data, qmode);
// This makes pasting the clipboard work in own widgets.
const auto data2 = createMimeData(dataMap);
QGuiApplication::clipboard()->setMimeData(data2, qmode);
}
}
void X11PlatformClipboard::setRawData(ClipboardMode mode, QMimeData *mimeData)
{
if ( X11Info::isPlatformX11() ) {
DummyClipboard::setRawData(mode, mimeData);
} else {
const auto qmode = modeToQClipboardMode(mode);
WaylandClipboard::instance()->setMimeData(mimeData, qmode);
}
}
const QMimeData *X11PlatformClipboard::rawMimeData(ClipboardMode mode) const
{
if ( X11Info::isPlatformX11() )
return DummyClipboard::rawMimeData(mode);
return WaylandClipboard::instance()->mimeData( modeToQClipboardMode(mode) );
}
void X11PlatformClipboard::onChanged(int mode)
{
auto &clipboardData = mode == QClipboard::Clipboard ? m_clipboardData : m_selectionData;
if (!clipboardData.enabled)
return;
++clipboardData.sequenceNumber;
// Store the current window title right after the clipboard/selection changes.
// This makes sure that the title points to the correct clipboard/selection
// owner most of the times.
clipboardData.newOwner = m_clipboardOwner;
if (mode == QClipboard::Selection) {
// Omit checking selection too fast.
if ( mode == QClipboard::Selection && m_timerCheckAgain.isActive() ) {
COPYQ_LOG("Postponing fast selection change");
return;
}
if ( isSelectionIncomplete() ) {
COPYQ_LOG("Selection is incomplete");
if ( !m_timerCheckAgain.isActive()
|| minCheckAgainIntervalMs < m_timerCheckAgain.remainingTime() )
{
m_timerCheckAgain.start(minCheckAgainIntervalMs);
}
return;
}
}
if (m_clipboardData.cloningData || m_selectionData.cloningData)
return;
updateClipboardData(&clipboardData);
checkAgainLater(true, 0);
}
void X11PlatformClipboard::check()
{
if (m_clipboardData.cloningData || m_selectionData.cloningData) {
m_timerCheckAgain.setInterval(minCheckAgainIntervalMs);
m_timerCheckAgain.start();
return;
}
m_timerCheckAgain.stop();
updateClipboardData(&m_clipboardData);
updateClipboardData(&m_selectionData);
if ( m_timerCheckAgain.isActive() )
return;
const bool changed = m_clipboardData.timerEmitChange.isActive()
|| m_selectionData.timerEmitChange.isActive();
// Check clipboard and selection again if some signals where
// not delivered or older data was received after new one.
const int interval = m_timerCheckAgain.interval() * 2 + minCheckAgainIntervalMs;
checkAgainLater(changed, interval);
}
void X11PlatformClipboard::updateClipboardData(X11PlatformClipboard::ClipboardData *clipboardData)
{
if (!clipboardData->enabled)
return;
if ( isSelectionIncomplete() ) {
m_timerCheckAgain.start(minCheckAgainIntervalMs);
return;
}
const QPointer<const QMimeData> data( mimeData(clipboardData->mode) );
// Retry to retrieve clipboard data few times.
if (!data) {
if ( !X11Info::isPlatformX11() )
return;
if ( rawMimeData(clipboardData->mode) )
return;
if (clipboardData->retry < maxRetryCount) {
++clipboardData->retry;
m_timerCheckAgain.start(clipboardData->retry * maxCheckAgainIntervalMs);
}
log( QString("Failed to retrieve %1 data (try %2/%3)")
.arg(clipboardData->mode == ClipboardMode::Clipboard ? "clipboard" : "selection")
.arg(clipboardData->retry)
.arg(maxRetryCount), LogWarning );
return;
}
clipboardData->retry = 0;
const QByteArray newDataTimestampData = data->data(QStringLiteral("TIMESTAMP"));
quint32 newDataTimestamp = 0;
if ( !newDataTimestampData.isEmpty() ) {
QDataStream stream(newDataTimestampData);
stream.setByteOrder(QDataStream::LittleEndian);
stream >> newDataTimestamp;
if (stream.status() != QDataStream::Ok)
newDataTimestamp = 0;
}
// In case there is a valid timestamp, omit update if the timestamp and
// text did not change.
if ( newDataTimestamp != 0 && clipboardData->newDataTimestamp == newDataTimestamp ) {
const QVariantMap newData = cloneData(*data, {mimeText});
if (!data || newData.value(mimeText) == clipboardData->newData.value(mimeText))
return;
}
clipboardData->timerEmitChange.stop();
clipboardData->cloningData = true;
const bool isDataSecret = isHidden(*data);
const auto sequenceNumberOrig = clipboardData->sequenceNumber;
clipboardData->newData = cloneData(*data, clipboardData->formats, &clipboardData->sequenceNumber);
if (isDataSecret)
clipboardData->newData[mimeSecret] = QByteArrayLiteral("1");
clipboardData->cloningData = false;
if (sequenceNumberOrig != clipboardData->sequenceNumber) {
m_timerCheckAgain.setInterval(0);
m_timerCheckAgain.start();
return;
}
// Update only if the data changed.
if ( clipboardData->data == clipboardData->newData )
return;
clipboardData->newDataTimestamp = newDataTimestamp;
clipboardData->timerEmitChange.start();
}
void X11PlatformClipboard::useNewClipboardData(X11PlatformClipboard::ClipboardData *clipboardData)
{
clipboardData->data = clipboardData->newData;
clipboardData->owner = clipboardData->newOwner;
clipboardData->timerEmitChange.stop();
if (clipboardData->ignoreNext)
clipboardData->ignoreNext = false;
else
emit changed(clipboardData->mode);
}
void X11PlatformClipboard::checkAgainLater(bool clipboardChanged, int interval)
{
m_timerCheckAgain.setInterval(interval);
if (interval < maxCheckAgainIntervalMs)
m_timerCheckAgain.start();
else if (clipboardChanged)
m_timerCheckAgain.start(maxCheckAgainIntervalMs);
else
m_timerCheckAgain.setInterval(0);
COPYQ_LOG( QString("Clipboard %1, selection %2.%3")
.arg(
QString::fromLatin1(m_clipboardData.timerEmitChange.isActive() ? "*CHANGED*" : "unchanged"),
QString::fromLatin1(m_selectionData.timerEmitChange.isActive() ? "*CHANGED*" : "unchanged"),
m_timerCheckAgain.isActive()
? QString(" Test again in %1ms.").arg(m_timerCheckAgain.interval())
: QString()
) );
}
| 11,399
|
C++
|
.cpp
| 281
| 34.064057
| 111
| 0.691612
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,190
|
x11info.cpp
|
hluk_CopyQ/src/platform/x11/x11info.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "x11info.h"
#include <QGuiApplication>
#ifdef COPYQ_WITH_X11
# if QT_VERSION < QT_VERSION_CHECK(6,0,0)
# include <QX11Info>
# else
# include <QtGui/private/qtx11extras_p.h>
# endif
# include <X11/Xlib.h>
#else
struct _XDisplay {};
#endif
bool X11Info::isPlatformX11()
{
return QGuiApplication::platformName() == QStringLiteral("xcb");
}
Display *X11Info::display()
{
#ifdef COPYQ_WITH_X11
return QX11Info::display();
#else
return nullptr;
#endif
}
| 539
|
C++
|
.cpp
| 25
| 19.88
| 68
| 0.715128
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,191
|
waylandclipboard.cpp
|
hluk_CopyQ/src/platform/x11/systemclipboard/waylandclipboard.cpp
|
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-FileCopyrightText: 2021 Méven Car <meven.car@enioka.com>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "waylandclipboard.h"
#include <QBuffer>
#include <QDebug>
#include <QElapsedTimer>
#include <QFile>
#include <QGuiApplication>
#include <QImageReader>
#include <QImageWriter>
#include <QMimeData>
#include <QThread>
#include <QtWaylandClient/QWaylandClientExtension>
#include <qpa/qplatformnativeinterface.h>
#include <qtwaylandclientversion.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include "qwayland-wlr-data-control-unstable-v1.h"
static inline QString applicationQtXImageLiteral()
{
return QStringLiteral("application/x-qt-image");
}
// copied from https://code.woboq.org/qt5/qtbase/src/gui/kernel/qinternalmimedata.cpp.html
static QString utf8Text()
{
return QStringLiteral("text/plain;charset=utf-8");
}
static QStringList imageMimeFormats(const QList<QByteArray> &imageFormats)
{
QStringList formats;
formats.reserve(imageFormats.size());
for (const auto &format : imageFormats)
formats.append(QLatin1String("image/") + QLatin1String(format.toLower()));
// put png at the front because it is best
int pngIndex = formats.indexOf(QLatin1String("image/png"));
if (pngIndex != -1 && pngIndex != 0)
formats.move(pngIndex, 0);
return formats;
}
static inline QStringList imageReadMimeFormats()
{
return imageMimeFormats(QImageReader::supportedImageFormats());
}
static inline QStringList imageWriteMimeFormats()
{
return imageMimeFormats(QImageWriter::supportedImageFormats());
}
// end copied
namespace {
class SendThread : public QThread {
public:
SendThread(int fd, const QByteArray &data)
: m_data(data)
, m_fd(fd)
{}
protected:
void run() override {
QFile c;
if (c.open(m_fd, QFile::WriteOnly, QFile::AutoCloseHandle)) {
// Create a sigpipe handler that does nothing, or clients may be forced to terminate
// if the pipe is closed in the other end.
struct sigaction action, oldAction;
action.sa_handler = SIG_IGN;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
sigaction(SIGPIPE, &action, &oldAction);
// Unset O_NONBLOCK
fcntl(m_fd, F_SETFL, 0);
const qint64 written = c.write(m_data);
sigaction(SIGPIPE, &oldAction, nullptr);
c.close();
if (written != m_data.size()) {
qWarning() << "Failed to send all clipobard data; sent"
<< written << "bytes out of" << m_data.size();
}
}
}
private:
QByteArray m_data;
int m_fd;
};
class ReceiveThread : public QThread {
public:
ReceiveThread(int fd)
: m_fd(fd)
{}
QByteArray data() const { return m_data; }
protected:
void run() override {
QFile readPipe;
if (readPipe.open(m_fd, QIODevice::ReadOnly, QFile::AutoCloseHandle)) {
readData();
close(m_fd);
}
}
private:
void readData() {
pollfd pfds[1];
pfds[0].fd = m_fd;
pfds[0].events = POLLIN;
while (true) {
const int ready = poll(pfds, 1, 1000);
if (ready < 0) {
if (errno != EINTR) {
qWarning("DataControlOffer: poll() failed: %s", strerror(errno));
return;
}
} else if (ready == 0) {
qWarning("DataControlOffer: timeout reading from pipe");
return;
} else {
char buf[4096];
int n = read(m_fd, buf, sizeof buf);
if (n < 0) {
qWarning("DataControlOffer: read() failed: %s", strerror(errno));
return;
} else if (n == 0) {
return;
} else if (n > 0) {
m_data.append(buf, n);
}
}
}
}
QByteArray m_data;
int m_fd;
};
} // namespace
class DataControlDeviceManager : public QWaylandClientExtensionTemplate<DataControlDeviceManager>
, public QtWayland::zwlr_data_control_manager_v1
{
Q_OBJECT
public:
DataControlDeviceManager()
: QWaylandClientExtensionTemplate<DataControlDeviceManager>(2)
{
}
void instantiate()
{
#if QTWAYLANDCLIENT_VERSION >= QT_VERSION_CHECK(6, 2, 0)
initialize();
#else
// QWaylandClientExtensionTemplate invokes this with a QueuedConnection but we want shortcuts
// to be have access to data_control immediately.
QMetaObject::invokeMethod(this, "addRegistryListener");
#endif
}
~DataControlDeviceManager()
{
if (isInitialized()) {
destroy();
}
}
};
class DataControlOffer : public QMimeData, public QtWayland::zwlr_data_control_offer_v1
{
Q_OBJECT
public:
DataControlOffer(struct ::zwlr_data_control_offer_v1 *id)
: QtWayland::zwlr_data_control_offer_v1(id)
{
}
~DataControlOffer()
{
if ( isInitialized() )
destroy();
}
QStringList formats() const override
{
return m_receivedFormats;
}
bool containsImageData() const
{
if (m_receivedFormats.contains(applicationQtXImageLiteral())) {
return true;
}
const auto formats = imageReadMimeFormats();
for (const auto &receivedFormat : m_receivedFormats) {
if (formats.contains(receivedFormat)) {
return true;
}
}
return false;
}
bool hasFormat(const QString &mimeType) const override
{
if (mimeType == QStringLiteral("text/plain") && m_receivedFormats.contains(utf8Text())) {
return true;
}
if (m_receivedFormats.contains(mimeType)) {
return true;
}
// If we have image data
if (containsImageData()) {
// is the requested output mimeType supported ?
const QStringList imageFormats = imageWriteMimeFormats();
for (const QString &imageFormat : imageFormats) {
if (imageFormat == mimeType) {
return true;
}
}
if (mimeType == applicationQtXImageLiteral()) {
return true;
}
}
return false;
}
protected:
void zwlr_data_control_offer_v1_offer(const QString &mime_type) override
{
if (!m_receivedFormats.contains(mime_type)) {
m_receivedFormats << mime_type;
}
}
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QVariant retrieveData(const QString &mimeType, QMetaType type) const override;
#else
QVariant retrieveData(const QString &mimeType, QVariant::Type type) const override;
#endif
private:
QStringList m_receivedFormats;
};
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QVariant DataControlOffer::retrieveData(const QString &mimeType, QMetaType type) const
#else
QVariant DataControlOffer::retrieveData(const QString &mimeType, QVariant::Type type) const
#endif
{
Q_UNUSED(type);
QString mime;
if (!m_receivedFormats.contains(mimeType)) {
if (mimeType == QStringLiteral("text/plain") && m_receivedFormats.contains(utf8Text())) {
mime = utf8Text();
} else if (mimeType == applicationQtXImageLiteral()) {
const auto writeFormats = imageWriteMimeFormats();
for (const auto &receivedFormat : m_receivedFormats) {
if (writeFormats.contains(receivedFormat)) {
mime = receivedFormat;
break;
}
}
if (mime.isEmpty()) {
// default exchange format
mime = QStringLiteral("image/png");
}
}
if (mime.isEmpty()) {
return QVariant();
}
} else {
mime = mimeType;
}
int pipeFds[2];
if (pipe(pipeFds) != 0) {
return QVariant();
}
auto t = const_cast<DataControlOffer *>(this);
t->receive(mime, pipeFds[1]);
close(pipeFds[1]);
/*
* Ideally we need to introduce a non-blocking QMimeData object
* Or a non-blocking constructor to QMimeData with the mimetypes that are relevant
*
* However this isn't actually any worse than X.
*/
QPlatformNativeInterface *native = qGuiApp->platformNativeInterface();
auto display = static_cast<struct ::wl_display *>(native->nativeResourceForIntegration("wl_display"));
wl_display_flush(display);
ReceiveThread thread(pipeFds[0]);
QEventLoop loop;
connect(&thread, &QThread::finished, &loop, &QEventLoop::quit);
thread.start();
if (thread.isRunning())
loop.exec();
const auto data = thread.data();
if (!data.isEmpty() && mimeType == applicationQtXImageLiteral()) {
QImage img = QImage::fromData(data, mime.mid(mime.indexOf(QLatin1Char('/')) + 1).toLatin1().toUpper().data());
if (!img.isNull()) {
return img;
}
}
return data;
}
class DataControlSource : public QObject, public QtWayland::zwlr_data_control_source_v1
{
Q_OBJECT
public:
DataControlSource(struct ::zwlr_data_control_source_v1 *id, QMimeData *mimeData);
~DataControlSource()
{
if (m_mimeData) {
m_mimeData->deleteLater();
m_mimeData = nullptr;
}
if ( isInitialized() )
destroy();
}
QMimeData *mimeData()
{
return m_mimeData;
}
bool isCancelled() const { return m_cancelled; }
Q_SIGNALS:
void cancelled();
protected:
void zwlr_data_control_source_v1_send(const QString &mime_type, int32_t fd) override;
void zwlr_data_control_source_v1_cancelled() override;
private:
QMimeData *m_mimeData = nullptr;
bool m_cancelled = false;
};
DataControlSource::DataControlSource(struct ::zwlr_data_control_source_v1 *id, QMimeData *mimeData)
: QtWayland::zwlr_data_control_source_v1(id)
, m_mimeData(mimeData)
{
const auto formats = mimeData->formats();
for (const QString &format : formats) {
offer(format);
}
if (mimeData->hasText()) {
// ensure GTK applications get this mimetype to avoid them discarding the offer
offer(QStringLiteral("text/plain;charset=utf-8"));
}
if (mimeData->hasImage()) {
const QStringList imageFormats = imageWriteMimeFormats();
for (const QString &imageFormat : imageFormats) {
if (!formats.contains(imageFormat)) {
offer(imageFormat);
}
}
}
}
void DataControlSource::zwlr_data_control_source_v1_send(const QString &mime_type, int32_t fd)
{
QString send_mime_type = mime_type;
if( send_mime_type == QStringLiteral("text/plain;charset=utf-8")
&& !m_mimeData->hasFormat(QStringLiteral("text/plain;charset=utf-8")) )
{
// if we get a request on the fallback mime, send the data from the original mime type
send_mime_type = QStringLiteral("text/plain");
}
QByteArray ba;
if (m_mimeData->hasImage()) {
// adapted from QInternalMimeData::renderDataHelper
if (mime_type == applicationQtXImageLiteral()) {
QImage image = qvariant_cast<QImage>(m_mimeData->imageData());
QBuffer buf(&ba);
buf.open(QBuffer::WriteOnly);
// would there not be PNG ??
image.save(&buf, "PNG");
} else if (mime_type.startsWith(QLatin1String("image/"))) {
QImage image = qvariant_cast<QImage>(m_mimeData->imageData());
QBuffer buf(&ba);
buf.open(QBuffer::WriteOnly);
image.save(&buf, mime_type.mid(mime_type.indexOf(QLatin1Char('/')) + 1).toLatin1().toUpper().data());
}
// end adapted
} else {
ba = m_mimeData->data(send_mime_type);
}
auto thread = new SendThread(fd, m_mimeData->data(send_mime_type));
connect(thread, &QThread::finished, thread, &QObject::deleteLater);
thread->start();
}
void DataControlSource::zwlr_data_control_source_v1_cancelled()
{
m_cancelled = true;
Q_EMIT cancelled();
}
class DataControlDevice : public QObject, public QtWayland::zwlr_data_control_device_v1
{
Q_OBJECT
public:
DataControlDevice(struct ::zwlr_data_control_device_v1 *id)
: QtWayland::zwlr_data_control_device_v1(id)
{
}
~DataControlDevice()
{
if ( isInitialized() )
destroy();
}
void setSelection(std::unique_ptr<DataControlSource> selection);
QMimeData *receivedSelection()
{
return m_receivedSelection.get();
}
QMimeData *selection()
{
return m_selection ? m_selection->mimeData() : nullptr;
}
void setPrimarySelection(std::unique_ptr<DataControlSource> selection);
QMimeData *receivedPrimarySelection()
{
return m_receivedPrimarySelection.get();
}
QMimeData *primarySelection()
{
return m_primarySelection ? m_primarySelection->mimeData() : nullptr;
}
Q_SIGNALS:
void receivedSelectionChanged();
void selectionChanged();
void receivedPrimarySelectionChanged();
void primarySelectionChanged();
protected:
void zwlr_data_control_device_v1_data_offer(struct ::zwlr_data_control_offer_v1 *id) override
{
// this will become memory managed when we retrieve the selection event
// a compositor calling data_offer without doing that would be a bug
new DataControlOffer(id);
}
void zwlr_data_control_device_v1_selection(struct ::zwlr_data_control_offer_v1 *id) override
{
if (!id) {
m_receivedSelection.reset();
} else {
#if QT_VERSION >= QT_VERSION_CHECK(5,12,5)
auto derivated = QtWayland::zwlr_data_control_offer_v1::fromObject(id);
#else
auto derivated = static_cast<QtWayland::zwlr_data_control_offer_v1 *>(zwlr_data_control_offer_v1_get_user_data(id));
#endif
auto offer = dynamic_cast<DataControlOffer *>(derivated); // dynamic because of the dual inheritance
m_receivedSelection.reset(offer);
}
Q_EMIT receivedSelectionChanged();
}
void zwlr_data_control_device_v1_primary_selection(struct ::zwlr_data_control_offer_v1 *id) override
{
if (!id) {
m_receivedPrimarySelection.reset();
} else {
#if QT_VERSION >= QT_VERSION_CHECK(5,12,5)
auto derivated = QtWayland::zwlr_data_control_offer_v1::fromObject(id);
#else
auto derivated = static_cast<QtWayland::zwlr_data_control_offer_v1 *>(zwlr_data_control_offer_v1_get_user_data(id));
#endif
auto offer = dynamic_cast<DataControlOffer *>(derivated); // dynamic because of the dual inheritance
m_receivedPrimarySelection.reset(offer);
}
Q_EMIT receivedPrimarySelectionChanged();
}
private:
std::unique_ptr<DataControlSource> m_selection; // selection set locally
std::unique_ptr<DataControlOffer> m_receivedSelection; // latest selection set from externally to here
std::unique_ptr<DataControlSource> m_primarySelection; // selection set locally
std::unique_ptr<DataControlOffer> m_receivedPrimarySelection; // latest selection set from externally to here
};
void DataControlDevice::setSelection(std::unique_ptr<DataControlSource> selection)
{
m_selection = std::move(selection);
connect(m_selection.get(), &DataControlSource::cancelled, this, [this]() {
m_selection.reset();
Q_EMIT selectionChanged();
});
set_selection(m_selection->object());
Q_EMIT selectionChanged();
}
void DataControlDevice::setPrimarySelection(std::unique_ptr<DataControlSource> selection)
{
m_primarySelection = std::move(selection);
connect(m_primarySelection.get(), &DataControlSource::cancelled, this, [this]() {
m_primarySelection.reset();
Q_EMIT primarySelectionChanged();
});
if (zwlr_data_control_device_v1_get_version(object()) >= ZWLR_DATA_CONTROL_DEVICE_V1_SET_PRIMARY_SELECTION_SINCE_VERSION) {
set_primary_selection(m_primarySelection->object());
Q_EMIT primarySelectionChanged();
}
}
WaylandClipboard::WaylandClipboard(QObject *parent)
: QObject(parent)
, m_manager(new DataControlDeviceManager)
{
connect(m_manager.get(), &DataControlDeviceManager::activeChanged, this, [this]() {
if (m_manager->isActive()) {
QPlatformNativeInterface *native = qApp->platformNativeInterface();
if (!native) {
return;
}
auto seat = static_cast<struct ::wl_seat *>(native->nativeResourceForIntegration("wl_seat"));
if (!seat) {
return;
}
m_device.reset(new DataControlDevice(m_manager->get_data_device(seat)));
connect(m_device.get(), &DataControlDevice::receivedSelectionChanged, this, [this]() {
// When our source is still valid, so the offer is for setting it or we emit changed when it is cancelled
if (!m_device->selection()) {
Q_EMIT changed(QClipboard::Clipboard);
}
});
connect(m_device.get(), &DataControlDevice::selectionChanged, this, [this]() {
Q_EMIT changed(QClipboard::Clipboard);
});
connect(m_device.get(), &DataControlDevice::receivedPrimarySelectionChanged, this, [this]() {
// When our source is still valid, so the offer is for setting it or we emit changed when it is cancelled
if (!m_device->primarySelection()) {
Q_EMIT changed(QClipboard::Selection);
}
});
connect(m_device.get(), &DataControlDevice::primarySelectionChanged, this, [this]() {
Q_EMIT changed(QClipboard::Selection);
});
} else {
m_device.reset();
}
});
m_manager->instantiate();
}
WaylandClipboard *WaylandClipboard::createInstance()
{
qInfo() << "Using Wayland clipboard access";
auto clipboard = new WaylandClipboard(qApp);
QElapsedTimer timer;
timer.start();
while ( !clipboard->isActive() && timer.elapsed() < 5000 ) {
QCoreApplication::processEvents();
}
if ( timer.elapsed() > 100 ) {
qWarning() << "Activating Wayland clipboard took" << timer.elapsed() << "ms";
}
if ( !clipboard->isActive() ) {
qCritical() << "Failed to activate Wayland clipboard";
}
return clipboard;
}
void WaylandClipboard::setMimeData(QMimeData *mime, QClipboard::Mode mode)
{
if (!m_device) {
return;
}
std::unique_ptr<DataControlSource> source(new DataControlSource(m_manager->create_data_source(), mime));
if (mode == QClipboard::Clipboard) {
m_device->setSelection(std::move(source));
} else if (mode == QClipboard::Selection) {
m_device->setPrimarySelection(std::move(source));
}
}
void WaylandClipboard::clear(QClipboard::Mode mode)
{
if (!m_device) {
return;
}
if (mode == QClipboard::Clipboard) {
m_device->set_selection(nullptr);
} else if (mode == QClipboard::Selection) {
if (zwlr_data_control_device_v1_get_version(m_device->object()) >= ZWLR_DATA_CONTROL_DEVICE_V1_SET_PRIMARY_SELECTION_SINCE_VERSION) {
m_device->set_primary_selection(nullptr);
}
}
}
const QMimeData *WaylandClipboard::mimeData(QClipboard::Mode mode) const
{
if (!m_device) {
return nullptr;
}
// return our locally set selection if it's not cancelled to avoid copying data to ourselves
if (mode == QClipboard::Clipboard) {
if (m_device->selection()) {
return m_device->selection();
}
return m_device->receivedSelection();
} else if (mode == QClipboard::Selection) {
if (m_device->primarySelection()) {
return m_device->primarySelection();
}
return m_device->receivedPrimarySelection();
}
return nullptr;
}
bool WaylandClipboard::isSelectionSupported() const
{
return m_device && zwlr_data_control_device_v1_get_version(m_device->object())
>= ZWLR_DATA_CONTROL_DEVICE_V1_SET_PRIMARY_SELECTION_SINCE_VERSION;
}
WaylandClipboard *WaylandClipboard::instance()
{
static WaylandClipboard *clipboard = createInstance();
return clipboard;
}
WaylandClipboard::~WaylandClipboard() = default;
#include "waylandclipboard.moc"
| 20,810
|
C++
|
.cpp
| 589
| 28.13073
| 141
| 0.636246
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,192
|
winplatform.cpp
|
hluk_CopyQ/src/platform/win/winplatform.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "app/applicationexceptionhandler.h"
#include "common/log.h"
#include "common/settings.h"
#include "platform/dummy/dummyclipboard.h"
#include "winplatform.h"
#include "winplatformclipboard.h"
#include "winplatformwindow.h"
#include <QApplication>
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QKeyEvent>
#include <QMetaObject>
#include <QSettings>
#include <QStringList>
#include <QWidget>
#include <qt_windows.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
namespace {
void setBinaryFor(int fd)
{
_setmode(fd, _O_BINARY);
}
QString portableConfigFolder()
{
const QString appDir = QCoreApplication::applicationDirPath();
if ( !QFileInfo(appDir).isWritable() )
return {};
const QString uninstPath = appDir + QLatin1String("/unins000.exe");
if ( QFile::exists(uninstPath) )
return {};
const QString path = appDir + QLatin1String("/config");
QDir dir(path);
if ( !dir.mkpath(".") || !dir.isReadable() )
return {};
const QString fullPath = dir.absolutePath();
if ( !QFileInfo(fullPath).isWritable() )
return {};
return fullPath;
}
void uninstallControlHandler();
BOOL appQuit()
{
uninstallControlHandler();
const bool invoked = QMetaObject::invokeMethod(
QCoreApplication::instance(), "quit", Qt::BlockingQueuedConnection);
if (!invoked) {
log("Failed to request application exit", LogError);
return FALSE;
}
ExitProcess(EXIT_SUCCESS);
return TRUE;
}
BOOL ctrlHandler(DWORD fdwCtrlType)
{
switch (fdwCtrlType) {
case CTRL_C_EVENT:
log("Terminating application on signal.");
return appQuit();
case CTRL_CLOSE_EVENT:
log("Terminating application on close event.");
return appQuit();
case CTRL_BREAK_EVENT:
log("Terminating application on break event.");
return appQuit();
case CTRL_LOGOFF_EVENT:
log("Terminating application on log off.");
return appQuit();
case CTRL_SHUTDOWN_EVENT:
log("Terminating application on shut down.");
return appQuit();
default:
return FALSE;
}
}
void installControlHandler()
{
if ( !SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(ctrlHandler), TRUE) )
log("Failed to set Windows control handler.", LogError);
}
void uninstallControlHandler()
{
SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(ctrlHandler), FALSE);
}
template <typename Application>
Application *createApplication(int &argc, char **argv)
{
Application *app = new ApplicationExceptionHandler<Application>(argc, argv);
installControlHandler();
setBinaryFor(0);
setBinaryFor(1);
// Don't use Windows registry.
QSettings::setDefaultFormat(QSettings::IniFormat);
// Use config and log file in portable app folder.
const QString portableFolder = portableConfigFolder();
if ( !portableFolder.isEmpty() ) {
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, portableFolder);
qputenv("COPYQ_LOG_FILE", portableFolder.toUtf8() + "/copyq.log");
app->setProperty("CopyQ_item_data_path", portableFolder + QLatin1String("/items"));
}
return app;
}
QApplication *createGuiApplication(int &argc, char **argv)
{
auto app = createApplication<QApplication>(argc, argv);
// WORKAROUND: Create a window so that application can receive
// WM_QUERYENDSESSION (from installer) and similar events.
auto w = new QWidget();
auto winId = w->winId();
Q_UNUSED(winId)
return app;
}
QString windowClass(HWND window)
{
WCHAR buf[32];
GetClassNameW(window, buf, 32);
return QString::fromUtf16(reinterpret_cast<ushort *>(buf));
}
HWND getLastVisibleActivePopUpOfWindow(HWND window)
{
HWND currentWindow = window;
for (int i = 0; i < 50; ++i) {
HWND lastPopUp = GetLastActivePopup(currentWindow);
if (IsWindowVisible(lastPopUp))
return lastPopUp;
if (lastPopUp == currentWindow)
return nullptr;
currentWindow = lastPopUp;
}
return nullptr;
}
bool isAltTabWindow(HWND window)
{
if (!window || window == GetShellWindow())
return false;
HWND root = GetAncestor(window, GA_ROOTOWNER);
if (getLastVisibleActivePopUpOfWindow(root) != window)
return false;
const QString cls = windowClass(window);
COPYQ_LOG_VERBOSE( QString("cls: \"%1\"").arg(cls) );
return !cls.isEmpty()
&& cls != "Shell_TrayWnd"
&& cls != "Shell_SecondaryTrayWnd"
&& cls != "Shell_CharmWindow"
&& cls != "DV2ControlHost"
&& cls != "MsgrIMEWindowClass"
&& cls != "SysShadow"
&& cls != "Button"
&& !cls.startsWith("WMP9MediaBarFlyout");
}
HWND currentWindow;
BOOL CALLBACK getCurrentWindowProc(HWND window, LPARAM)
{
if (!isAltTabWindow(window))
return TRUE;
currentWindow = window;
return FALSE;
}
} // namespace
PlatformNativeInterface *platformNativeInterface()
{
static WinPlatform platform;
return &platform;
}
PlatformWindowPtr WinPlatform::getWindow(WId winId)
{
HWND window = reinterpret_cast<HWND>(winId);
return PlatformWindowPtr( window ? new WinPlatformWindow(window) : nullptr );
}
PlatformWindowPtr WinPlatform::getCurrentWindow()
{
currentWindow = GetForegroundWindow();
if (!isAltTabWindow(currentWindow))
EnumWindows(getCurrentWindowProc, 0);
return PlatformWindowPtr( currentWindow ? new WinPlatformWindow(currentWindow) : nullptr );
}
QCoreApplication *WinPlatform::createConsoleApplication(int &argc, char **argv)
{
return createApplication<QCoreApplication>(argc, argv);
}
QApplication *WinPlatform::createServerApplication(int &argc, char **argv)
{
return createGuiApplication(argc, argv);
}
QGuiApplication *WinPlatform::createMonitorApplication(int &argc, char **argv)
{
return createApplication<QGuiApplication>(argc, argv);
}
QGuiApplication *WinPlatform::createClipboardProviderApplication(int &argc, char **argv)
{
return createApplication<QGuiApplication>(argc, argv);
}
QCoreApplication *WinPlatform::createClientApplication(int &argc, char **argv)
{
return createApplication<QCoreApplication>(argc, argv);
}
QGuiApplication *WinPlatform::createTestApplication(int &argc, char **argv)
{
return createApplication<QGuiApplication>(argc, argv);
}
PlatformClipboardPtr WinPlatform::clipboard()
{
return PlatformClipboardPtr(new WinPlatformClipboard());
}
QStringList WinPlatform::getCommandLineArguments(int, char**)
{
int argumentCount;
LPWSTR *arguments = CommandLineToArgvW(GetCommandLineW(), &argumentCount);
QStringList result;
for (int i = 1; i < argumentCount; ++i)
result.append( QString::fromUtf16(reinterpret_cast<ushort*>(arguments[i])) );
return result;
}
bool WinPlatform::findPluginDir(QDir *pluginsDir)
{
pluginsDir->setPath( qApp->applicationDirPath() );
return pluginsDir->cd("plugins");
}
QString WinPlatform::defaultEditorCommand()
{
return "notepad %1";
}
QString WinPlatform::translationPrefix()
{
return QCoreApplication::applicationDirPath() + "/translations";
}
QString WinPlatform::themePrefix()
{
return QApplication::applicationDirPath() + "/themes";
}
| 7,426
|
C++
|
.cpp
| 233
| 27.566524
| 95
| 0.713504
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
18,193
|
winplatformwindow.cpp
|
hluk_CopyQ/src/platform/win/winplatformwindow.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "platform/platformcommon.h"
#include "winplatformwindow.h"
#include "common/appconfig.h"
#include "common/log.h"
#include "common/sleeptimer.h"
#include <QApplication>
#include <QElapsedTimer>
#include <QString>
#include <QVector>
namespace {
QString windowTitle(HWND window)
{
WCHAR buf[1024];
GetWindowTextW(window, buf, 1024);
return QString::fromUtf16(reinterpret_cast<ushort *>(buf));
}
INPUT createInput(WORD key, DWORD flags = 0)
{
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.wVk = key;
input.ki.wScan = 0;
input.ki.dwFlags = KEYEVENTF_UNICODE | flags;
input.ki.time = 0;
input.ki.dwExtraInfo = GetMessageExtraInfo();
return input;
}
QString windowLogText(QString text, HWND window)
{
const QString windowInfo =
QString("%1").arg(reinterpret_cast<quintptr>(window))
+ " \"" + windowTitle(window) + "\"";
text.prepend("Window " + windowInfo + ": ");
const DWORD lastError = GetLastError();
if (lastError != 0)
text.append( QString(" (last error is %1)").arg(GetLastError()) );
return text;
}
void logWindow(const char *text, HWND window)
{
COPYQ_LOG( windowLogText(text, window) );
}
bool raiseWindowHelper(HWND window)
{
if (!SetForegroundWindow(window)) {
logWindow("Failed to raise: SetForegroundWindow() == false", window);
return false;
}
SetWindowPos(window, HWND_TOP, 0, 0, 0, 0,
SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
logWindow("Raised", window);
return true;
}
bool raiseWindow(HWND window)
{
if (!IsWindowVisible(window)) {
logWindow("Failed to raise: IsWindowVisible() == false", window);
return false;
}
// WORKAROUND: Set foreground window if even this process is not in foreground.
const auto thisThreadId = GetCurrentThreadId();
const auto foregroundThreadId = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
if (thisThreadId != foregroundThreadId) {
if ( AttachThreadInput(thisThreadId, foregroundThreadId, true) ) {
logWindow("Attached foreground thread", window);
const bool result = raiseWindowHelper(window);
AttachThreadInput(thisThreadId, foregroundThreadId, false);
return result;
}
logWindow("Failed to attach foreground thread", window);
}
return raiseWindowHelper(window);
}
bool isKeyPressed(int key)
{
return GetKeyState(key) & 0x8000;
}
bool isModifierPressed()
{
return isKeyPressed(VK_LCONTROL)
|| isKeyPressed(VK_RCONTROL)
|| isKeyPressed(VK_LSHIFT)
|| isKeyPressed(VK_RSHIFT)
|| isKeyPressed(VK_LMENU)
|| isKeyPressed(VK_RMENU)
|| isKeyPressed(VK_MENU);
}
bool waitForModifiersReleased(const AppConfig &config)
{
const int maxWaitForModsReleaseMs = config.option<Config::window_wait_for_modifier_released_ms>();
if (maxWaitForModsReleaseMs >= 0) {
SleepTimer t(maxWaitForModsReleaseMs);
while (t.sleep()) {
if (!isModifierPressed())
return true;
}
}
return !isModifierPressed();
}
bool sendInputs(QVector<INPUT> input, HWND wnd)
{
const UINT numberOfAddedEvents = SendInput( input.size(), input.data(), sizeof(INPUT) );
if (numberOfAddedEvents == 0u) {
logWindow("Failed to paste", wnd);
return false;
}
logWindow("Paste successful", wnd);
return true;
}
} // namespace
WinPlatformWindow::WinPlatformWindow(HWND window)
: m_window(window)
{
}
QString WinPlatformWindow::getTitle()
{
return windowTitle(m_window);
}
void WinPlatformWindow::raise()
{
raiseWindow(m_window);
}
void WinPlatformWindow::pasteClipboard()
{
const AppConfig config;
if ( pasteWithCtrlV(*this, config) )
sendKeyPress(VK_LCONTROL, 'V', config);
else
sendKeyPress(VK_LSHIFT, VK_INSERT, config);
}
void WinPlatformWindow::copy()
{
const AppConfig config;
const DWORD clipboardSequenceNumber = GetClipboardSequenceNumber();
sendKeyPress(VK_LCONTROL, 'C', config);
// Wait for clipboard to change.
QElapsedTimer t;
t.start();
while ( clipboardSequenceNumber == GetClipboardSequenceNumber() && t.elapsed() < 2000 )
QApplication::processEvents(QEventLoop::AllEvents, 100);
}
void WinPlatformWindow::sendKeyPress(WORD modifier, WORD key, const AppConfig &config)
{
waitMs(config.option<Config::window_wait_before_raise_ms>());
if (!raiseWindow(m_window))
return;
waitMs(config.option<Config::window_wait_after_raised_ms>());
// Wait for user to release modifiers.
if (!waitForModifiersReleased(config))
return;
const int keyPressTimeMs = config.option<Config::window_key_press_time_ms>();
if (keyPressTimeMs <= 0) {
sendInputs({
createInput(modifier),
createInput(key),
createInput(key, KEYEVENTF_KEYUP),
createInput(modifier, KEYEVENTF_KEYUP)
}, m_window);
} else {
const bool sent = sendInputs({
createInput(modifier),
createInput(key)
}, m_window);
if (!sent)
return;
waitMs(keyPressTimeMs);
sendInputs({
createInput(key, KEYEVENTF_KEYUP),
createInput(modifier, KEYEVENTF_KEYUP)
}, m_window);
}
}
| 5,464
|
C++
|
.cpp
| 173
| 26.132948
| 102
| 0.674543
|
hluk/CopyQ
| 8,577
| 439
| 420
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.