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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
14,360
|
vmci_connecter.cpp
|
zeromq_libzmq/src/vmci_connecter.cpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#include "precompiled.hpp"
#include "vmci_connecter.hpp"
#if defined ZMQ_HAVE_VMCI
#include <new>
#include "io_thread.hpp"
#include "platform.hpp"
#include "random.hpp"
#include "err.hpp"
#include "ip.hpp"
#include "address.hpp"
#include "vmci_address.hpp"
#include "vmci.hpp"
#include "session_base.hpp"
zmq::vmci_connecter_t::vmci_connecter_t (class io_thread_t *io_thread_,
class session_base_t *session_,
const options_t &options_,
address_t *addr_,
bool delayed_start_) :
stream_connecter_base_t (
io_thread_, session_, options_, addr_, delayed_start_),
_connect_timer_started (false)
{
zmq_assert (_addr->protocol == protocol_name::vmci);
}
zmq::vmci_connecter_t::~vmci_connecter_t ()
{
zmq_assert (!_connect_timer_started);
}
void zmq::vmci_connecter_t::process_term (int linger_)
{
if (_connect_timer_started) {
cancel_timer (connect_timer_id);
_connect_timer_started = false;
}
stream_connecter_base_t::process_term (linger_);
}
void zmq::vmci_connecter_t::in_event ()
{
// We are not polling for incoming data, so we are actually called
// because of error here. However, we can get error on out event as well
// on some platforms, so we'll simply handle both events in the same way.
out_event ();
}
void zmq::vmci_connecter_t::out_event ()
{
if (_connect_timer_started) {
cancel_timer (connect_timer_id);
_connect_timer_started = false;
}
// TODO this is still very similar to (t)ipc_connecter_t, maybe the
// differences can be factored out
rm_handle ();
const fd_t fd = connect ();
if (fd == retired_fd
&& ((options.reconnect_stop & ZMQ_RECONNECT_STOP_CONN_REFUSED)
&& errno == ECONNREFUSED)) {
send_conn_failed (_session);
close ();
terminate ();
return;
}
// Handle the error condition by attempt to reconnect.
if (fd == retired_fd) {
close ();
add_reconnect_timer ();
return;
}
tune_vmci_buffer_size (this->get_ctx (), fd, options.vmci_buffer_size,
options.vmci_buffer_min_size,
options.vmci_buffer_max_size);
if (options.vmci_connect_timeout > 0) {
#if defined ZMQ_HAVE_WINDOWS
tune_vmci_connect_timeout (this->get_ctx (), fd,
options.vmci_connect_timeout);
#else
struct timeval timeout = {0, options.vmci_connect_timeout * 1000};
tune_vmci_connect_timeout (this->get_ctx (), fd, timeout);
#endif
}
create_engine (
fd, zmq::vmci_connecter_t::get_socket_name (fd, socket_end_local));
}
std::string
zmq::vmci_connecter_t::get_socket_name (zmq::fd_t fd_,
socket_end_t socket_end_) const
{
struct sockaddr_storage ss;
const zmq_socklen_t sl = get_socket_address (fd_, socket_end_, &ss);
if (sl == 0) {
return std::string ();
}
const vmci_address_t addr (reinterpret_cast<struct sockaddr *> (&ss), sl,
this->get_ctx ());
std::string address_string;
addr.to_string (address_string);
return address_string;
}
void zmq::vmci_connecter_t::timer_event (int id_)
{
if (id_ == connect_timer_id) {
_connect_timer_started = false;
rm_handle ();
close ();
add_reconnect_timer ();
} else
stream_connecter_base_t::timer_event (id_);
}
void zmq::vmci_connecter_t::start_connecting ()
{
// Open the connecting socket.
const int rc = open ();
// Connect may succeed in synchronous manner.
if (rc == 0) {
_handle = add_fd (_s);
out_event ();
}
// Connection establishment may be delayed. Poll for its completion.
else if (rc == -1 && errno == EINPROGRESS) {
_handle = add_fd (_s);
set_pollout (_handle);
_socket->event_connect_delayed (
make_unconnected_connect_endpoint_pair (_endpoint), zmq_errno ());
// add userspace connect timeout
add_connect_timer ();
}
// Handle any other error condition by eventual reconnect.
else {
if (_s != retired_fd)
close ();
add_reconnect_timer ();
}
}
void zmq::vmci_connecter_t::add_connect_timer ()
{
if (options.connect_timeout > 0) {
add_timer (options.connect_timeout, connect_timer_id);
_connect_timer_started = true;
}
}
int zmq::vmci_connecter_t::open ()
{
zmq_assert (_s == retired_fd);
// Resolve the address
if (_addr->resolved.vmci_addr != NULL) {
LIBZMQ_DELETE (_addr->resolved.vmci_addr);
}
_addr->resolved.vmci_addr =
new (std::nothrow) vmci_address_t (this->get_ctx ());
alloc_assert (_addr->resolved.vmci_addr);
_s = vmci_open_socket (_addr->address.c_str (), options,
_addr->resolved.vmci_addr);
if (_s == retired_fd) {
// TODO we should emit some event in this case!
LIBZMQ_DELETE (_addr->resolved.vmci_addr);
return -1;
}
zmq_assert (_addr->resolved.vmci_addr != NULL);
// Set the socket to non-blocking mode so that we get async connect().
unblock_socket (_s);
const vmci_address_t *const vmci_addr = _addr->resolved.vmci_addr;
int rc;
// Connect to the remote peer.
#if defined ZMQ_HAVE_VXWORKS
rc = ::connect (_s, (sockaddr *) vmci_addr->addr (), vmci_addr->addrlen ());
#else
rc = ::connect (_s, vmci_addr->addr (), vmci_addr->addrlen ());
#endif
// Connect was successful immediately.
if (rc == 0) {
return 0;
}
// Translate error codes indicating asynchronous connect has been
// launched to a uniform EINPROGRESS.
#ifdef ZMQ_HAVE_WINDOWS
const int last_error = WSAGetLastError ();
if (last_error == WSAEINPROGRESS || last_error == WSAEWOULDBLOCK)
errno = EINPROGRESS;
else
errno = wsa_error_to_errno (last_error);
#else
if (errno == EINTR)
errno = EINPROGRESS;
#endif
return -1;
}
zmq::fd_t zmq::vmci_connecter_t::connect ()
{
// Async connect has finished. Check whether an error occurred
int err = 0;
#if defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_VXWORKS
int len = sizeof err;
#else
socklen_t len = sizeof err;
#endif
const int rc = getsockopt (_s, SOL_SOCKET, SO_ERROR,
reinterpret_cast<char *> (&err), &len);
// Assert if the error was caused by 0MQ bug.
// Networking problems are OK. No need to assert.
#ifdef ZMQ_HAVE_WINDOWS
zmq_assert (rc == 0);
if (err != 0) {
if (err == WSAEBADF || err == WSAENOPROTOOPT || err == WSAENOTSOCK
|| err == WSAENOBUFS) {
wsa_assert_no (err);
}
errno = wsa_error_to_errno (err);
return retired_fd;
}
#else
// Following code should handle both Berkeley-derived socket
// implementations and Solaris.
if (rc == -1)
err = errno;
if (err != 0) {
errno = err;
#if !defined(TARGET_OS_IPHONE) || !TARGET_OS_IPHONE
errno_assert (errno != EBADF && errno != ENOPROTOOPT
&& errno != ENOTSOCK && errno != ENOBUFS);
#else
errno_assert (errno != ENOPROTOOPT && errno != ENOTSOCK
&& errno != ENOBUFS);
#endif
return retired_fd;
}
#endif
// Return the newly connected socket.
const fd_t result = _s;
_s = retired_fd;
return result;
}
#endif
| 7,701
|
C++
|
.cpp
| 232
| 26.521552
| 80
| 0.59728
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,373
|
wss_engine.cpp
|
zeromq_libzmq/src/wss_engine.cpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#include "precompiled.hpp"
#include "wss_engine.hpp"
static int verify_certificate_callback (gnutls_session_t session)
{
unsigned int status;
const char *hostname;
// read hostname
hostname = (const char *) gnutls_session_get_ptr (session);
int rc = gnutls_certificate_verify_peers3 (session, hostname, &status);
zmq_assert (rc >= 0);
if (status != 0) {
// TODO: somehow log the error
// Certificate is not trusted
return GNUTLS_E_CERTIFICATE_ERROR;
}
// notify gnutls to continue handshake normally
return 0;
}
zmq::wss_engine_t::wss_engine_t (fd_t fd_,
const options_t &options_,
const endpoint_uri_pair_t &endpoint_uri_pair_,
ws_address_t &address_,
bool client_,
void *tls_server_cred_,
const std::string &hostname_) :
ws_engine_t (fd_, options_, endpoint_uri_pair_, address_, client_),
_established (false),
_tls_client_cred (NULL)
{
int rc = 0;
if (client_) {
// TODO: move to session_base, to allow changing the socket options between connect calls
rc = gnutls_certificate_allocate_credentials (&_tls_client_cred);
zmq_assert (rc == 0);
if (options_.wss_trust_system)
gnutls_certificate_set_x509_system_trust (_tls_client_cred);
if (options_.wss_trust_pem.length () > 0) {
gnutls_datum_t trust = {
(unsigned char *) options_.wss_trust_pem.c_str (),
(unsigned int) options_.wss_trust_pem.length ()};
rc = gnutls_certificate_set_x509_trust_mem (
_tls_client_cred, &trust, GNUTLS_X509_FMT_PEM);
zmq_assert (rc >= 0);
}
gnutls_certificate_set_verify_function (_tls_client_cred,
verify_certificate_callback);
rc = gnutls_init (&_tls_session, GNUTLS_CLIENT | GNUTLS_NONBLOCK);
zmq_assert (rc == GNUTLS_E_SUCCESS);
if (!hostname_.empty ())
gnutls_server_name_set (_tls_session, GNUTLS_NAME_DNS,
hostname_.c_str (), hostname_.size ());
gnutls_session_set_ptr (
_tls_session,
hostname_.empty () ? NULL : const_cast<char *> (hostname_.c_str ()));
rc = gnutls_credentials_set (_tls_session, GNUTLS_CRD_CERTIFICATE,
_tls_client_cred);
zmq_assert (rc == GNUTLS_E_SUCCESS);
} else {
zmq_assert (tls_server_cred_);
rc = gnutls_init (&_tls_session, GNUTLS_SERVER | GNUTLS_NONBLOCK);
zmq_assert (rc == GNUTLS_E_SUCCESS);
rc = gnutls_credentials_set (_tls_session, GNUTLS_CRD_CERTIFICATE,
tls_server_cred_);
zmq_assert (rc == GNUTLS_E_SUCCESS);
}
gnutls_set_default_priority (_tls_session);
gnutls_transport_set_int (_tls_session, fd_);
}
zmq::wss_engine_t::~wss_engine_t ()
{
gnutls_deinit (_tls_session);
if (_tls_client_cred)
gnutls_certificate_free_credentials (_tls_client_cred);
}
void zmq::wss_engine_t::plug_internal ()
{
set_pollin ();
in_event ();
}
void zmq::wss_engine_t::out_event ()
{
if (_established)
return ws_engine_t::out_event ();
do_handshake ();
}
bool zmq::wss_engine_t::do_handshake ()
{
int rc = gnutls_handshake (_tls_session);
reset_pollout ();
if (rc == GNUTLS_E_SUCCESS) {
start_ws_handshake ();
_established = true;
return false;
} else if (rc == GNUTLS_E_AGAIN) {
int direction = gnutls_record_get_direction (_tls_session);
if (direction == 1)
set_pollout ();
return false;
} else if (rc == GNUTLS_E_INTERRUPTED
|| rc == GNUTLS_E_WARNING_ALERT_RECEIVED) {
return false;
} else {
error (zmq::i_engine::connection_error);
return false;
}
return true;
}
bool zmq::wss_engine_t::handshake ()
{
if (!_established) {
if (!do_handshake ()) {
return false;
}
}
return ws_engine_t::handshake ();
}
int zmq::wss_engine_t::read (void *data_, size_t size_)
{
ssize_t rc = gnutls_record_recv (_tls_session, data_, size_);
if (rc == GNUTLS_E_REHANDSHAKE) {
gnutls_alert_send (_tls_session, GNUTLS_AL_WARNING,
GNUTLS_A_NO_RENEGOTIATION);
return 0;
}
if (rc == GNUTLS_E_INTERRUPTED) {
errno = EINTR;
return -1;
}
if (rc == GNUTLS_E_AGAIN) {
errno = EAGAIN;
return -1;
}
if (rc == 0) {
errno = EPIPE;
return -1;
}
if (rc < 0) {
errno = EINVAL;
return -1;
}
// TODO: change return type to ssize_t (signed)
return rc;
}
int zmq::wss_engine_t::write (const void *data_, size_t size_)
{
ssize_t rc = gnutls_record_send (_tls_session, data_, size_);
if (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN) {
return 0;
}
if (rc < 0) {
errno = EINVAL;
return -1;
}
// TODO: change return type to ssize_t (signed)
return rc;
}
| 5,347
|
C++
|
.cpp
| 157
| 25.503185
| 97
| 0.557887
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
14,376
|
peer.cpp
|
zeromq_libzmq/src/peer.cpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#include "precompiled.hpp"
#include "macros.hpp"
#include "peer.hpp"
#include "pipe.hpp"
#include "wire.hpp"
#include "random.hpp"
#include "likely.hpp"
#include "err.hpp"
zmq::peer_t::peer_t (class ctx_t *parent_, uint32_t tid_, int sid_) :
server_t (parent_, tid_, sid_)
{
options.type = ZMQ_PEER;
options.can_send_hello_msg = true;
options.can_recv_disconnect_msg = true;
options.can_recv_hiccup_msg = true;
}
uint32_t zmq::peer_t::connect_peer (const char *endpoint_uri_)
{
scoped_optional_lock_t sync_lock (&_sync);
// connect_peer cannot work with immediate enabled
if (options.immediate == 1) {
errno = EFAULT;
return 0;
}
int rc = socket_base_t::connect_internal (endpoint_uri_);
if (rc != 0)
return 0;
return _peer_last_routing_id;
}
void zmq::peer_t::xattach_pipe (pipe_t *pipe_,
bool subscribe_to_all_,
bool locally_initiated_)
{
server_t::xattach_pipe (pipe_, subscribe_to_all_, locally_initiated_);
_peer_last_routing_id = pipe_->get_server_socket_routing_id ();
}
| 1,168
|
C++
|
.cpp
| 37
| 26.486486
| 74
| 0.635231
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,381
|
proxy.cpp
|
zeromq_libzmq/src/proxy.cpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#include "precompiled.hpp"
#include <stddef.h>
#include "poller.hpp"
#include "proxy.hpp"
#include "likely.hpp"
#include "msg.hpp"
#if defined ZMQ_POLL_BASED_ON_POLL && !defined ZMQ_HAVE_WINDOWS \
&& !defined ZMQ_HAVE_AIX
#include <poll.h>
#endif
// These headers end up pulling in zmq.h somewhere in their include
// dependency chain
#include "socket_base.hpp"
#include "err.hpp"
int zmq::proxy (class socket_base_t *frontend_,
class socket_base_t *backend_,
class socket_base_t *capture_)
{
return zmq::proxy_steerable (frontend_, backend_, capture_, NULL);
}
#ifdef ZMQ_HAVE_POLLER
#include "socket_poller.hpp"
// Macros for repetitive code.
// PROXY_CLEANUP() must not be used before these variables are initialized.
#define PROXY_CLEANUP() \
do { \
delete poller_all; \
delete poller_in; \
delete poller_receive_blocked; \
delete poller_send_blocked; \
delete poller_both_blocked; \
delete poller_frontend_only; \
delete poller_backend_only; \
} while (false)
#define CHECK_RC_EXIT_ON_FAILURE() \
do { \
if (rc < 0) { \
PROXY_CLEANUP (); \
return close_and_return (&msg, -1); \
} \
} while (false)
#endif // ZMQ_HAVE_POLLER
static int
capture (class zmq::socket_base_t *capture_, zmq::msg_t *msg_, int more_ = 0)
{
// Copy message to capture socket if any
if (capture_) {
zmq::msg_t ctrl;
int rc = ctrl.init ();
if (unlikely (rc < 0))
return -1;
rc = ctrl.copy (*msg_);
if (unlikely (rc < 0))
return -1;
rc = capture_->send (&ctrl, more_ ? ZMQ_SNDMORE : 0);
if (unlikely (rc < 0))
return -1;
}
return 0;
}
struct stats_socket
{
uint64_t count, bytes;
};
struct stats_endpoint
{
stats_socket send, recv;
};
struct stats_proxy
{
stats_endpoint frontend, backend;
};
static int forward (class zmq::socket_base_t *from_,
class zmq::socket_base_t *to_,
class zmq::socket_base_t *capture_,
zmq::msg_t *msg_,
stats_socket &recving,
stats_socket &sending)
{
// Forward a burst of messages
for (unsigned int i = 0; i < zmq::proxy_burst_size; i++) {
int more;
size_t moresz;
// Forward all the parts of one message
while (true) {
int rc = from_->recv (msg_, ZMQ_DONTWAIT);
if (rc < 0) {
if (likely (errno == EAGAIN && i > 0))
return 0; // End of burst
return -1;
}
size_t nbytes = msg_->size ();
recving.count += 1;
recving.bytes += nbytes;
moresz = sizeof more;
rc = from_->getsockopt (ZMQ_RCVMORE, &more, &moresz);
if (unlikely (rc < 0))
return -1;
// Copy message to capture socket if any
rc = capture (capture_, msg_, more);
if (unlikely (rc < 0))
return -1;
rc = to_->send (msg_, more ? ZMQ_SNDMORE : 0);
if (unlikely (rc < 0))
return -1;
sending.count += 1;
sending.bytes += nbytes;
if (more == 0)
break;
}
}
return 0;
}
enum proxy_state_t
{
active,
paused,
terminated
};
// Handle control request [5]PAUSE, [6]RESUME, [9]TERMINATE,
// [10]STATISTICS. Only STATISTICS results in a send.
static int handle_control (class zmq::socket_base_t *control_,
proxy_state_t &state,
const stats_proxy &stats)
{
zmq::msg_t cmsg;
int rc = cmsg.init ();
if (rc != 0) {
return -1;
}
rc = control_->recv (&cmsg, ZMQ_DONTWAIT);
if (rc < 0) {
return -1;
}
uint8_t *const command = static_cast<uint8_t *> (cmsg.data ());
const size_t msiz = cmsg.size ();
if (msiz == 10 && 0 == memcmp (command, "STATISTICS", 10)) {
// The stats are a cross product:
//
// (Front,Back) X (Recv,Sent) X (Number,Bytes).
//
// that is flattened into sequence of 8 message parts according to the
// zmq_proxy_steerable(3) documentation as:
//
// (frn, frb, fsn, fsb, brn, brb, bsn, bsb)
//
// f=front/b=back, r=recv/s=send, n=number/b=bytes.
const uint64_t stat_vals[8] = {
stats.frontend.recv.count, stats.frontend.recv.bytes,
stats.frontend.send.count, stats.frontend.send.bytes,
stats.backend.recv.count, stats.backend.recv.bytes,
stats.backend.send.count, stats.backend.send.bytes};
for (size_t ind = 0; ind < 8; ++ind) {
cmsg.init_size (sizeof (uint64_t));
memcpy (cmsg.data (), stat_vals + ind, sizeof (uint64_t));
rc = control_->send (&cmsg, ind < 7 ? ZMQ_SNDMORE : 0);
if (unlikely (rc < 0)) {
return -1;
}
}
return 0;
}
if (msiz == 5 && 0 == memcmp (command, "PAUSE", 5)) {
state = paused;
} else if (msiz == 6 && 0 == memcmp (command, "RESUME", 6)) {
state = active;
} else if (msiz == 9 && 0 == memcmp (command, "TERMINATE", 9)) {
state = terminated;
}
int type;
size_t sz = sizeof (type);
zmq_getsockopt (control_, ZMQ_TYPE, &type, &sz);
if (type == ZMQ_REP) {
// satisfy REP duty and reply no matter what.
cmsg.init_size (0);
rc = control_->send (&cmsg, 0);
if (unlikely (rc < 0)) {
return -1;
}
}
return 0;
}
#ifdef ZMQ_HAVE_POLLER
int zmq::proxy_steerable (class socket_base_t *frontend_,
class socket_base_t *backend_,
class socket_base_t *capture_,
class socket_base_t *control_)
{
msg_t msg;
int rc = msg.init ();
if (rc != 0)
return -1;
// The algorithm below assumes ratio of requests and replies processed
// under full load to be 1:1.
// Proxy can be in these three states
proxy_state_t state = active;
bool frontend_equal_to_backend;
bool frontend_in = false;
bool frontend_out = false;
bool backend_in = false;
bool backend_out = false;
zmq::socket_poller_t::event_t events[4];
int nevents = 3; // increase to 4 if we have control_
stats_proxy stats = {{{0, 0}, {0, 0}}, {{0, 0}, {0, 0}}};
// Don't allocate these pollers from stack because they will take more than 900 kB of stack!
// On Windows this blows up default stack of 1 MB and aborts the program.
// I wanted to use std::shared_ptr here as the best solution but that requires C++11...
zmq::socket_poller_t *poller_all =
new (std::nothrow) zmq::socket_poller_t; // Poll for everything.
zmq::socket_poller_t *poller_in = new (std::nothrow) zmq::
socket_poller_t; // Poll only 'ZMQ_POLLIN' on all sockets. Initial blocking poll in loop.
zmq::socket_poller_t *poller_receive_blocked = new (std::nothrow)
zmq::socket_poller_t; // All except 'ZMQ_POLLIN' on 'frontend_'.
// If frontend_==backend_ 'poller_send_blocked' and 'poller_receive_blocked' are the same, 'ZMQ_POLLIN' is ignored.
// In that case 'poller_send_blocked' is not used. We need only 'poller_receive_blocked'.
// We also don't need 'poller_both_blocked', 'poller_backend_only' nor 'poller_frontend_only' no need to initialize it.
// We save some RAM and time for initialization.
zmq::socket_poller_t *poller_send_blocked =
NULL; // All except 'ZMQ_POLLIN' on 'backend_'.
zmq::socket_poller_t *poller_both_blocked =
NULL; // All except 'ZMQ_POLLIN' on both 'frontend_' and 'backend_'.
zmq::socket_poller_t *poller_frontend_only =
NULL; // Only 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' on 'frontend_'.
zmq::socket_poller_t *poller_backend_only =
NULL; // Only 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' on 'backend_'.
if (frontend_ != backend_) {
poller_send_blocked = new (std::nothrow)
zmq::socket_poller_t; // All except 'ZMQ_POLLIN' on 'backend_'.
poller_both_blocked = new (std::nothrow) zmq::
socket_poller_t; // All except 'ZMQ_POLLIN' on both 'frontend_' and 'backend_'.
poller_frontend_only = new (std::nothrow) zmq::
socket_poller_t; // Only 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' on 'frontend_'.
poller_backend_only = new (std::nothrow) zmq::
socket_poller_t; // Only 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' on 'backend_'.
frontend_equal_to_backend = false;
} else
frontend_equal_to_backend = true;
if (poller_all == NULL || poller_in == NULL
|| poller_receive_blocked == NULL
|| ((poller_send_blocked == NULL || poller_both_blocked == NULL)
&& !frontend_equal_to_backend)) {
PROXY_CLEANUP ();
return close_and_return (&msg, -1);
}
zmq::socket_poller_t *poller_wait =
poller_in; // Poller for blocking wait, initially all 'ZMQ_POLLIN'.
// Register 'frontend_' and 'backend_' with pollers.
rc = poller_all->add (frontend_, NULL,
ZMQ_POLLIN | ZMQ_POLLOUT); // Everything.
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_in->add (frontend_, NULL, ZMQ_POLLIN); // All 'ZMQ_POLLIN's.
CHECK_RC_EXIT_ON_FAILURE ();
if (frontend_equal_to_backend) {
// If frontend_==backend_ 'poller_send_blocked' and 'poller_receive_blocked' are the same,
// so we don't need 'poller_send_blocked'. We need only 'poller_receive_blocked'.
// We also don't need 'poller_both_blocked', no need to initialize it.
rc = poller_receive_blocked->add (frontend_, NULL, ZMQ_POLLOUT);
CHECK_RC_EXIT_ON_FAILURE ();
} else {
rc = poller_all->add (backend_, NULL,
ZMQ_POLLIN | ZMQ_POLLOUT); // Everything.
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_in->add (backend_, NULL, ZMQ_POLLIN); // All 'ZMQ_POLLIN's.
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_both_blocked->add (
frontend_, NULL, ZMQ_POLLOUT); // Waiting only for 'ZMQ_POLLOUT'.
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_both_blocked->add (
backend_, NULL, ZMQ_POLLOUT); // Waiting only for 'ZMQ_POLLOUT'.
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_send_blocked->add (
backend_, NULL,
ZMQ_POLLOUT); // All except 'ZMQ_POLLIN' on 'backend_'.
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_send_blocked->add (
frontend_, NULL,
ZMQ_POLLIN | ZMQ_POLLOUT); // All except 'ZMQ_POLLIN' on 'backend_'.
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_receive_blocked->add (
frontend_, NULL,
ZMQ_POLLOUT); // All except 'ZMQ_POLLIN' on 'frontend_'.
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_receive_blocked->add (
backend_, NULL,
ZMQ_POLLIN | ZMQ_POLLOUT); // All except 'ZMQ_POLLIN' on 'frontend_'.
CHECK_RC_EXIT_ON_FAILURE ();
rc =
poller_frontend_only->add (frontend_, NULL, ZMQ_POLLIN | ZMQ_POLLOUT);
CHECK_RC_EXIT_ON_FAILURE ();
rc =
poller_backend_only->add (backend_, NULL, ZMQ_POLLIN | ZMQ_POLLOUT);
CHECK_RC_EXIT_ON_FAILURE ();
}
if (control_) {
++nevents;
// wherever you go, there you are.
rc = poller_all->add (control_, NULL, ZMQ_POLLIN);
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_in->add (control_, NULL, ZMQ_POLLIN);
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_receive_blocked->add (control_, NULL, ZMQ_POLLIN);
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_send_blocked->add (control_, NULL, ZMQ_POLLIN);
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_both_blocked->add (control_, NULL, ZMQ_POLLIN);
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_frontend_only->add (control_, NULL, ZMQ_POLLIN);
CHECK_RC_EXIT_ON_FAILURE ();
rc = poller_backend_only->add (control_, NULL, ZMQ_POLLIN);
CHECK_RC_EXIT_ON_FAILURE ();
}
bool request_processed = false, reply_processed = false;
while (state != terminated) {
// Blocking wait initially only for 'ZMQ_POLLIN' - 'poller_wait' points to 'poller_in'.
// If one of receiving end's queue is full ('ZMQ_POLLOUT' not available),
// 'poller_wait' is pointed to 'poller_receive_blocked', 'poller_send_blocked' or 'poller_both_blocked'.
rc = poller_wait->wait (events, nevents, -1);
if (rc < 0 && errno == EAGAIN)
rc = 0;
CHECK_RC_EXIT_ON_FAILURE ();
// Some of events waited for by 'poller_wait' have arrived, now poll for everything without blocking.
rc = poller_all->wait (events, nevents, 0);
if (rc < 0 && errno == EAGAIN)
rc = 0;
CHECK_RC_EXIT_ON_FAILURE ();
// Process events.
for (int i = 0; i < rc; i++) {
if (control_ && events[i].socket == control_) {
rc = handle_control (control_, state, stats);
CHECK_RC_EXIT_ON_FAILURE ();
continue;
}
if (events[i].socket == frontend_) {
frontend_in = (events[i].events & ZMQ_POLLIN) != 0;
frontend_out = (events[i].events & ZMQ_POLLOUT) != 0;
} else
// This 'if' needs to be after check for 'frontend_' in order never
// to be reached in case frontend_==backend_, so we ensure backend_in=false in that case.
if (events[i].socket == backend_) {
backend_in = (events[i].events & ZMQ_POLLIN) != 0;
backend_out = (events[i].events & ZMQ_POLLOUT) != 0;
}
}
if (state == active) {
// Process a request, 'ZMQ_POLLIN' on 'frontend_' and 'ZMQ_POLLOUT' on 'backend_'.
// In case of frontend_==backend_ there's no 'ZMQ_POLLOUT' event.
if (frontend_in && (backend_out || frontend_equal_to_backend)) {
rc = forward (frontend_, backend_, capture_, &msg,
stats.frontend.recv, stats.backend.send);
CHECK_RC_EXIT_ON_FAILURE ();
request_processed = true;
frontend_in = backend_out = false;
} else
request_processed = false;
// Process a reply, 'ZMQ_POLLIN' on 'backend_' and 'ZMQ_POLLOUT' on 'frontend_'.
// If 'frontend_' and 'backend_' are the same this is not needed because previous processing
// covers all of the cases. 'backend_in' is always false if frontend_==backend_ due to
// design in 'for' event processing loop.
if (backend_in && frontend_out) {
rc = forward (backend_, frontend_, capture_, &msg,
stats.backend.recv, stats.frontend.send);
CHECK_RC_EXIT_ON_FAILURE ();
reply_processed = true;
backend_in = frontend_out = false;
} else
reply_processed = false;
if (request_processed || reply_processed) {
// If request/reply is processed that means we had at least one 'ZMQ_POLLOUT' event.
// Enable corresponding 'ZMQ_POLLIN' for blocking wait if any was disabled.
if (poller_wait != poller_in) {
if (request_processed) { // 'frontend_' -> 'backend_'
if (poller_wait == poller_both_blocked)
poller_wait = poller_send_blocked;
else if (poller_wait == poller_receive_blocked
|| poller_wait == poller_frontend_only)
poller_wait = poller_in;
}
if (reply_processed) { // 'backend_' -> 'frontend_'
if (poller_wait == poller_both_blocked)
poller_wait = poller_receive_blocked;
else if (poller_wait == poller_send_blocked
|| poller_wait == poller_backend_only)
poller_wait = poller_in;
}
}
} else {
// No requests have been processed, there were no 'ZMQ_POLLIN' with corresponding 'ZMQ_POLLOUT' events.
// That means that out queue(s) is/are full or one out queue is full and second one has no messages to process.
// Disable receiving 'ZMQ_POLLIN' for sockets for which there's no 'ZMQ_POLLOUT',
// or wait only on both 'backend_''s or 'frontend_''s 'ZMQ_POLLIN' and 'ZMQ_POLLOUT'.
if (frontend_in) {
if (frontend_out)
// If frontend_in and frontend_out are true, obviously backend_in and backend_out are both false.
// In that case we need to wait for both 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' only on 'backend_'.
// We'll never get here in case of frontend_==backend_ because then frontend_out will always be false.
poller_wait = poller_backend_only;
else {
if (poller_wait == poller_send_blocked)
poller_wait = poller_both_blocked;
else if (poller_wait == poller_in)
poller_wait = poller_receive_blocked;
}
}
if (backend_in) {
// Will never be reached if frontend_==backend_, 'backend_in' will
// always be false due to design in 'for' event processing loop.
if (backend_out)
// If backend_in and backend_out are true, obviously frontend_in and frontend_out are both false.
// In that case we need to wait for both 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' only on 'frontend_'.
poller_wait = poller_frontend_only;
else {
if (poller_wait == poller_receive_blocked)
poller_wait = poller_both_blocked;
else if (poller_wait == poller_in)
poller_wait = poller_send_blocked;
}
}
}
}
}
PROXY_CLEANUP ();
return close_and_return (&msg, 0);
}
#else // ZMQ_HAVE_POLLER
int zmq::proxy_steerable (class socket_base_t *frontend_,
class socket_base_t *backend_,
class socket_base_t *capture_,
class socket_base_t *control_)
{
msg_t msg;
int rc = msg.init ();
if (rc != 0)
return -1;
// The algorithm below assumes ratio of requests and replies processed
// under full load to be 1:1.
zmq_pollitem_t items[] = {{frontend_, 0, ZMQ_POLLIN, 0},
{backend_, 0, ZMQ_POLLIN, 0},
{control_, 0, ZMQ_POLLIN, 0}};
const int qt_poll_items = control_ ? 3 : 2;
zmq_pollitem_t itemsout[] = {{frontend_, 0, ZMQ_POLLOUT, 0},
{backend_, 0, ZMQ_POLLOUT, 0}};
stats_proxy stats = {0};
// Proxy can be in these three states
proxy_state_t state = active;
while (state != terminated) {
// Wait while there are either requests or replies to process.
rc = zmq_poll (&items[0], qt_poll_items, -1);
if (unlikely (rc < 0))
return close_and_return (&msg, -1);
if (control_ && items[2].revents & ZMQ_POLLIN) {
rc = handle_control (control_, state, stats);
if (unlikely (rc < 0))
return close_and_return (&msg, -1);
}
// Get the pollout separately because when combining this with pollin it maxes the CPU
// because pollout shall most of the time return directly.
// POLLOUT is only checked when frontend and backend sockets are not the same.
if (frontend_ != backend_) {
rc = zmq_poll (&itemsout[0], 2, 0);
if (unlikely (rc < 0)) {
return close_and_return (&msg, -1);
}
}
if (state == active && items[0].revents & ZMQ_POLLIN
&& (frontend_ == backend_ || itemsout[1].revents & ZMQ_POLLOUT)) {
rc = forward (frontend_, backend_, capture_, &msg,
stats.frontend.recv, stats.backend.send);
if (unlikely (rc < 0))
return close_and_return (&msg, -1);
}
// Process a reply
if (state == active && frontend_ != backend_
&& items[1].revents & ZMQ_POLLIN
&& itemsout[0].revents & ZMQ_POLLOUT) {
rc = forward (backend_, frontend_, capture_, &msg,
stats.backend.recv, stats.frontend.send);
if (unlikely (rc < 0))
return close_and_return (&msg, -1);
}
}
return close_and_return (&msg, 0);
}
#endif // ZMQ_HAVE_POLLER
| 22,275
|
C++
|
.cpp
| 484
| 35.283058
| 128
| 0.528315
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
14,390
|
vmci_listener.cpp
|
zeromq_libzmq/src/vmci_listener.cpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#include "precompiled.hpp"
#include "vmci_listener.hpp"
#if defined ZMQ_HAVE_VMCI
#include <new>
//#include "stream_engine.hpp"
#include "vmci_address.hpp"
#include "io_thread.hpp"
#include "session_base.hpp"
#include "config.hpp"
#include "err.hpp"
#include "ip.hpp"
#include "socket_base.hpp"
#include "vmci.hpp"
#if defined ZMQ_HAVE_WINDOWS
#include "windows.hpp"
#else
#include <unistd.h>
#include <fcntl.h>
#endif
zmq::vmci_listener_t::vmci_listener_t (io_thread_t *io_thread_,
socket_base_t *socket_,
const options_t &options_) :
stream_listener_base_t (io_thread_, socket_, options_)
{
}
void zmq::vmci_listener_t::in_event ()
{
fd_t fd = accept ();
// If connection was reset by the peer in the meantime, just ignore it.
if (fd == retired_fd) {
_socket->event_accept_failed (
make_unconnected_bind_endpoint_pair (_endpoint), zmq_errno ());
return;
}
tune_vmci_buffer_size (this->get_ctx (), fd, options.vmci_buffer_size,
options.vmci_buffer_min_size,
options.vmci_buffer_max_size);
if (options.vmci_connect_timeout > 0) {
#if defined ZMQ_HAVE_WINDOWS
tune_vmci_connect_timeout (this->get_ctx (), fd,
options.vmci_connect_timeout);
#else
struct timeval timeout = {0, options.vmci_connect_timeout * 1000};
tune_vmci_connect_timeout (this->get_ctx (), fd, timeout);
#endif
}
// Create the engine object for this connection.
create_engine (fd);
}
std::string
zmq::vmci_listener_t::get_socket_name (zmq::fd_t fd_,
socket_end_t socket_end_) const
{
struct sockaddr_storage ss;
const zmq_socklen_t sl = get_socket_address (fd_, socket_end_, &ss);
if (sl == 0) {
return std::string ();
}
const vmci_address_t addr (reinterpret_cast<struct sockaddr *> (&ss), sl,
this->get_ctx ());
std::string address_string;
addr.to_string (address_string);
return address_string;
}
int zmq::vmci_listener_t::set_local_address (const char *addr_)
{
// Create addr on stack for auto-cleanup
std::string addr (addr_);
// Initialise the address structure.
vmci_address_t address (this->get_ctx ());
int rc = address.resolve (addr.c_str ());
if (rc != 0)
return -1;
// Create a listening socket.
_s =
open_socket (this->get_ctx ()->get_vmci_socket_family (), SOCK_STREAM, 0);
#ifdef ZMQ_HAVE_WINDOWS
if (s == INVALID_SOCKET) {
errno = wsa_error_to_errno (WSAGetLastError ());
return -1;
}
#if !defined _WIN32_WCE
// On Windows, preventing sockets to be inherited by child processes.
BOOL brc = SetHandleInformation ((HANDLE) _s, HANDLE_FLAG_INHERIT, 0);
win_assert (brc);
#endif
#else
if (_s == -1)
return -1;
#endif
address.to_string (_endpoint);
// Bind the socket.
rc = bind (_s, address.addr (), address.addrlen ());
#ifdef ZMQ_HAVE_WINDOWS
if (rc == SOCKET_ERROR) {
errno = wsa_error_to_errno (WSAGetLastError ());
goto error;
}
#else
if (rc != 0)
goto error;
#endif
// Listen for incoming connections.
rc = listen (_s, options.backlog);
#ifdef ZMQ_HAVE_WINDOWS
if (rc == SOCKET_ERROR) {
errno = wsa_error_to_errno (WSAGetLastError ());
goto error;
}
#else
if (rc != 0)
goto error;
#endif
_socket->event_listening (make_unconnected_bind_endpoint_pair (_endpoint),
_s);
return 0;
error:
int err = errno;
close ();
errno = err;
return -1;
}
zmq::fd_t zmq::vmci_listener_t::accept ()
{
// Accept one connection and deal with different failure modes.
// The situation where connection cannot be accepted due to insufficient
// resources is considered valid and treated by ignoring the connection.
zmq_assert (_s != retired_fd);
fd_t sock = ::accept (_s, NULL, NULL);
#ifdef ZMQ_HAVE_WINDOWS
if (sock == INVALID_SOCKET) {
wsa_assert (WSAGetLastError () == WSAEWOULDBLOCK
|| WSAGetLastError () == WSAECONNRESET
|| WSAGetLastError () == WSAEMFILE
|| WSAGetLastError () == WSAENOBUFS);
return retired_fd;
}
#if !defined _WIN32_WCE
// On Windows, preventing sockets to be inherited by child processes.
BOOL brc = SetHandleInformation ((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
win_assert (brc);
#endif
#else
if (sock == -1) {
errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR
|| errno == ECONNABORTED || errno == EPROTO
|| errno == ENOBUFS || errno == ENOMEM || errno == EMFILE
|| errno == ENFILE);
return retired_fd;
}
#endif
// Race condition can cause socket not to be closed (if fork happens
// between accept and this point).
#ifdef FD_CLOEXEC
int rc = fcntl (sock, F_SETFD, FD_CLOEXEC);
errno_assert (rc != -1);
#endif
return sock;
}
#endif
| 5,256
|
C++
|
.cpp
| 161
| 26.304348
| 80
| 0.606156
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,403
|
vmci.cpp
|
zeromq_libzmq/src/vmci.cpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#include "precompiled.hpp"
#include "ip.hpp"
#include "vmci.hpp"
#include "vmci_address.hpp"
#if defined ZMQ_HAVE_VMCI
#include <cassert>
#include <vmci_sockets.h>
void zmq::tune_vmci_buffer_size (ctx_t *context_,
fd_t sockfd_,
uint64_t default_size_,
uint64_t min_size_,
uint64_t max_size_)
{
int family = context_->get_vmci_socket_family ();
assert (family != -1);
if (default_size_ != 0) {
int rc = setsockopt (sockfd_, family, SO_VMCI_BUFFER_SIZE,
(char *) &default_size_, sizeof default_size_);
#if defined ZMQ_HAVE_WINDOWS
wsa_assert (rc != SOCKET_ERROR);
#else
errno_assert (rc == 0);
#endif
}
if (min_size_ != 0) {
int rc = setsockopt (sockfd_, family, SO_VMCI_BUFFER_SIZE,
(char *) &min_size_, sizeof min_size_);
#if defined ZMQ_HAVE_WINDOWS
wsa_assert (rc != SOCKET_ERROR);
#else
errno_assert (rc == 0);
#endif
}
if (max_size_ != 0) {
int rc = setsockopt (sockfd_, family, SO_VMCI_BUFFER_SIZE,
(char *) &max_size_, sizeof max_size_);
#if defined ZMQ_HAVE_WINDOWS
wsa_assert (rc != SOCKET_ERROR);
#else
errno_assert (rc == 0);
#endif
}
}
#if defined ZMQ_HAVE_WINDOWS
void zmq::tune_vmci_connect_timeout (ctx_t *context_,
fd_t sockfd_,
DWORD timeout_)
#else
void zmq::tune_vmci_connect_timeout (ctx_t *context_,
fd_t sockfd_,
struct timeval timeout_)
#endif
{
int family = context_->get_vmci_socket_family ();
assert (family != -1);
int rc = setsockopt (sockfd_, family, SO_VMCI_CONNECT_TIMEOUT,
(char *) &timeout_, sizeof timeout_);
#if defined ZMQ_HAVE_WINDOWS
wsa_assert (rc != SOCKET_ERROR);
#else
errno_assert (rc == 0);
#endif
}
zmq::fd_t zmq::vmci_open_socket (const char *address_,
const zmq::options_t &options_,
zmq::vmci_address_t *out_vmci_addr_)
{
// Convert the textual address into address structure.
int rc = out_vmci_addr_->resolve (address_);
if (rc != 0)
return retired_fd;
// Create the socket.
fd_t s = open_socket (out_vmci_addr_->family (), SOCK_STREAM, 0);
if (s == retired_fd) {
return retired_fd;
}
return s;
}
#endif
| 2,637
|
C++
|
.cpp
| 80
| 23.9125
| 76
| 0.534801
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,404
|
ws_encoder.cpp
|
zeromq_libzmq/src/ws_encoder.cpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#include "precompiled.hpp"
#include "ws_protocol.hpp"
#include "ws_encoder.hpp"
#include "msg.hpp"
#include "likely.hpp"
#include "wire.hpp"
#include "random.hpp"
#include <limits.h>
zmq::ws_encoder_t::ws_encoder_t (size_t bufsize_, bool must_mask_) :
encoder_base_t<ws_encoder_t> (bufsize_), _must_mask (must_mask_)
{
// Write 0 bytes to the batch and go to message_ready state.
next_step (NULL, 0, &ws_encoder_t::message_ready, true);
_masked_msg.init ();
}
zmq::ws_encoder_t::~ws_encoder_t ()
{
_masked_msg.close ();
}
void zmq::ws_encoder_t::message_ready ()
{
int offset = 0;
_is_binary = false;
if (in_progress ()->is_ping ())
_tmp_buf[offset++] = 0x80 | zmq::ws_protocol_t::opcode_ping;
else if (in_progress ()->is_pong ())
_tmp_buf[offset++] = 0x80 | zmq::ws_protocol_t::opcode_pong;
else if (in_progress ()->is_close_cmd ())
_tmp_buf[offset++] = 0x80 | zmq::ws_protocol_t::opcode_close;
else {
_tmp_buf[offset++] = 0x82; // Final | binary
_is_binary = true;
}
_tmp_buf[offset] = _must_mask ? 0x80 : 0x00;
size_t size = in_progress ()->size ();
if (_is_binary)
size++;
// TODO: create an opcode for subscribe/cancel
if (in_progress ()->is_subscribe () || in_progress ()->is_cancel ())
size++;
if (size <= 125)
_tmp_buf[offset++] |= static_cast<unsigned char> (size & 127);
else if (size <= 0xFFFF) {
_tmp_buf[offset++] |= 126;
_tmp_buf[offset++] = static_cast<unsigned char> ((size >> 8) & 0xFF);
_tmp_buf[offset++] = static_cast<unsigned char> (size & 0xFF);
} else {
_tmp_buf[offset++] |= 127;
put_uint64 (_tmp_buf + offset, size);
offset += 8;
}
if (_must_mask) {
const uint32_t random = generate_random ();
put_uint32 (_tmp_buf + offset, random);
put_uint32 (_mask, random);
offset += 4;
}
int mask_index = 0;
if (_is_binary) {
// Encode flags.
unsigned char protocol_flags = 0;
if (in_progress ()->flags () & msg_t::more)
protocol_flags |= ws_protocol_t::more_flag;
if (in_progress ()->flags () & msg_t::command)
protocol_flags |= ws_protocol_t::command_flag;
_tmp_buf[offset++] =
_must_mask ? protocol_flags ^ _mask[mask_index++] : protocol_flags;
}
// Encode the subscribe/cancel byte.
// TODO: remove once there is an opcode for subscribe/cancel
if (in_progress ()->is_subscribe ())
_tmp_buf[offset++] = _must_mask ? 1 ^ _mask[mask_index++] : 1;
else if (in_progress ()->is_cancel ())
_tmp_buf[offset++] = _must_mask ? 0 ^ _mask[mask_index++] : 0;
next_step (_tmp_buf, offset, &ws_encoder_t::size_ready, false);
}
void zmq::ws_encoder_t::size_ready ()
{
if (_must_mask) {
assert (in_progress () != &_masked_msg);
const size_t size = in_progress ()->size ();
unsigned char *src =
static_cast<unsigned char *> (in_progress ()->data ());
unsigned char *dest = src;
// If msg is shared or data is constant we cannot mask in-place, allocate a new msg for it
if (in_progress ()->flags () & msg_t::shared
|| in_progress ()->is_cmsg ()) {
_masked_msg.close ();
_masked_msg.init_size (size);
dest = static_cast<unsigned char *> (_masked_msg.data ());
}
int mask_index = 0;
if (_is_binary)
++mask_index;
// TODO: remove once there is an opcode for subscribe/cancel
if (in_progress ()->is_subscribe () || in_progress ()->is_cancel ())
++mask_index;
for (size_t i = 0; i < size; ++i, mask_index++)
dest[i] = src[i] ^ _mask[mask_index % 4];
next_step (dest, size, &ws_encoder_t::message_ready, true);
} else {
next_step (in_progress ()->data (), in_progress ()->size (),
&ws_encoder_t::message_ready, true);
}
}
| 4,076
|
C++
|
.cpp
| 106
| 31.650943
| 99
| 0.564304
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,422
|
curve_mechanism_base.cpp
|
zeromq_libzmq/src/curve_mechanism_base.cpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#include "precompiled.hpp"
#include "curve_mechanism_base.hpp"
#include "msg.hpp"
#include "wire.hpp"
#include "session_base.hpp"
#ifdef ZMQ_HAVE_CURVE
#ifdef ZMQ_USE_LIBSODIUM
// libsodium added crypto_box_easy_afternm and crypto_box_open_easy_afternm with
// https: //github.com/jedisct1/libsodium/commit/aaf5fbf2e53a33b18d8ea9bdf2c6f73d7acc8c3e
#if SODIUM_LIBRARY_VERSION_MAJOR > 7 \
|| (SODIUM_LIBRARY_VERSION_MAJOR == 7 && SODIUM_LIBRARY_VERSION_MINOR >= 4)
#define ZMQ_HAVE_CRYPTO_BOX_EASY_FNS 1
#endif
#endif
zmq::curve_mechanism_base_t::curve_mechanism_base_t (
session_base_t *session_,
const options_t &options_,
const char *encode_nonce_prefix_,
const char *decode_nonce_prefix_,
const bool downgrade_sub_) :
mechanism_base_t (session_, options_),
curve_encoding_t (
encode_nonce_prefix_, decode_nonce_prefix_, downgrade_sub_)
{
}
int zmq::curve_mechanism_base_t::encode (msg_t *msg_)
{
return curve_encoding_t::encode (msg_);
}
int zmq::curve_mechanism_base_t::decode (msg_t *msg_)
{
int rc = check_basic_command_structure (msg_);
if (rc == -1)
return -1;
int error_event_code;
rc = curve_encoding_t::decode (msg_, &error_event_code);
if (-1 == rc) {
session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), error_event_code);
}
return rc;
}
zmq::curve_encoding_t::curve_encoding_t (const char *encode_nonce_prefix_,
const char *decode_nonce_prefix_,
const bool downgrade_sub_) :
_encode_nonce_prefix (encode_nonce_prefix_),
_decode_nonce_prefix (decode_nonce_prefix_),
_cn_nonce (1),
_cn_peer_nonce (1),
_downgrade_sub (downgrade_sub_)
{
}
// Right now, we only transport the lower two bit flags of zmq::msg_t, so they
// are binary identical, and we can just use a bitmask to select them. If we
// happened to add more flags, this might change.
static const uint8_t flag_mask = zmq::msg_t::more | zmq::msg_t::command;
static const size_t flags_len = 1;
static const size_t nonce_prefix_len = 16;
static const char message_command[] = "\x07MESSAGE";
static const size_t message_command_len = sizeof (message_command) - 1;
static const size_t message_header_len =
message_command_len + sizeof (zmq::curve_encoding_t::nonce_t);
#ifndef ZMQ_USE_LIBSODIUM
static const size_t crypto_box_MACBYTES = 16;
#endif
int zmq::curve_encoding_t::check_validity (msg_t *msg_, int *error_event_code_)
{
const size_t size = msg_->size ();
const uint8_t *const message = static_cast<uint8_t *> (msg_->data ());
if (size < message_command_len
|| 0 != memcmp (message, message_command, message_command_len)) {
*error_event_code_ = ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND;
errno = EPROTO;
return -1;
}
if (size < message_header_len + crypto_box_MACBYTES + flags_len) {
*error_event_code_ = ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_MESSAGE;
errno = EPROTO;
return -1;
}
{
const uint64_t nonce = get_uint64 (message + message_command_len);
if (nonce <= _cn_peer_nonce) {
*error_event_code_ = ZMQ_PROTOCOL_ERROR_ZMTP_INVALID_SEQUENCE;
errno = EPROTO;
return -1;
}
set_peer_nonce (nonce);
}
return 0;
}
int zmq::curve_encoding_t::encode (msg_t *msg_)
{
size_t sub_cancel_len = 0;
uint8_t message_nonce[crypto_box_NONCEBYTES];
memcpy (message_nonce, _encode_nonce_prefix, nonce_prefix_len);
put_uint64 (message_nonce + nonce_prefix_len, get_and_inc_nonce ());
if (msg_->is_subscribe () || msg_->is_cancel ()) {
if (_downgrade_sub)
sub_cancel_len = 1;
else
sub_cancel_len = msg_->is_cancel ()
? zmq::msg_t::cancel_cmd_name_size
: zmq::msg_t::sub_cmd_name_size;
}
#ifdef ZMQ_HAVE_CRYPTO_BOX_EASY_FNS
const size_t mlen = flags_len + sub_cancel_len + msg_->size ();
std::vector<uint8_t> message_plaintext (mlen);
#else
const size_t mlen =
crypto_box_ZEROBYTES + flags_len + sub_cancel_len + msg_->size ();
std::vector<uint8_t> message_plaintext_with_zerobytes (mlen);
uint8_t *const message_plaintext =
&message_plaintext_with_zerobytes[crypto_box_ZEROBYTES];
std::fill (message_plaintext_with_zerobytes.begin (),
message_plaintext_with_zerobytes.begin () + crypto_box_ZEROBYTES,
0);
#endif
const uint8_t flags = msg_->flags () & flag_mask;
message_plaintext[0] = flags;
// For backward compatibility subscribe/cancel command messages are not stored with
// the message flags, and are encoded in the encoder, so that messages for < 3.0 peers
// can be encoded in the "old" 0/1 way rather than as commands.
if (sub_cancel_len == 1)
message_plaintext[flags_len] = msg_->is_subscribe () ? 1 : 0;
else if (sub_cancel_len == zmq::msg_t::sub_cmd_name_size) {
message_plaintext[0] |= zmq::msg_t::command;
memcpy (&message_plaintext[flags_len], zmq::sub_cmd_name,
zmq::msg_t::sub_cmd_name_size);
} else if (sub_cancel_len == zmq::msg_t::cancel_cmd_name_size) {
message_plaintext[0] |= zmq::msg_t::command;
memcpy (&message_plaintext[flags_len], zmq::cancel_cmd_name,
zmq::msg_t::cancel_cmd_name_size);
}
// this is copying the data from insecure memory, so there is no point in
// using secure_allocator_t for message_plaintext
if (msg_->size () > 0)
memcpy (&message_plaintext[flags_len + sub_cancel_len], msg_->data (),
msg_->size ());
#ifdef ZMQ_HAVE_CRYPTO_BOX_EASY_FNS
msg_t msg_box;
int rc =
msg_box.init_size (message_header_len + mlen + crypto_box_MACBYTES);
zmq_assert (rc == 0);
rc = crypto_box_easy_afternm (
static_cast<uint8_t *> (msg_box.data ()) + message_header_len,
&message_plaintext[0], mlen, message_nonce, _cn_precom);
zmq_assert (rc == 0);
msg_->move (msg_box);
uint8_t *const message = static_cast<uint8_t *> (msg_->data ());
#else
std::vector<uint8_t> message_box (mlen);
int rc =
crypto_box_afternm (&message_box[0], &message_plaintext_with_zerobytes[0],
mlen, message_nonce, _cn_precom);
zmq_assert (rc == 0);
rc = msg_->close ();
zmq_assert (rc == 0);
rc = msg_->init_size (16 + mlen - crypto_box_BOXZEROBYTES);
zmq_assert (rc == 0);
uint8_t *const message = static_cast<uint8_t *> (msg_->data ());
memcpy (message + message_header_len, &message_box[crypto_box_BOXZEROBYTES],
mlen - crypto_box_BOXZEROBYTES);
#endif
memcpy (message, message_command, message_command_len);
memcpy (message + message_command_len, message_nonce + nonce_prefix_len,
sizeof (nonce_t));
return 0;
}
int zmq::curve_encoding_t::decode (msg_t *msg_, int *error_event_code_)
{
int rc = check_validity (msg_, error_event_code_);
if (0 != rc) {
return rc;
}
uint8_t *const message = static_cast<uint8_t *> (msg_->data ());
uint8_t message_nonce[crypto_box_NONCEBYTES];
memcpy (message_nonce, _decode_nonce_prefix, nonce_prefix_len);
memcpy (message_nonce + nonce_prefix_len, message + message_command_len,
sizeof (nonce_t));
#ifdef ZMQ_HAVE_CRYPTO_BOX_EASY_FNS
const size_t clen = msg_->size () - message_header_len;
uint8_t *const message_plaintext = message + message_header_len;
rc = crypto_box_open_easy_afternm (message_plaintext,
message + message_header_len, clen,
message_nonce, _cn_precom);
#else
const size_t clen =
crypto_box_BOXZEROBYTES + msg_->size () - message_header_len;
std::vector<uint8_t> message_plaintext_with_zerobytes (clen);
std::vector<uint8_t> message_box (clen);
std::fill (message_box.begin (),
message_box.begin () + crypto_box_BOXZEROBYTES, 0);
memcpy (&message_box[crypto_box_BOXZEROBYTES], message + message_header_len,
msg_->size () - message_header_len);
rc = crypto_box_open_afternm (&message_plaintext_with_zerobytes[0],
&message_box[0], clen, message_nonce,
_cn_precom);
const uint8_t *const message_plaintext =
&message_plaintext_with_zerobytes[crypto_box_ZEROBYTES];
#endif
if (rc == 0) {
const uint8_t flags = message_plaintext[0];
#ifdef ZMQ_HAVE_CRYPTO_BOX_EASY_FNS
const size_t plaintext_size = clen - flags_len - crypto_box_MACBYTES;
if (plaintext_size > 0) {
memmove (msg_->data (), &message_plaintext[flags_len],
plaintext_size);
}
msg_->shrink (plaintext_size);
#else
rc = msg_->close ();
zmq_assert (rc == 0);
rc = msg_->init_size (clen - flags_len - crypto_box_ZEROBYTES);
zmq_assert (rc == 0);
// this is copying the data to insecure memory, so there is no point in
// using secure_allocator_t for message_plaintext
if (msg_->size () > 0) {
memcpy (msg_->data (), &message_plaintext[flags_len],
msg_->size ());
}
#endif
msg_->set_flags (flags & flag_mask);
} else {
// CURVE I : connection key used for MESSAGE is wrong
*error_event_code_ = ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC;
errno = EPROTO;
}
return rc;
}
#endif
| 9,737
|
C++
|
.cpp
| 232
| 35.030172
| 90
| 0.623744
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,439
|
v1_encoder.cpp
|
zeromq_libzmq/src/v1_encoder.cpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#include "precompiled.hpp"
#include "encoder.hpp"
#include "v1_encoder.hpp"
#include "msg.hpp"
#include "wire.hpp"
#include <limits.h>
zmq::v1_encoder_t::v1_encoder_t (size_t bufsize_) :
encoder_base_t<v1_encoder_t> (bufsize_)
{
// Write 0 bytes to the batch and go to message_ready state.
next_step (NULL, 0, &v1_encoder_t::message_ready, true);
}
zmq::v1_encoder_t::~v1_encoder_t ()
{
}
void zmq::v1_encoder_t::size_ready ()
{
// Write message body into the buffer.
next_step (in_progress ()->data (), in_progress ()->size (),
&v1_encoder_t::message_ready, true);
}
void zmq::v1_encoder_t::message_ready ()
{
size_t header_size = 2; // flags byte + size byte
// Get the message size.
size_t size = in_progress ()->size ();
// Account for the 'flags' byte.
size++;
// Account for the subscribe/cancel byte.
if (in_progress ()->is_subscribe () || in_progress ()->is_cancel ())
size++;
// For messages less than 255 bytes long, write one byte of message size.
// For longer messages write 0xff escape character followed by 8-byte
// message size. In both cases 'flags' field follows.
if (size < UCHAR_MAX) {
_tmpbuf[0] = static_cast<unsigned char> (size);
_tmpbuf[1] = (in_progress ()->flags () & msg_t::more);
} else {
_tmpbuf[0] = UCHAR_MAX;
put_uint64 (_tmpbuf + 1, size);
_tmpbuf[9] = (in_progress ()->flags () & msg_t::more);
header_size = 10;
}
// Encode the subscribe/cancel byte. This is done in the encoder as
// opposed to when the subscribe message is created to allow different
// protocol behaviour on the wire in the v3.1 and legacy encoders.
// It results in the work being done multiple times in case the sub
// is sending the subscription/cancel to multiple pubs, but it cannot
// be avoided. This processing can be moved to xsub once support for
// ZMTP < 3.1 is dropped.
if (in_progress ()->is_subscribe ())
_tmpbuf[header_size++] = 1;
else if (in_progress ()->is_cancel ())
_tmpbuf[header_size++] = 0;
next_step (_tmpbuf, header_size, &v1_encoder_t::size_ready, false);
}
| 2,255
|
C++
|
.cpp
| 57
| 34.877193
| 78
| 0.635574
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,455
|
channel.cpp
|
zeromq_libzmq/src/channel.cpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#include "precompiled.hpp"
#include "macros.hpp"
#include "channel.hpp"
#include "err.hpp"
#include "pipe.hpp"
#include "msg.hpp"
zmq::channel_t::channel_t (class ctx_t *parent_, uint32_t tid_, int sid_) :
socket_base_t (parent_, tid_, sid_, true), _pipe (NULL)
{
options.type = ZMQ_CHANNEL;
}
zmq::channel_t::~channel_t ()
{
zmq_assert (!_pipe);
}
void zmq::channel_t::xattach_pipe (pipe_t *pipe_,
bool subscribe_to_all_,
bool locally_initiated_)
{
LIBZMQ_UNUSED (subscribe_to_all_);
LIBZMQ_UNUSED (locally_initiated_);
zmq_assert (pipe_ != NULL);
// ZMQ_PAIR socket can only be connected to a single peer.
// The socket rejects any further connection requests.
if (_pipe == NULL)
_pipe = pipe_;
else
pipe_->terminate (false);
}
void zmq::channel_t::xpipe_terminated (pipe_t *pipe_)
{
if (pipe_ == _pipe)
_pipe = NULL;
}
void zmq::channel_t::xread_activated (pipe_t *)
{
// There's just one pipe. No lists of active and inactive pipes.
// There's nothing to do here.
}
void zmq::channel_t::xwrite_activated (pipe_t *)
{
// There's just one pipe. No lists of active and inactive pipes.
// There's nothing to do here.
}
int zmq::channel_t::xsend (msg_t *msg_)
{
// CHANNEL sockets do not allow multipart data (ZMQ_SNDMORE)
if (msg_->flags () & msg_t::more) {
errno = EINVAL;
return -1;
}
if (!_pipe || !_pipe->write (msg_)) {
errno = EAGAIN;
return -1;
}
_pipe->flush ();
// Detach the original message from the data buffer.
const int rc = msg_->init ();
errno_assert (rc == 0);
return 0;
}
int zmq::channel_t::xrecv (msg_t *msg_)
{
// Deallocate old content of the message.
int rc = msg_->close ();
errno_assert (rc == 0);
if (!_pipe) {
// Initialise the output parameter to be a 0-byte message.
rc = msg_->init ();
errno_assert (rc == 0);
errno = EAGAIN;
return -1;
}
// Drop any messages with more flag
bool read = _pipe->read (msg_);
while (read && msg_->flags () & msg_t::more) {
// drop all frames of the current multi-frame message
read = _pipe->read (msg_);
while (read && msg_->flags () & msg_t::more)
read = _pipe->read (msg_);
// get the new message
if (read)
read = _pipe->read (msg_);
}
if (!read) {
// Initialise the output parameter to be a 0-byte message.
rc = msg_->init ();
errno_assert (rc == 0);
errno = EAGAIN;
return -1;
}
return 0;
}
bool zmq::channel_t::xhas_in ()
{
if (!_pipe)
return false;
return _pipe->check_read ();
}
bool zmq::channel_t::xhas_out ()
{
if (!_pipe)
return false;
return _pipe->check_write ();
}
| 2,966
|
C++
|
.cpp
| 106
| 22.490566
| 75
| 0.573042
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,456
|
sub.cpp
|
zeromq_libzmq/src/sub.cpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#include "precompiled.hpp"
#include "sub.hpp"
#include "msg.hpp"
zmq::sub_t::sub_t (class ctx_t *parent_, uint32_t tid_, int sid_) :
xsub_t (parent_, tid_, sid_)
{
options.type = ZMQ_SUB;
// Switch filtering messages on (as opposed to XSUB which where the
// filtering is off).
options.filter = true;
}
zmq::sub_t::~sub_t ()
{
}
int zmq::sub_t::xsetsockopt (int option_,
const void *optval_,
size_t optvallen_)
{
if (option_ != ZMQ_SUBSCRIBE && option_ != ZMQ_UNSUBSCRIBE) {
errno = EINVAL;
return -1;
}
// Create the subscription message.
msg_t msg;
int rc;
const unsigned char *data = static_cast<const unsigned char *> (optval_);
if (option_ == ZMQ_SUBSCRIBE) {
rc = msg.init_subscribe (optvallen_, data);
} else {
rc = msg.init_cancel (optvallen_, data);
}
errno_assert (rc == 0);
// Pass it further on in the stack.
rc = xsub_t::xsend (&msg);
return close_and_return (&msg, rc);
}
int zmq::sub_t::xsend (msg_t *)
{
// Override the XSUB's send.
errno = ENOTSUP;
return -1;
}
bool zmq::sub_t::xhas_out ()
{
// Override the XSUB's send.
return false;
}
| 1,291
|
C++
|
.cpp
| 48
| 21.916667
| 77
| 0.58671
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,457
|
wss_address.cpp
|
zeromq_libzmq/src/wss_address.cpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#include "precompiled.hpp"
#include <string>
#include <sstream>
#include "wss_address.hpp"
zmq::wss_address_t::wss_address_t () : ws_address_t ()
{
}
zmq::wss_address_t::wss_address_t (const sockaddr *sa_, socklen_t sa_len_) :
ws_address_t (sa_, sa_len_)
{
}
int zmq::wss_address_t::to_string (std::string &addr_) const
{
std::ostringstream os;
os << std::string ("wss://") << host () << std::string (":")
<< _address.port () << path ();
addr_ = os.str ();
return 0;
}
| 541
|
C++
|
.cpp
| 20
| 24.4
| 76
| 0.617476
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,469
|
zmq_utils.h
|
zeromq_libzmq/include/zmq_utils.h
|
/* SPDX-License-Identifier: MPL-2.0 */
/* This file is deprecated, and all its functionality provided by zmq.h */
/* Note that -Wpedantic compilation requires GCC to avoid using its custom
extensions such as #warning, hence the trick below. Also, pragmas for
warnings or other messages are not standard, not portable, and not all
compilers even have an equivalent concept.
So in the worst case, this include file is treated as silently empty. */
#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) \
|| defined(_MSC_VER)
#if defined(__GNUC__) || defined(__GNUG__)
#pragma GCC diagnostic push
#pragma GCC diagnostic warning "-Wcpp"
#pragma GCC diagnostic ignored "-Werror"
#pragma GCC diagnostic ignored "-Wall"
#endif
#pragma message( \
"Warning: zmq_utils.h is deprecated. All its functionality is provided by zmq.h.")
#if defined(__GNUC__) || defined(__GNUG__)
#pragma GCC diagnostic pop
#endif
#endif
| 1,021
|
C++
|
.h
| 21
| 46.571429
| 84
| 0.671343
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
14,472
|
testutil.hpp
|
zeromq_libzmq/tests/testutil.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __TESTUTIL_HPP_INCLUDED__
#define __TESTUTIL_HPP_INCLUDED__
#if defined ZMQ_CUSTOM_PLATFORM_HPP
#include "platform.hpp"
#else
#include "../src/platform.hpp"
#endif
#include "../include/zmq.h"
#include "../src/stdint.hpp"
// For AF_INET and IPPROTO_TCP
#if defined _WIN32
#include "../src/windows.hpp"
#if defined(__MINGW32__)
#include <unistd.h>
#endif
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#endif
// This defines the settle time used in tests; raise this if we
// get test failures on slower systems due to binds/connects not
// settled. Tested to work reliably at 1 msec on a fast PC.
#define SETTLE_TIME 300 // In msec
// Commonly used buffer size for ZMQ_LAST_ENDPOINT
// this used to be sizeof ("tcp://[::ffff:127.127.127.127]:65536"), but this
// may be too short for ipc wildcard binds, e.g.
#define MAX_SOCKET_STRING 256
// We need to test codepaths with non-random bind ports. List them here to
// keep them unique, to allow parallel test runs.
#define ENDPOINT_0 "tcp://127.0.0.1:5555"
#define ENDPOINT_1 "tcp://127.0.0.1:5556"
#define ENDPOINT_2 "tcp://127.0.0.1:5557"
#define ENDPOINT_3 "tcp://127.0.0.1:5558"
#define ENDPOINT_4 "udp://127.0.0.1:5559"
#define ENDPOINT_5 "udp://127.0.0.1:5560"
#define PORT_6 5561
// For tests that mock ZMTP
const uint8_t zmtp_greeting_null[64] = {
0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0x7f, 3, 0, 'N', 'U', 'L', 'L',
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
const uint8_t zmtp_greeting_curve[64] = {
0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0x7f, 3, 0, 'C', 'U', 'R', 'V',
'E', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
const uint8_t zmtp_ready_dealer[43] = {
4, 41, 5, 'R', 'E', 'A', 'D', 'Y', 11, 'S', 'o', 'c', 'k', 'e', 't',
'-', 'T', 'y', 'p', 'e', 0, 0, 0, 6, 'D', 'E', 'A', 'L', 'E', 'R',
8, 'I', 'd', 'e', 'n', 't', 'i', 't', 'y', 0, 0, 0, 0};
const uint8_t zmtp_ready_xpub[28] = {
4, 26, 5, 'R', 'E', 'A', 'D', 'Y', 11, 'S', 'o', 'c', 'k', 'e',
't', '-', 'T', 'y', 'p', 'e', 0, 0, 0, 4, 'X', 'P', 'U', 'B'};
const uint8_t zmtp_ready_sub[27] = {
4, 25, 5, 'R', 'E', 'A', 'D', 'Y', 11, 'S', 'o', 'c', 'k', 'e',
't', '-', 'T', 'y', 'p', 'e', 0, 0, 0, 3, 'S', 'U', 'B'};
#undef NDEBUG
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif
// duplicated from fd.hpp
#ifdef ZMQ_HAVE_WINDOWS
#ifndef NOMINMAX
#define NOMINMAX // Macros min(a,b) and max(a,b)
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdexcept>
#define close closesocket
typedef int socket_size_t;
inline const char *as_setsockopt_opt_t (const void *opt)
{
return static_cast<const char *> (opt);
}
#else
typedef size_t socket_size_t;
inline const void *as_setsockopt_opt_t (const void *opt_)
{
return opt_;
}
#endif
// duplicated from fd.hpp
typedef zmq_fd_t fd_t;
#ifdef ZMQ_HAVE_WINDOWS
#if defined _MSC_VER && _MSC_VER <= 1400
enum
{
retired_fd = (zmq_fd_t) (~0)
};
#else
enum
#if _MSC_VER >= 1800
: zmq_fd_t
#endif
{
retired_fd = INVALID_SOCKET
};
#endif
#else
enum
{
retired_fd = -1
};
#endif
// In MSVC prior to v14, snprintf is not available
// The closest implementation is the _snprintf_s function
#if defined _MSC_VER && _MSC_VER < 1900
#define snprintf(buffer_, count_, format_, ...) \
_snprintf_s (buffer_, count_, _TRUNCATE, format_, __VA_ARGS__)
#endif
#define LIBZMQ_UNUSED(object) (void) object
// Bounce a message from client to server and back
// For REQ/REP or DEALER/DEALER pairs only
void bounce (void *server_, void *client_);
// Same as bounce, but expect messages to never arrive
// for security or subscriber reasons.
void expect_bounce_fail (void *server_, void *client_);
// Receive 0MQ string from socket and convert into C string
// Caller must free returned string. Returns NULL if the context
// is being terminated.
char *s_recv (void *socket_);
bool streq (const char *lhs, const char *rhs);
bool strneq (const char *lhs, const char *rhs);
extern const char *SEQ_END;
// Sends a message composed of frames that are C strings or null frames.
// The list must be terminated by SEQ_END.
// Example: s_send_seq (req, "ABC", 0, "DEF", SEQ_END);
void s_send_seq (void *socket_, ...);
// Receives message a number of frames long and checks that the frames have
// the given data which can be either C strings or 0 for a null frame.
// The list must be terminated by SEQ_END.
// Example: s_recv_seq (rep, "ABC", 0, "DEF", SEQ_END);
void s_recv_seq (void *socket_, ...);
// Sets a zero linger period on a socket and closes it.
void close_zero_linger (void *socket_);
// Setups the test environment. Must be called at the beginning of each test
// executable. On POSIX systems, it sets an alarm to the specified number of
// seconds, after which the test will be killed. Set to 0 to disable this
// timeout.
void setup_test_environment (int timeout_seconds_ = 60);
// Provide portable millisecond sleep
// http://www.cplusplus.com/forum/unices/60161/
// http://en.cppreference.com/w/cpp/thread/sleep_for
void msleep (int milliseconds_);
// check if IPv6 is available (0/false if not, 1/true if it is)
// only way to reliably check is to actually open a socket and try to bind it
int is_ipv6_available (void);
// check if tipc is available (0/false if not, 1/true if it is)
// only way to reliably check is to actually open a socket and try to bind it
// as it depends on a non-default kernel module to be already loaded
int is_tipc_available (void);
// Wrapper around 'inet_pton' for systems that don't support it (e.g. Windows
// XP)
int test_inet_pton (int af_, const char *src_, void *dst_);
// Binds an ipv4 BSD socket to an ephemeral port, returns the compiled sockaddr
struct sockaddr_in bind_bsd_socket (int socket);
// Some custom definitions in addition to IPPROTO_TCP and IPPROTO_UDP
#define IPPROTO_WS 10000
#define IPPROTO_WSS 10001
// Connects a BSD socket to the ZMQ endpoint. Works with ipv4/ipv6/unix.
fd_t connect_socket (const char *endpoint_,
const int af_ = AF_INET,
const int protocol_ = IPPROTO_TCP);
// Binds a BSD socket to an ephemeral port, returns the file descriptor.
// The resulting ZMQ endpoint will be stored in my_endpoint, including the protocol
// prefix, so ensure it is writable and of appropriate size.
// Works with ipv4/ipv6/unix. With unix sockets address_/port_ can be empty and
// my_endpoint_ will contain a random path.
fd_t bind_socket_resolve_port (const char *address_,
const char *port_,
char *my_endpoint_,
const int af_ = AF_INET,
const int protocol_ = IPPROTO_TCP);
int fuzzer_corpus_encode (const char *filename,
uint8_t ***data,
size_t **len,
size_t *num_cases);
#endif
| 7,196
|
C++
|
.h
| 181
| 36.917127
| 84
| 0.642018
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,475
|
sha1.h
|
zeromq_libzmq/external/sha1/sha1.h
|
/* contrib/pgcrypto/sha1.h */
/* $KAME: sha1.h,v 1.4 2000/02/22 14:01:18 itojun Exp $ */
/*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS 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.
*/
/*
* FIPS pub 180-1: Secure Hash Algorithm (SHA-1)
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* based on: http://www.itl.nist.gov/fipspubs/fip180-1.htm
* implemented by Jun-ichiro itojun Itoh <itojun@itojun.org>
*/
#ifndef _NETINET6_SHA1_H_
#define _NETINET6_SHA1_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#include "../../src/stdint.hpp"
struct sha1_ctxt
{
union
{
uint8_t b8[20];
uint32_t b32[5];
} h;
union
{
uint8_t b8[8];
uint64_t b64[1];
} c;
union
{
uint8_t b8[64];
uint32_t b32[16];
} m;
uint8_t count;
};
void sha1_init(struct sha1_ctxt *);
void sha1_pad(struct sha1_ctxt *);
void sha1_loop(struct sha1_ctxt *, const uint8_t *, size_t);
void sha1_result(struct sha1_ctxt *, uint8_t *);
// Compatibility with OpenSSL API
#define SHA_DIGEST_LENGTH 20
typedef struct sha1_ctxt SHA_CTX;
#define SHA1_Init(x) sha1_init((x))
#define SHA1_Update(x, y, z) sha1_loop((x), (y), (z))
#define SHA1_Final(x, y) sha1_result((y), (x))
#define SHA1_RESULTLEN (160/8)
#ifdef __cplusplus
}
#endif
#endif /* _NETINET6_SHA1_H_ */
| 2,720
|
C++
|
.h
| 76
| 33.947368
| 77
| 0.733004
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
14,476
|
wepoll.h
|
zeromq_libzmq/external/wepoll/wepoll.h
|
/*
* wepoll - epoll for Windows
* https://github.com/piscisaureus/wepoll
*
* Copyright 2012-2020, Bert Belder <bertbelder@gmail.com>
* 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.
*
* 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 THE COPYRIGHT
* OWNER OR CONTRIBUTORS 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.
*/
#ifndef WEPOLL_H_
#define WEPOLL_H_
#ifndef WEPOLL_EXPORT
#define WEPOLL_EXPORT
#endif
#include <stdint.h>
enum EPOLL_EVENTS {
EPOLLIN = (int) (1U << 0),
EPOLLPRI = (int) (1U << 1),
EPOLLOUT = (int) (1U << 2),
EPOLLERR = (int) (1U << 3),
EPOLLHUP = (int) (1U << 4),
EPOLLRDNORM = (int) (1U << 6),
EPOLLRDBAND = (int) (1U << 7),
EPOLLWRNORM = (int) (1U << 8),
EPOLLWRBAND = (int) (1U << 9),
EPOLLMSG = (int) (1U << 10), /* Never reported. */
EPOLLRDHUP = (int) (1U << 13),
EPOLLONESHOT = (int) (1U << 31)
};
#define EPOLLIN (1U << 0)
#define EPOLLPRI (1U << 1)
#define EPOLLOUT (1U << 2)
#define EPOLLERR (1U << 3)
#define EPOLLHUP (1U << 4)
#define EPOLLRDNORM (1U << 6)
#define EPOLLRDBAND (1U << 7)
#define EPOLLWRNORM (1U << 8)
#define EPOLLWRBAND (1U << 9)
#define EPOLLMSG (1U << 10)
#define EPOLLRDHUP (1U << 13)
#define EPOLLONESHOT (1U << 31)
#define EPOLL_CTL_ADD 1
#define EPOLL_CTL_MOD 2
#define EPOLL_CTL_DEL 3
typedef void* HANDLE;
typedef uintptr_t SOCKET;
typedef union epoll_data {
void* ptr;
int fd;
uint32_t u32;
uint64_t u64;
SOCKET sock; /* Windows specific */
HANDLE hnd; /* Windows specific */
} epoll_data_t;
struct epoll_event {
uint32_t events; /* Epoll events and flags */
epoll_data_t data; /* User data variable */
};
#ifdef __cplusplus
extern "C" {
#endif
WEPOLL_EXPORT HANDLE epoll_create(int size);
WEPOLL_EXPORT HANDLE epoll_create1(int flags);
WEPOLL_EXPORT int epoll_close(HANDLE ephnd);
WEPOLL_EXPORT int epoll_ctl(HANDLE ephnd,
int op,
SOCKET sock,
struct epoll_event* event);
WEPOLL_EXPORT int epoll_wait(HANDLE ephnd,
struct epoll_event* events,
int maxevents,
int timeout);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* WEPOLL_H_ */
| 3,471
|
C++
|
.h
| 97
| 32.14433
| 75
| 0.670042
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
14,477
|
unity_internals.h
|
zeromq_libzmq/external/unity/unity_internals.h
|
/* ==========================================
Unity Project - A Test Framework for C
Copyright (c) 2007-14 Mike Karlesky, Mark VanderVoord, Greg Williams
[Released under MIT License. Please refer to license.txt for details]
========================================== */
#ifndef UNITY_INTERNALS_H
#define UNITY_INTERNALS_H
#ifdef UNITY_INCLUDE_CONFIG_H
#include "unity_config.h"
#endif
#ifndef UNITY_EXCLUDE_SETJMP_H
#include <setjmp.h>
#endif
#ifndef UNITY_EXCLUDE_MATH_H
#include <math.h>
#endif
/* Unity Attempts to Auto-Detect Integer Types
* Attempt 1: UINT_MAX, ULONG_MAX in <limits.h>, or default to 32 bits
* Attempt 2: UINTPTR_MAX in <stdint.h>, or default to same size as long
* The user may override any of these derived constants:
* UNITY_INT_WIDTH, UNITY_LONG_WIDTH, UNITY_POINTER_WIDTH */
#ifndef UNITY_EXCLUDE_STDINT_H
#include <stdint.h>
#endif
#ifndef UNITY_EXCLUDE_LIMITS_H
#include <limits.h>
#endif
/*-------------------------------------------------------
* Guess Widths If Not Specified
*-------------------------------------------------------*/
/* Determine the size of an int, if not already specified.
* We cannot use sizeof(int), because it is not yet defined
* at this stage in the translation of the C program.
* Therefore, infer it from UINT_MAX if possible. */
#ifndef UNITY_INT_WIDTH
#ifdef UINT_MAX
#if (UINT_MAX == 0xFFFF)
#define UNITY_INT_WIDTH (16)
#elif (UINT_MAX == 0xFFFFFFFF)
#define UNITY_INT_WIDTH (32)
#elif (UINT_MAX == 0xFFFFFFFFFFFFFFFF)
#define UNITY_INT_WIDTH (64)
#endif
#else /* Set to default */
#define UNITY_INT_WIDTH (32)
#endif /* UINT_MAX */
#endif
/* Determine the size of a long, if not already specified. */
#ifndef UNITY_LONG_WIDTH
#ifdef ULONG_MAX
#if (ULONG_MAX == 0xFFFF)
#define UNITY_LONG_WIDTH (16)
#elif (ULONG_MAX == 0xFFFFFFFF)
#define UNITY_LONG_WIDTH (32)
#elif (ULONG_MAX == 0xFFFFFFFFFFFFFFFF)
#define UNITY_LONG_WIDTH (64)
#endif
#else /* Set to default */
#define UNITY_LONG_WIDTH (32)
#endif /* ULONG_MAX */
#endif
/* Determine the size of a pointer, if not already specified. */
#ifndef UNITY_POINTER_WIDTH
#ifdef UINTPTR_MAX
#if (UINTPTR_MAX <= 0xFFFF)
#define UNITY_POINTER_WIDTH (16)
#elif (UINTPTR_MAX <= 0xFFFFFFFF)
#define UNITY_POINTER_WIDTH (32)
#elif (UINTPTR_MAX <= 0xFFFFFFFFFFFFFFFF)
#define UNITY_POINTER_WIDTH (64)
#endif
#else /* Set to default */
#define UNITY_POINTER_WIDTH UNITY_LONG_WIDTH
#endif /* UINTPTR_MAX */
#endif
/*-------------------------------------------------------
* Int Support (Define types based on detected sizes)
*-------------------------------------------------------*/
#if (UNITY_INT_WIDTH == 32)
typedef unsigned char UNITY_UINT8;
typedef unsigned short UNITY_UINT16;
typedef unsigned int UNITY_UINT32;
typedef signed char UNITY_INT8;
typedef signed short UNITY_INT16;
typedef signed int UNITY_INT32;
#elif (UNITY_INT_WIDTH == 16)
typedef unsigned char UNITY_UINT8;
typedef unsigned int UNITY_UINT16;
typedef unsigned long UNITY_UINT32;
typedef signed char UNITY_INT8;
typedef signed int UNITY_INT16;
typedef signed long UNITY_INT32;
#else
#error Invalid UNITY_INT_WIDTH specified! (16 or 32 are supported)
#endif
/*-------------------------------------------------------
* 64-bit Support
*-------------------------------------------------------*/
#ifndef UNITY_SUPPORT_64
#if UNITY_LONG_WIDTH == 64 || UNITY_POINTER_WIDTH == 64
#define UNITY_SUPPORT_64
#endif
#endif
#ifndef UNITY_SUPPORT_64
/* No 64-bit Support */
typedef UNITY_UINT32 UNITY_UINT;
typedef UNITY_INT32 UNITY_INT;
#else
/* 64-bit Support */
#if (UNITY_LONG_WIDTH == 32)
typedef unsigned long long UNITY_UINT64;
typedef signed long long UNITY_INT64;
#elif (UNITY_LONG_WIDTH == 64)
typedef unsigned long UNITY_UINT64;
typedef signed long UNITY_INT64;
#else
#error Invalid UNITY_LONG_WIDTH specified! (32 or 64 are supported)
#endif
typedef UNITY_UINT64 UNITY_UINT;
typedef UNITY_INT64 UNITY_INT;
#endif
/*-------------------------------------------------------
* Pointer Support
*-------------------------------------------------------*/
#if (UNITY_POINTER_WIDTH == 32)
#define UNITY_PTR_TO_INT UNITY_INT32
#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX32
#elif (UNITY_POINTER_WIDTH == 64)
#define UNITY_PTR_TO_INT UNITY_INT64
#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX64
#elif (UNITY_POINTER_WIDTH == 16)
#define UNITY_PTR_TO_INT UNITY_INT16
#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX16
#else
#error Invalid UNITY_POINTER_WIDTH specified! (16, 32 or 64 are supported)
#endif
#ifndef UNITY_PTR_ATTRIBUTE
#define UNITY_PTR_ATTRIBUTE
#endif
#ifndef UNITY_INTERNAL_PTR
#define UNITY_INTERNAL_PTR UNITY_PTR_ATTRIBUTE const void*
#endif
/*-------------------------------------------------------
* Float Support
*-------------------------------------------------------*/
#ifdef UNITY_EXCLUDE_FLOAT
/* No Floating Point Support */
#ifndef UNITY_EXCLUDE_DOUBLE
#define UNITY_EXCLUDE_DOUBLE /* Remove double when excluding float support */
#endif
#ifndef UNITY_EXCLUDE_FLOAT_PRINT
#define UNITY_EXCLUDE_FLOAT_PRINT
#endif
#else
/* Floating Point Support */
#ifndef UNITY_FLOAT_PRECISION
#define UNITY_FLOAT_PRECISION (0.00001f)
#endif
#ifndef UNITY_FLOAT_TYPE
#define UNITY_FLOAT_TYPE float
#endif
typedef UNITY_FLOAT_TYPE UNITY_FLOAT;
/* isinf & isnan macros should be provided by math.h */
#ifndef isinf
/* The value of Inf - Inf is NaN */
#define isinf(n) (isnan((n) - (n)) && !isnan(n))
#endif
#ifndef isnan
/* NaN is the only floating point value that does NOT equal itself.
* Therefore if n != n, then it is NaN. */
#define isnan(n) ((n != n) ? 1 : 0)
#endif
#endif
/*-------------------------------------------------------
* Double Float Support
*-------------------------------------------------------*/
/* unlike float, we DON'T include by default */
#if defined(UNITY_EXCLUDE_DOUBLE) || !defined(UNITY_INCLUDE_DOUBLE)
/* No Floating Point Support */
#ifndef UNITY_EXCLUDE_DOUBLE
#define UNITY_EXCLUDE_DOUBLE
#else
#undef UNITY_INCLUDE_DOUBLE
#endif
#ifndef UNITY_EXCLUDE_FLOAT
#ifndef UNITY_DOUBLE_TYPE
#define UNITY_DOUBLE_TYPE double
#endif
typedef UNITY_FLOAT UNITY_DOUBLE;
/* For parameter in UnityPrintFloat(UNITY_DOUBLE), which aliases to double or float */
#endif
#else
/* Double Floating Point Support */
#ifndef UNITY_DOUBLE_PRECISION
#define UNITY_DOUBLE_PRECISION (1e-12)
#endif
#ifndef UNITY_DOUBLE_TYPE
#define UNITY_DOUBLE_TYPE double
#endif
typedef UNITY_DOUBLE_TYPE UNITY_DOUBLE;
#endif
/*-------------------------------------------------------
* Output Method: stdout (DEFAULT)
*-------------------------------------------------------*/
#ifndef UNITY_OUTPUT_CHAR
/* Default to using putchar, which is defined in stdio.h */
#include <stdio.h>
#define UNITY_OUTPUT_CHAR(a) (void)putchar(a)
#else
/* If defined as something else, make sure we declare it here so it's ready for use */
#ifdef UNITY_OUTPUT_CHAR_HEADER_DECLARATION
extern void UNITY_OUTPUT_CHAR_HEADER_DECLARATION;
#endif
#endif
#ifndef UNITY_OUTPUT_FLUSH
#ifdef UNITY_USE_FLUSH_STDOUT
/* We want to use the stdout flush utility */
#include <stdio.h>
#define UNITY_OUTPUT_FLUSH() (void)fflush(stdout)
#else
/* We've specified nothing, therefore flush should just be ignored */
#define UNITY_OUTPUT_FLUSH()
#endif
#else
/* We've defined flush as something else, so make sure we declare it here so it's ready for use */
#ifdef UNITY_OUTPUT_FLUSH_HEADER_DECLARATION
extern void UNITY_OMIT_OUTPUT_FLUSH_HEADER_DECLARATION;
#endif
#endif
#ifndef UNITY_OUTPUT_FLUSH
#define UNITY_FLUSH_CALL()
#else
#define UNITY_FLUSH_CALL() UNITY_OUTPUT_FLUSH()
#endif
#ifndef UNITY_PRINT_EOL
#define UNITY_PRINT_EOL() UNITY_OUTPUT_CHAR('\n')
#endif
#ifndef UNITY_OUTPUT_START
#define UNITY_OUTPUT_START()
#endif
#ifndef UNITY_OUTPUT_COMPLETE
#define UNITY_OUTPUT_COMPLETE()
#endif
/*-------------------------------------------------------
* Footprint
*-------------------------------------------------------*/
#ifndef UNITY_LINE_TYPE
#define UNITY_LINE_TYPE UNITY_UINT
#endif
#ifndef UNITY_COUNTER_TYPE
#define UNITY_COUNTER_TYPE UNITY_UINT
#endif
/*-------------------------------------------------------
* Language Features Available
*-------------------------------------------------------*/
#if !defined(UNITY_WEAK_ATTRIBUTE) && !defined(UNITY_WEAK_PRAGMA)
# if defined(__GNUC__) || defined(__ghs__) /* __GNUC__ includes clang */
# if !(defined(__WIN32__) && defined(__clang__)) && !defined(__TMS470__)
# define UNITY_WEAK_ATTRIBUTE __attribute__((weak))
# endif
# endif
#endif
#ifdef UNITY_NO_WEAK
# undef UNITY_WEAK_ATTRIBUTE
# undef UNITY_WEAK_PRAGMA
#endif
/*-------------------------------------------------------
* Internal Structs Needed
*-------------------------------------------------------*/
typedef void (*UnityTestFunction)(void);
#define UNITY_DISPLAY_RANGE_INT (0x10)
#define UNITY_DISPLAY_RANGE_UINT (0x20)
#define UNITY_DISPLAY_RANGE_HEX (0x40)
typedef enum
{
UNITY_DISPLAY_STYLE_INT = sizeof(int)+ UNITY_DISPLAY_RANGE_INT,
UNITY_DISPLAY_STYLE_INT8 = 1 + UNITY_DISPLAY_RANGE_INT,
UNITY_DISPLAY_STYLE_INT16 = 2 + UNITY_DISPLAY_RANGE_INT,
UNITY_DISPLAY_STYLE_INT32 = 4 + UNITY_DISPLAY_RANGE_INT,
#ifdef UNITY_SUPPORT_64
UNITY_DISPLAY_STYLE_INT64 = 8 + UNITY_DISPLAY_RANGE_INT,
#endif
UNITY_DISPLAY_STYLE_UINT = sizeof(unsigned) + UNITY_DISPLAY_RANGE_UINT,
UNITY_DISPLAY_STYLE_UINT8 = 1 + UNITY_DISPLAY_RANGE_UINT,
UNITY_DISPLAY_STYLE_UINT16 = 2 + UNITY_DISPLAY_RANGE_UINT,
UNITY_DISPLAY_STYLE_UINT32 = 4 + UNITY_DISPLAY_RANGE_UINT,
#ifdef UNITY_SUPPORT_64
UNITY_DISPLAY_STYLE_UINT64 = 8 + UNITY_DISPLAY_RANGE_UINT,
#endif
UNITY_DISPLAY_STYLE_HEX8 = 1 + UNITY_DISPLAY_RANGE_HEX,
UNITY_DISPLAY_STYLE_HEX16 = 2 + UNITY_DISPLAY_RANGE_HEX,
UNITY_DISPLAY_STYLE_HEX32 = 4 + UNITY_DISPLAY_RANGE_HEX,
#ifdef UNITY_SUPPORT_64
UNITY_DISPLAY_STYLE_HEX64 = 8 + UNITY_DISPLAY_RANGE_HEX,
#endif
UNITY_DISPLAY_STYLE_UNKNOWN
} UNITY_DISPLAY_STYLE_T;
typedef enum
{
UNITY_EQUAL_TO = 1,
UNITY_GREATER_THAN = 2,
UNITY_GREATER_OR_EQUAL = 2 + UNITY_EQUAL_TO,
UNITY_SMALLER_THAN = 4,
UNITY_SMALLER_OR_EQUAL = 4 + UNITY_EQUAL_TO
} UNITY_COMPARISON_T;
#ifndef UNITY_EXCLUDE_FLOAT
typedef enum UNITY_FLOAT_TRAIT
{
UNITY_FLOAT_IS_NOT_INF = 0,
UNITY_FLOAT_IS_INF,
UNITY_FLOAT_IS_NOT_NEG_INF,
UNITY_FLOAT_IS_NEG_INF,
UNITY_FLOAT_IS_NOT_NAN,
UNITY_FLOAT_IS_NAN,
UNITY_FLOAT_IS_NOT_DET,
UNITY_FLOAT_IS_DET,
UNITY_FLOAT_INVALID_TRAIT
} UNITY_FLOAT_TRAIT_T;
#endif
typedef enum
{
UNITY_ARRAY_TO_VAL = 0,
UNITY_ARRAY_TO_ARRAY
} UNITY_FLAGS_T;
struct UNITY_STORAGE_T
{
const char* TestFile;
const char* CurrentTestName;
#ifndef UNITY_EXCLUDE_DETAILS
const char* CurrentDetail1;
const char* CurrentDetail2;
#endif
UNITY_LINE_TYPE CurrentTestLineNumber;
UNITY_COUNTER_TYPE NumberOfTests;
UNITY_COUNTER_TYPE TestFailures;
UNITY_COUNTER_TYPE TestIgnores;
UNITY_COUNTER_TYPE CurrentTestFailed;
UNITY_COUNTER_TYPE CurrentTestIgnored;
#ifndef UNITY_EXCLUDE_SETJMP_H
jmp_buf AbortFrame;
#endif
};
extern struct UNITY_STORAGE_T Unity;
/*-------------------------------------------------------
* Test Suite Management
*-------------------------------------------------------*/
void UnityBegin(const char* filename);
int UnityEnd(void);
void UnityConcludeTest(void);
void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum);
/*-------------------------------------------------------
* Details Support
*-------------------------------------------------------*/
#ifdef UNITY_EXCLUDE_DETAILS
#define UNITY_CLR_DETAILS()
#define UNITY_SET_DETAIL(d1)
#define UNITY_SET_DETAILS(d1,d2)
#else
#define UNITY_CLR_DETAILS() { Unity.CurrentDetail1 = 0; Unity.CurrentDetail2 = 0; }
#define UNITY_SET_DETAIL(d1) { Unity.CurrentDetail1 = d1; Unity.CurrentDetail2 = 0; }
#define UNITY_SET_DETAILS(d1,d2) { Unity.CurrentDetail1 = d1; Unity.CurrentDetail2 = d2; }
#ifndef UNITY_DETAIL1_NAME
#define UNITY_DETAIL1_NAME "Function"
#endif
#ifndef UNITY_DETAIL2_NAME
#define UNITY_DETAIL2_NAME "Argument"
#endif
#endif
/*-------------------------------------------------------
* Test Output
*-------------------------------------------------------*/
void UnityPrint(const char* string);
void UnityPrintLen(const char* string, const UNITY_UINT32 length);
void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number);
void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style);
void UnityPrintNumber(const UNITY_INT number);
void UnityPrintNumberUnsigned(const UNITY_UINT number);
void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles);
#ifndef UNITY_EXCLUDE_FLOAT_PRINT
void UnityPrintFloat(const UNITY_DOUBLE input_number);
#endif
/*-------------------------------------------------------
* Test Assertion Functions
*-------------------------------------------------------
* Use the macros below this section instead of calling
* these directly. The macros have a consistent naming
* convention and will pull in file and line information
* for you. */
void UnityAssertEqualNumber(const UNITY_INT expected,
const UNITY_INT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style);
void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold,
const UNITY_INT actual,
const UNITY_COMPARISON_T compare,
const char *msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style);
void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected,
UNITY_INTERNAL_PTR actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style,
const UNITY_FLAGS_T flags);
void UnityAssertBits(const UNITY_INT mask,
const UNITY_INT expected,
const UNITY_INT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber);
void UnityAssertEqualString(const char* expected,
const char* actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber);
void UnityAssertEqualStringLen(const char* expected,
const char* actual,
const UNITY_UINT32 length,
const char* msg,
const UNITY_LINE_TYPE lineNumber);
void UnityAssertEqualStringArray( UNITY_INTERNAL_PTR expected,
const char** actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLAGS_T flags);
void UnityAssertEqualMemory( UNITY_INTERNAL_PTR expected,
UNITY_INTERNAL_PTR actual,
const UNITY_UINT32 length,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLAGS_T flags);
void UnityAssertNumbersWithin(const UNITY_UINT delta,
const UNITY_INT expected,
const UNITY_INT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style);
void UnityFail(const char* message, const UNITY_LINE_TYPE line);
void UnityIgnore(const char* message, const UNITY_LINE_TYPE line);
#ifndef UNITY_EXCLUDE_FLOAT
void UnityAssertFloatsWithin(const UNITY_FLOAT delta,
const UNITY_FLOAT expected,
const UNITY_FLOAT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber);
void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected,
UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLAGS_T flags);
void UnityAssertFloatSpecial(const UNITY_FLOAT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLOAT_TRAIT_T style);
#endif
#ifndef UNITY_EXCLUDE_DOUBLE
void UnityAssertDoublesWithin(const UNITY_DOUBLE delta,
const UNITY_DOUBLE expected,
const UNITY_DOUBLE actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber);
void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected,
UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLAGS_T flags);
void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLOAT_TRAIT_T style);
#endif
/*-------------------------------------------------------
* Helpers
*-------------------------------------------------------*/
UNITY_INTERNAL_PTR UnityNumToPtr(const UNITY_INT num, const UNITY_UINT8 size);
#ifndef UNITY_EXCLUDE_FLOAT
UNITY_INTERNAL_PTR UnityFloatToPtr(const float num);
#endif
#ifndef UNITY_EXCLUDE_DOUBLE
UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num);
#endif
/*-------------------------------------------------------
* Error Strings We Might Need
*-------------------------------------------------------*/
extern const char UnityStrErrFloat[];
extern const char UnityStrErrDouble[];
extern const char UnityStrErr64[];
/*-------------------------------------------------------
* Test Running Macros
*-------------------------------------------------------*/
#ifndef UNITY_EXCLUDE_SETJMP_H
#define TEST_PROTECT() (setjmp(Unity.AbortFrame) == 0)
#define TEST_ABORT() longjmp(Unity.AbortFrame, 1)
#else
#define TEST_PROTECT() 1
#define TEST_ABORT() return
#endif
/* This tricky series of macros gives us an optional line argument to treat it as RUN_TEST(func, num=__LINE__) */
#ifndef RUN_TEST
#ifdef __STDC_VERSION__
#if __STDC_VERSION__ >= 199901L
#define RUN_TEST(...) UnityDefaultTestRun(RUN_TEST_FIRST(__VA_ARGS__), RUN_TEST_SECOND(__VA_ARGS__))
#define RUN_TEST_FIRST(...) RUN_TEST_FIRST_HELPER(__VA_ARGS__, throwaway)
#define RUN_TEST_FIRST_HELPER(first, ...) (first), #first
#define RUN_TEST_SECOND(...) RUN_TEST_SECOND_HELPER(__VA_ARGS__, __LINE__, throwaway)
#define RUN_TEST_SECOND_HELPER(first, second, ...) (second)
#endif
#endif
#endif
/* If we can't do the tricky version, we'll just have to require them to always include the line number */
#ifndef RUN_TEST
#ifdef CMOCK
#define RUN_TEST(func, num) UnityDefaultTestRun(func, #func, num)
#else
#define RUN_TEST(func) UnityDefaultTestRun(func, #func, __LINE__)
#endif
#endif
#define TEST_LINE_NUM (Unity.CurrentTestLineNumber)
#define TEST_IS_IGNORED (Unity.CurrentTestIgnored)
#define UNITY_NEW_TEST(a) \
Unity.CurrentTestName = (a); \
Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)(__LINE__); \
Unity.NumberOfTests++;
#ifndef UNITY_BEGIN
#define UNITY_BEGIN() UnityBegin(__FILE__)
#endif
#ifndef UNITY_END
#define UNITY_END() UnityEnd()
#endif
/*-----------------------------------------------
* Command Line Argument Support
*-----------------------------------------------*/
#ifdef UNITY_USE_COMMAND_LINE_ARGS
int UnityParseOptions(int argc, char** argv);
int UnityTestMatches(void);
#endif
/*-------------------------------------------------------
* Basic Fail and Ignore
*-------------------------------------------------------*/
#define UNITY_TEST_FAIL(line, message) UnityFail( (message), (UNITY_LINE_TYPE)(line))
#define UNITY_TEST_IGNORE(line, message) UnityIgnore( (message), (UNITY_LINE_TYPE)(line))
/*-------------------------------------------------------
* Test Asserts
*-------------------------------------------------------*/
#define UNITY_TEST_ASSERT(condition, line, message) if (condition) {} else {UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), (message));}
#define UNITY_TEST_ASSERT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) == NULL), (UNITY_LINE_TYPE)(line), (message))
#define UNITY_TEST_ASSERT_NOT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) != NULL), (UNITY_LINE_TYPE)(line), (message))
#define UNITY_TEST_ASSERT_EQUAL_INT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT)
#define UNITY_TEST_ASSERT_EQUAL_INT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8)
#define UNITY_TEST_ASSERT_EQUAL_INT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16)
#define UNITY_TEST_ASSERT_EQUAL_INT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32)
#define UNITY_TEST_ASSERT_EQUAL_UINT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT)
#define UNITY_TEST_ASSERT_EQUAL_UINT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8)
#define UNITY_TEST_ASSERT_EQUAL_UINT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16)
#define UNITY_TEST_ASSERT_EQUAL_UINT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32)
#define UNITY_TEST_ASSERT_EQUAL_HEX8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8)
#define UNITY_TEST_ASSERT_EQUAL_HEX16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16)
#define UNITY_TEST_ASSERT_EQUAL_HEX32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32)
#define UNITY_TEST_ASSERT_BITS(mask, expected, actual, line, message) UnityAssertBits((UNITY_INT)(mask), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line))
#define UNITY_TEST_ASSERT_GREATER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT)
#define UNITY_TEST_ASSERT_GREATER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8)
#define UNITY_TEST_ASSERT_GREATER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16)
#define UNITY_TEST_ASSERT_GREATER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32)
#define UNITY_TEST_ASSERT_GREATER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT)
#define UNITY_TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8)
#define UNITY_TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16)
#define UNITY_TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32)
#define UNITY_TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8)
#define UNITY_TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16)
#define UNITY_TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32)
#define UNITY_TEST_ASSERT_SMALLER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT)
#define UNITY_TEST_ASSERT_SMALLER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8)
#define UNITY_TEST_ASSERT_SMALLER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16)
#define UNITY_TEST_ASSERT_SMALLER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32)
#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT)
#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8)
#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16)
#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32)
#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8)
#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16)
#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32)
#define UNITY_TEST_ASSERT_INT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT)
#define UNITY_TEST_ASSERT_INT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8)
#define UNITY_TEST_ASSERT_INT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16)
#define UNITY_TEST_ASSERT_INT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32)
#define UNITY_TEST_ASSERT_UINT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT)
#define UNITY_TEST_ASSERT_UINT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8)
#define UNITY_TEST_ASSERT_UINT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16)
#define UNITY_TEST_ASSERT_UINT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32)
#define UNITY_TEST_ASSERT_HEX8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8)
#define UNITY_TEST_ASSERT_HEX16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16)
#define UNITY_TEST_ASSERT_HEX32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32)
#define UNITY_TEST_ASSERT_EQUAL_PTR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_PTR_TO_INT)(expected), (UNITY_PTR_TO_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER)
#define UNITY_TEST_ASSERT_EQUAL_STRING(expected, actual, line, message) UnityAssertEqualString((const char*)(expected), (const char*)(actual), (message), (UNITY_LINE_TYPE)(line))
#define UNITY_TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len, line, message) UnityAssertEqualStringLen((const char*)(expected), (const char*)(actual), (UNITY_UINT32)(len), (message), (UNITY_LINE_TYPE)(line))
#define UNITY_TEST_ASSERT_EQUAL_MEMORY(expected, actual, len, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), 1, (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) expected, sizeof(int)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )expected, 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )expected, 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )expected, 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) expected, sizeof(unsigned int)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT8 )expected, 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT16)expected, 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT32)expected, 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )expected, 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )expected, 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )expected, 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_PTR_TO_INT) expected, sizeof(int*)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL)
#ifdef UNITY_SUPPORT_64
#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64)
#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64)
#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64)
#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)expected, 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT64)expected, 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)expected, 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64)
#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64)
#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64)
#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64)
#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64)
#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64)
#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64)
#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64)
#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64)
#else
#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#endif
#ifdef UNITY_EXCLUDE_FLOAT
#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#else
#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UnityAssertFloatsWithin((UNITY_FLOAT)(delta), (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line))
#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((UNITY_FLOAT)(expected) * (UNITY_FLOAT)UNITY_FLOAT_PRECISION, (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (UNITY_LINE_TYPE)(line), (message))
#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray((UNITY_FLOAT*)(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray(UnityFloatToPtr(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF)
#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF)
#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN)
#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET)
#endif
#ifdef UNITY_EXCLUDE_DOUBLE
#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#else
#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UnityAssertDoublesWithin((UNITY_DOUBLE)(delta), (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)line)
#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((UNITY_DOUBLE)(expected) * (UNITY_DOUBLE)UNITY_DOUBLE_PRECISION, (UNITY_DOUBLE)expected, (UNITY_DOUBLE)actual, (UNITY_LINE_TYPE)(line), message)
#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray((UNITY_DOUBLE*)(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)line, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray(UnityDoubleToPtr(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)line, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN)
#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET)
#endif
/* End of UNITY_INTERNALS_H */
#endif
| 69,577
|
C++
|
.h
| 754
| 87.72679
| 338
| 0.679499
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
14,478
|
unity.h
|
zeromq_libzmq/external/unity/unity.h
|
/* ==========================================
Unity Project - A Test Framework for C
Copyright (c) 2007-14 Mike Karlesky, Mark VanderVoord, Greg Williams
[Released under MIT License. Please refer to license.txt for details]
========================================== */
#ifndef UNITY_FRAMEWORK_H
#define UNITY_FRAMEWORK_H
#define UNITY
#ifdef __cplusplus
extern "C"
{
#endif
#include "unity_internals.h"
/*-------------------------------------------------------
* Test Setup / Teardown
*-------------------------------------------------------*/
/* These functions are intended to be called before and after each test. */
void setUp(void);
void tearDown(void);
/* These functions are intended to be called at the beginning and end of an
* entire test suite. suiteTearDown() is passed the number of tests that
* failed, and its return value becomes the exit code of main(). */
void suiteSetUp(void);
int suiteTearDown(int num_failures);
/* If the compiler supports it, the following block provides stub
* implementations of the above functions as weak symbols. Note that on
* some platforms (MinGW for example), weak function implementations need
* to be in the same translation unit they are called from. This can be
* achieved by defining UNITY_INCLUDE_SETUP_STUBS before including unity.h. */
#ifdef UNITY_INCLUDE_SETUP_STUBS
#ifdef UNITY_WEAK_ATTRIBUTE
UNITY_WEAK_ATTRIBUTE void setUp(void) { }
UNITY_WEAK_ATTRIBUTE void tearDown(void) { }
UNITY_WEAK_ATTRIBUTE void suiteSetUp(void) { }
UNITY_WEAK_ATTRIBUTE int suiteTearDown(int num_failures) { return num_failures; }
#elif defined(UNITY_WEAK_PRAGMA)
#pragma weak setUp
void setUp(void) { }
#pragma weak tearDown
void tearDown(void) { }
#pragma weak suiteSetUp
void suiteSetUp(void) { }
#pragma weak suiteTearDown
int suiteTearDown(int num_failures) { return num_failures; }
#endif
#endif
/*-------------------------------------------------------
* Configuration Options
*-------------------------------------------------------
* All options described below should be passed as a compiler flag to all files using Unity. If you must add #defines, place them BEFORE the #include above.
* Integers/longs/pointers
* - Unity attempts to automatically discover your integer sizes
* - define UNITY_EXCLUDE_STDINT_H to stop attempting to look in <stdint.h>
* - define UNITY_EXCLUDE_LIMITS_H to stop attempting to look in <limits.h>
* - If you cannot use the automatic methods above, you can force Unity by using these options:
* - define UNITY_SUPPORT_64
* - set UNITY_INT_WIDTH
* - set UNITY_LONG_WIDTH
* - set UNITY_POINTER_WIDTH
* Floats
* - define UNITY_EXCLUDE_FLOAT to disallow floating point comparisons
* - define UNITY_FLOAT_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_FLOAT
* - define UNITY_FLOAT_TYPE to specify doubles instead of single precision floats
* - define UNITY_INCLUDE_DOUBLE to allow double floating point comparisons
* - define UNITY_EXCLUDE_DOUBLE to disallow double floating point comparisons (default)
* - define UNITY_DOUBLE_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_DOUBLE
* - define UNITY_DOUBLE_TYPE to specify something other than double
* - define UNITY_EXCLUDE_FLOAT_PRINT to trim binary size, won't print floating point values in errors
* Output
* - by default, Unity prints to standard out with putchar. define UNITY_OUTPUT_CHAR(a) with a different function if desired
* - define UNITY_DIFFERENTIATE_FINAL_FAIL to print FAILED (vs. FAIL) at test end summary - for automated search for failure
* Optimization
* - by default, line numbers are stored in unsigned shorts. Define UNITY_LINE_TYPE with a different type if your files are huge
* - by default, test and failure counters are unsigned shorts. Define UNITY_COUNTER_TYPE with a different type if you want to save space or have more than 65535 Tests.
* Test Cases
* - define UNITY_SUPPORT_TEST_CASES to include the TEST_CASE macro, though really it's mostly about the runner generator script
* Parameterized Tests
* - you'll want to create a define of TEST_CASE(...) which basically evaluates to nothing
* Tests with Arguments
* - you'll want to define UNITY_USE_COMMAND_LINE_ARGS if you have the test runner passing arguments to Unity
*-------------------------------------------------------
* Basic Fail and Ignore
*-------------------------------------------------------*/
#define TEST_FAIL_MESSAGE(message) UNITY_TEST_FAIL(__LINE__, (message))
#define TEST_FAIL() UNITY_TEST_FAIL(__LINE__, NULL)
#define TEST_IGNORE_MESSAGE(message) UNITY_TEST_IGNORE(__LINE__, (message))
#define TEST_IGNORE() UNITY_TEST_IGNORE(__LINE__, NULL)
#define TEST_ONLY()
/* It is not necessary for you to call PASS. A PASS condition is assumed if nothing fails.
* This method allows you to abort a test immediately with a PASS state, ignoring the remainder of the test. */
#define TEST_PASS() TEST_ABORT()
/* This macro does nothing, but it is useful for build tools (like Ceedling) to make use of this to figure out
* which files should be linked to in order to perform a test. Use it like TEST_FILE("sandwiches.c") */
#define TEST_FILE(a)
/*-------------------------------------------------------
* Test Asserts (simple)
*-------------------------------------------------------*/
/* Boolean */
#define TEST_ASSERT(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expression Evaluated To FALSE")
#define TEST_ASSERT_TRUE(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expected TRUE Was FALSE")
#define TEST_ASSERT_UNLESS(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expression Evaluated To TRUE")
#define TEST_ASSERT_FALSE(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expected FALSE Was TRUE")
#define TEST_ASSERT_NULL(pointer) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, " Expected NULL")
#define TEST_ASSERT_NOT_NULL(pointer) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, " Expected Non-NULL")
/* Integers (of all sizes) */
#define TEST_ASSERT_EQUAL_INT(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal")
#define TEST_ASSERT_EQUAL_UINT(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX8(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX16(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX32(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX64(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_BITS(mask, expected, actual) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_BITS_HIGH(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, NULL)
#define TEST_ASSERT_BITS_LOW(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, NULL)
#define TEST_ASSERT_BIT_HIGH(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), (actual), __LINE__, NULL)
#define TEST_ASSERT_BIT_LOW(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), (actual), __LINE__, NULL)
/* Integer Greater Than/ Less Than (of all sizes) */
#define TEST_ASSERT_GREATER_THAN(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL)
/* Integer Ranges (of all sizes) */
#define TEST_ASSERT_INT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_INT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_INT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_INT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_INT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_UINT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_UINT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_UINT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_UINT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_UINT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_HEX_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_HEX8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_HEX16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_HEX32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_HEX64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, NULL)
/* Structs and Strings */
#define TEST_ASSERT_EQUAL_PTR(expected, actual) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_STRING(expected, actual) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_MEMORY(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, NULL)
/* Arrays */
#define TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, NULL)
/* Arrays Compared To Single Value */
#define TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_HEX(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, NULL)
/* Floating Point (If Enabled) */
#define TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_FLOAT(expected, actual) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_NOT_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, NULL)
/* Double (If Enabled) */
#define TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_DOUBLE(expected, actual) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_NOT_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, NULL)
/*-------------------------------------------------------
* Test Asserts (with additional messages)
*-------------------------------------------------------*/
/* Boolean */
#define TEST_ASSERT_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message))
#define TEST_ASSERT_TRUE_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message))
#define TEST_ASSERT_UNLESS_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message))
#define TEST_ASSERT_FALSE_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message))
#define TEST_ASSERT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, (message))
#define TEST_ASSERT_NOT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, (message))
/* Integers (of all sizes) */
#define TEST_ASSERT_EQUAL_INT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_BITS_MESSAGE(mask, expected, actual, message) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_BITS_HIGH_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, (message))
#define TEST_ASSERT_BITS_LOW_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, (message))
#define TEST_ASSERT_BIT_HIGH_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), (actual), __LINE__, (message))
#define TEST_ASSERT_BIT_LOW_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), (actual), __LINE__, (message))
/* Integer Greater Than/ Less Than (of all sizes) */
#define TEST_ASSERT_GREATER_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, (message))
/* Integer Ranges (of all sizes) */
#define TEST_ASSERT_INT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_INT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_INT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_INT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_INT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_UINT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_UINT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_UINT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_UINT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_UINT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_HEX_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_HEX8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_HEX16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_HEX32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_HEX64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, (message))
/* Structs and Strings */
#define TEST_ASSERT_EQUAL_PTR_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_STRING_LEN_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, (message))
#define TEST_ASSERT_EQUAL_MEMORY_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, (message))
/* Arrays */
#define TEST_ASSERT_EQUAL_INT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_PTR_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_STRING_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_MEMORY_ARRAY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, (message))
/* Arrays Compared To Single Value*/
#define TEST_ASSERT_EACH_EQUAL_INT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_INT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_INT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_INT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_INT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_UINT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_UINT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_UINT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_UINT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_UINT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_HEX_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_HEX8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_HEX16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_HEX32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_HEX64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_PTR_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_STRING_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_MEMORY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, (message))
/* Floating Point (If Enabled) */
#define TEST_ASSERT_FLOAT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_FLOAT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_FLOAT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_FLOAT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, (message))
/* Double (If Enabled) */
#define TEST_ASSERT_DOUBLE_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_DOUBLE_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_DOUBLE_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, (message))
/* end of UNITY_FRAMEWORK_H */
#ifdef __cplusplus
}
#endif
#endif
| 66,485
|
C++
|
.h
| 457
| 144.126915
| 201
| 0.608727
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
14,485
|
macros.hpp
|
zeromq_libzmq/src/macros.hpp
|
/******************************************************************************/
/* 0MQ Internal Use */
/******************************************************************************/
#define LIBZMQ_UNUSED(object) (void) object
#define LIBZMQ_DELETE(p_object) \
{ \
delete p_object; \
p_object = 0; \
}
/******************************************************************************/
#if !defined ZMQ_NOEXCEPT
#if defined ZMQ_HAVE_NOEXCEPT
#define ZMQ_NOEXCEPT noexcept
#else
#define ZMQ_NOEXCEPT
#endif
#endif
#if !defined ZMQ_OVERRIDE
#if defined ZMQ_HAVE_NOEXCEPT
#define ZMQ_OVERRIDE override
#else
#define ZMQ_OVERRIDE
#endif
#endif
#if !defined ZMQ_FINAL
#if defined ZMQ_HAVE_NOEXCEPT
#define ZMQ_FINAL final
#else
#define ZMQ_FINAL
#endif
#endif
#if !defined ZMQ_DEFAULT
#if defined ZMQ_HAVE_NOEXCEPT
#define ZMQ_DEFAULT = default;
#else
#define ZMQ_DEFAULT \
{ \
}
#endif
#endif
#if !defined ZMQ_NON_COPYABLE_NOR_MOVABLE
#if defined ZMQ_HAVE_NOEXCEPT
#define ZMQ_NON_COPYABLE_NOR_MOVABLE(classname) \
public: \
classname (const classname &) = delete; \
classname &operator= (const classname &) = delete; \
classname (classname &&) = delete; \
classname &operator= (classname &&) = delete;
#else
#define ZMQ_NON_COPYABLE_NOR_MOVABLE(classname) \
private: \
classname (const classname &); \
classname &operator= (const classname &);
#endif
#endif
| 2,185
|
C++
|
.h
| 55
| 37.490909
| 80
| 0.384543
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| true
| true
| false
|
14,489
|
ws_encoder.hpp
|
zeromq_libzmq/src/ws_encoder.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_WS_ENCODER_HPP_INCLUDED__
#define __ZMQ_WS_ENCODER_HPP_INCLUDED__
#include "encoder.hpp"
namespace zmq
{
// Encoder for web socket framing protocol. Converts messages into data stream.
class ws_encoder_t ZMQ_FINAL : public encoder_base_t<ws_encoder_t>
{
public:
ws_encoder_t (size_t bufsize_, bool must_mask_);
~ws_encoder_t ();
private:
void size_ready ();
void message_ready ();
unsigned char _tmp_buf[16];
bool _must_mask;
unsigned char _mask[4];
msg_t _masked_msg;
bool _is_binary;
ZMQ_NON_COPYABLE_NOR_MOVABLE (ws_encoder_t)
};
}
#endif
| 648
|
C++
|
.h
| 24
| 23.833333
| 80
| 0.693182
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,507
|
array.hpp
|
zeromq_libzmq/src/array.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_ARRAY_INCLUDED__
#define __ZMQ_ARRAY_INCLUDED__
#include <vector>
#include <algorithm>
#include "macros.hpp"
namespace zmq
{
// Implementation of fast arrays with O(1) access, insertion and
// removal. The array stores pointers rather than objects.
// O(1) is achieved by making items inheriting from
// array_item_t<ID> class which internally stores the position
// in the array.
// The ID template argument is used to differentiate among arrays
// and thus let an object be stored in different arrays.
// Base class for objects stored in the array. If you want to store
// same object in multiple arrays, each of those arrays has to have
// different ID. The item itself has to be derived from instantiations of
// array_item_t template for all relevant IDs.
template <int ID = 0> class array_item_t
{
public:
array_item_t () : _array_index (-1) {}
// The destructor doesn't have to be virtual. It is made virtual
// just to keep ICC and code checking tools from complaining.
virtual ~array_item_t () ZMQ_DEFAULT;
void set_array_index (int index_) { _array_index = index_; }
int get_array_index () const { return _array_index; }
private:
int _array_index;
ZMQ_NON_COPYABLE_NOR_MOVABLE (array_item_t)
};
template <typename T, int ID = 0> class array_t
{
private:
typedef array_item_t<ID> item_t;
public:
typedef typename std::vector<T *>::size_type size_type;
array_t () ZMQ_DEFAULT;
size_type size () { return _items.size (); }
bool empty () { return _items.empty (); }
T *&operator[] (size_type index_) { return _items[index_]; }
void push_back (T *item_)
{
if (item_)
static_cast<item_t *> (item_)->set_array_index (
static_cast<int> (_items.size ()));
_items.push_back (item_);
}
void erase (T *item_)
{
erase (static_cast<item_t *> (item_)->get_array_index ());
}
void erase (size_type index_)
{
if (_items.empty ())
return;
static_cast<item_t *> (_items.back ())
->set_array_index (static_cast<int> (index_));
_items[index_] = _items.back ();
_items.pop_back ();
}
void swap (size_type index1_, size_type index2_)
{
if (_items[index1_])
static_cast<item_t *> (_items[index1_])
->set_array_index (static_cast<int> (index2_));
if (_items[index2_])
static_cast<item_t *> (_items[index2_])
->set_array_index (static_cast<int> (index1_));
std::swap (_items[index1_], _items[index2_]);
}
void clear () { _items.clear (); }
static size_type index (T *item_)
{
return static_cast<size_type> (
static_cast<item_t *> (item_)->get_array_index ());
}
private:
typedef std::vector<T *> items_t;
items_t _items;
ZMQ_NON_COPYABLE_NOR_MOVABLE (array_t)
};
}
#endif
| 2,990
|
C++
|
.h
| 85
| 29.847059
| 74
| 0.623914
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,508
|
compat.hpp
|
zeromq_libzmq/src/compat.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_COMPAT_HPP_INCLUDED__
#define __ZMQ_COMPAT_HPP_INCLUDED__
#include "precompiled.hpp"
#include <string.h>
#ifdef ZMQ_HAVE_WINDOWS
#define strcasecmp _stricmp
#define strtok_r strtok_s
#else
#ifndef ZMQ_HAVE_STRLCPY
#ifdef ZMQ_HAVE_LIBBSD
#include <bsd/string.h>
#else
static inline size_t
strlcpy (char *dest_, const char *src_, const size_t dest_size_)
{
size_t remain = dest_size_;
for (; remain && *src_; --remain, ++src_, ++dest_) {
*dest_ = *src_;
}
return dest_size_ - remain;
}
#endif
#endif
template <size_t size>
static inline int strcpy_s (char (&dest_)[size], const char *const src_)
{
const size_t res = strlcpy (dest_, src_, size);
return res >= size ? ERANGE : 0;
}
#endif
#ifndef HAVE_STRNLEN
static inline size_t strnlen (const char *s, size_t len)
{
for (size_t i = 0; i < len; i++) {
if (s[i] == '\0')
return i + 1;
}
return len;
}
#endif
#endif
| 986
|
C++
|
.h
| 42
| 20.809524
| 72
| 0.651386
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,512
|
vmci_connecter.hpp
|
zeromq_libzmq/src/vmci_connecter.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_VMCI_CONNECTER_HPP_INCLUDED__
#define __ZMQ_VMCI_CONNECTER_HPP_INCLUDED__
#include "platform.hpp"
#if defined ZMQ_HAVE_VMCI
#include "fd.hpp"
#include "own.hpp"
#include "stdint.hpp"
#include "io_object.hpp"
#include "stream_connecter_base.hpp"
namespace zmq
{
class io_thread_t;
class session_base_t;
struct address_t;
class vmci_connecter_t ZMQ_FINAL : public stream_connecter_base_t
{
public:
// If 'delayed_start' is true connecter first waits for a while,
// then starts connection process.
vmci_connecter_t (zmq::io_thread_t *io_thread_,
zmq::session_base_t *session_,
const options_t &options_,
address_t *addr_,
bool delayed_start_);
~vmci_connecter_t ();
protected:
std::string get_socket_name (fd_t fd_, socket_end_t socket_end_) const;
private:
// ID of the timer used to check the connect timeout, must be different from stream_connecter_base_t::reconnect_timer_id.
enum
{
connect_timer_id = 2
};
// Handlers for incoming commands.
void process_term (int linger_);
// Handlers for I/O events.
void in_event ();
void out_event ();
void timer_event (int id_);
// Internal function to start the actual connection establishment.
void start_connecting ();
// Internal function to add a connect timer
void add_connect_timer ();
// Internal function to return a reconnect backoff delay.
// Will modify the current_reconnect_ivl used for next call
// Returns the currently used interval
int get_new_reconnect_ivl ();
// Open VMCI connecting socket. Returns -1 in case of error,
// 0 if connect was successful immediately. Returns -1 with
// EAGAIN errno if async connect was launched.
int open ();
// Get the file descriptor of newly created connection. Returns
// retired_fd if the connection was unsuccessful.
fd_t connect ();
// True iff a timer has been started.
bool _connect_timer_started;
ZMQ_NON_COPYABLE_NOR_MOVABLE (vmci_connecter_t)
};
}
#endif
#endif
| 2,189
|
C++
|
.h
| 62
| 30.225806
| 126
| 0.675522
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,516
|
peer.hpp
|
zeromq_libzmq/src/peer.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_PEER_HPP_INCLUDED__
#define __ZMQ_PEER_HPP_INCLUDED__
#include <map>
#include "socket_base.hpp"
#include "server.hpp"
#include "session_base.hpp"
#include "stdint.hpp"
#include "blob.hpp"
#include "fq.hpp"
namespace zmq
{
class ctx_t;
class msg_t;
class pipe_t;
class peer_t ZMQ_FINAL : public server_t
{
public:
peer_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_);
// Overrides of functions from socket_base_t.
void xattach_pipe (zmq::pipe_t *pipe_,
bool subscribe_to_all_,
bool locally_initiated_);
uint32_t connect_peer (const char *endpoint_uri_);
private:
uint32_t _peer_last_routing_id;
ZMQ_NON_COPYABLE_NOR_MOVABLE (peer_t)
};
}
#endif
| 783
|
C++
|
.h
| 30
| 22.3
| 58
| 0.66891
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,520
|
polling_util.hpp
|
zeromq_libzmq/src/polling_util.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_SOCKET_POLLING_UTIL_HPP_INCLUDED__
#define __ZMQ_SOCKET_POLLING_UTIL_HPP_INCLUDED__
#include <stdlib.h>
#include <vector>
#if defined ZMQ_HAVE_WINDOWS
#include <winsock.h>
#else
#include <sys/select.h>
#endif
#include "macros.hpp"
#include "stdint.hpp"
#include "platform.hpp"
#include "err.hpp"
namespace zmq
{
template <typename T, size_t S> class fast_vector_t
{
public:
explicit fast_vector_t (const size_t nitems_)
{
if (nitems_ > S) {
_buf = new (std::nothrow) T[nitems_];
// TODO since this function is called by a client, we could return errno == ENOMEM here
alloc_assert (_buf);
} else {
_buf = _static_buf;
}
}
T &operator[] (const size_t i) { return _buf[i]; }
~fast_vector_t ()
{
if (_buf != _static_buf)
delete[] _buf;
}
private:
T _static_buf[S];
T *_buf;
ZMQ_NON_COPYABLE_NOR_MOVABLE (fast_vector_t)
};
template <typename T, size_t S> class resizable_fast_vector_t
{
public:
resizable_fast_vector_t () : _dynamic_buf (NULL) {}
void resize (const size_t nitems_)
{
if (_dynamic_buf) {
_dynamic_buf->resize (nitems_);
} else if (nitems_ > S) {
_dynamic_buf = new (std::nothrow) std::vector<T> (nitems_);
// TODO since this function is called by a client, we could return errno == ENOMEM here
alloc_assert (_dynamic_buf);
memcpy (&(*_dynamic_buf)[0], _static_buf, sizeof _static_buf);
}
}
T *get_buf ()
{
// e.g. MSVC 2008 does not have std::vector::data, so we use &...[0]
return _dynamic_buf ? &(*_dynamic_buf)[0] : _static_buf;
}
T &operator[] (const size_t i) { return get_buf ()[i]; }
~resizable_fast_vector_t () { delete _dynamic_buf; }
private:
T _static_buf[S];
std::vector<T> *_dynamic_buf;
ZMQ_NON_COPYABLE_NOR_MOVABLE (resizable_fast_vector_t)
};
#if defined ZMQ_POLL_BASED_ON_POLL
typedef int timeout_t;
timeout_t
compute_timeout (bool first_pass_, long timeout_, uint64_t now_, uint64_t end_);
#endif
#if (!defined ZMQ_POLL_BASED_ON_POLL && defined ZMQ_POLL_BASED_ON_SELECT) \
|| defined ZMQ_HAVE_PPOLL
#if defined ZMQ_HAVE_WINDOWS
inline size_t valid_pollset_bytes (const fd_set &pollset_)
{
// On Windows we don't need to copy the whole fd_set.
// SOCKETS are continuous from the beginning of fd_array in fd_set.
// We just need to copy fd_count elements of fd_array.
// We gain huge memcpy() improvement if number of used SOCKETs is much lower than FD_SETSIZE.
return reinterpret_cast<const char *> (
&pollset_.fd_array[pollset_.fd_count])
- reinterpret_cast<const char *> (&pollset_);
}
#else
inline size_t valid_pollset_bytes (const fd_set & /*pollset_*/)
{
return sizeof (fd_set);
}
#endif
#if defined ZMQ_HAVE_WINDOWS
// struct fd_set {
// u_int fd_count;
// SOCKET fd_array[1];
// };
// NOTE: offsetof(fd_set, fd_array)==sizeof(SOCKET) on both x86 and x64
// due to alignment bytes for the latter.
class optimized_fd_set_t
{
public:
explicit optimized_fd_set_t (size_t nevents_) : _fd_set (1 + nevents_) {}
fd_set *get () { return reinterpret_cast<fd_set *> (&_fd_set[0]); }
private:
fast_vector_t<SOCKET, 1 + ZMQ_POLLITEMS_DFLT> _fd_set;
};
class resizable_optimized_fd_set_t
{
public:
void resize (size_t nevents_) { _fd_set.resize (1 + nevents_); }
fd_set *get () { return reinterpret_cast<fd_set *> (&_fd_set[0]); }
private:
resizable_fast_vector_t<SOCKET, 1 + ZMQ_POLLITEMS_DFLT> _fd_set;
};
#else
class optimized_fd_set_t
{
public:
explicit optimized_fd_set_t (size_t /*nevents_*/) {}
fd_set *get () { return &_fd_set; }
private:
fd_set _fd_set;
};
class resizable_optimized_fd_set_t : public optimized_fd_set_t
{
public:
resizable_optimized_fd_set_t () : optimized_fd_set_t (0) {}
void resize (size_t /*nevents_*/) {}
};
#endif
#endif
}
#endif
| 4,081
|
C++
|
.h
| 133
| 26.481203
| 100
| 0.633997
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
14,534
|
tcp_listener.hpp
|
zeromq_libzmq/src/tcp_listener.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_TCP_LISTENER_HPP_INCLUDED__
#define __ZMQ_TCP_LISTENER_HPP_INCLUDED__
#include "fd.hpp"
#include "tcp_address.hpp"
#include "stream_listener_base.hpp"
namespace zmq
{
class tcp_listener_t ZMQ_FINAL : public stream_listener_base_t
{
public:
tcp_listener_t (zmq::io_thread_t *io_thread_,
zmq::socket_base_t *socket_,
const options_t &options_);
// Set address to listen on.
int set_local_address (const char *addr_);
protected:
std::string get_socket_name (fd_t fd_, socket_end_t socket_end_) const;
private:
// Handlers for I/O events.
void in_event ();
// Accept the new connection. Returns the file descriptor of the
// newly created connection. The function may return retired_fd
// if the connection was dropped while waiting in the listen backlog
// or was denied because of accept filters.
fd_t accept ();
int create_socket (const char *addr_);
// Address to listen on.
tcp_address_t _address;
ZMQ_NON_COPYABLE_NOR_MOVABLE (tcp_listener_t)
};
}
#endif
| 1,134
|
C++
|
.h
| 33
| 29.818182
| 75
| 0.677982
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| true
| true
| false
|
14,535
|
ipc_listener.hpp
|
zeromq_libzmq/src/ipc_listener.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_IPC_LISTENER_HPP_INCLUDED__
#define __ZMQ_IPC_LISTENER_HPP_INCLUDED__
#if defined ZMQ_HAVE_IPC
#include <string>
#include "fd.hpp"
#include "stream_listener_base.hpp"
namespace zmq
{
class ipc_listener_t ZMQ_FINAL : public stream_listener_base_t
{
public:
ipc_listener_t (zmq::io_thread_t *io_thread_,
zmq::socket_base_t *socket_,
const options_t &options_);
// Set address to listen on.
int set_local_address (const char *addr_);
protected:
std::string get_socket_name (fd_t fd_, socket_end_t socket_end_) const;
private:
// Handlers for I/O events.
void in_event ();
// Filter new connections if the OS provides a mechanism to get
// the credentials of the peer process. Called from accept().
#if defined ZMQ_HAVE_SO_PEERCRED || defined ZMQ_HAVE_LOCAL_PEERCRED
bool filter (fd_t sock_);
#endif
int close ();
// Accept the new connection. Returns the file descriptor of the
// newly created connection. The function may return retired_fd
// if the connection was dropped while waiting in the listen backlog.
fd_t accept ();
// True, if the underlying file for UNIX domain socket exists.
bool _has_file;
// Name of the temporary directory (if any) that has the
// UNIX domain socket
std::string _tmp_socket_dirname;
// Name of the file associated with the UNIX domain address.
std::string _filename;
ZMQ_NON_COPYABLE_NOR_MOVABLE (ipc_listener_t)
};
}
#endif
#endif
| 1,581
|
C++
|
.h
| 44
| 31.5
| 75
| 0.6875
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| true
| true
| false
|
14,536
|
raw_decoder.hpp
|
zeromq_libzmq/src/raw_decoder.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_RAW_DECODER_HPP_INCLUDED__
#define __ZMQ_RAW_DECODER_HPP_INCLUDED__
#include "msg.hpp"
#include "i_decoder.hpp"
#include "stdint.hpp"
#include "decoder_allocators.hpp"
namespace zmq
{
// Decoder for 0MQ v1 framing protocol. Converts data stream into messages.
class raw_decoder_t ZMQ_FINAL : public i_decoder
{
public:
raw_decoder_t (size_t bufsize_);
~raw_decoder_t ();
// i_decoder interface.
void get_buffer (unsigned char **data_, size_t *size_);
int decode (const unsigned char *data_, size_t size_, size_t &bytes_used_);
msg_t *msg () { return &_in_progress; }
void resize_buffer (size_t) {}
private:
msg_t _in_progress;
shared_message_memory_allocator _allocator;
ZMQ_NON_COPYABLE_NOR_MOVABLE (raw_decoder_t)
};
}
#endif
| 840
|
C++
|
.h
| 27
| 28
| 79
| 0.7
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| true
| true
| false
|
14,544
|
ws_listener.hpp
|
zeromq_libzmq/src/ws_listener.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_WS_LISTENER_HPP_INCLUDED__
#define __ZMQ_WS_LISTENER_HPP_INCLUDED__
#include "fd.hpp"
#include "ws_address.hpp"
#include "stream_listener_base.hpp"
#ifdef ZMQ_USE_GNUTLS
#include <gnutls/gnutls.h>
#endif
namespace zmq
{
class ws_listener_t ZMQ_FINAL : public stream_listener_base_t
{
public:
ws_listener_t (zmq::io_thread_t *io_thread_,
zmq::socket_base_t *socket_,
const options_t &options_,
bool wss_);
~ws_listener_t ();
// Set address to listen on.
int set_local_address (const char *addr_);
protected:
std::string get_socket_name (fd_t fd_, socket_end_t socket_end_) const;
void create_engine (fd_t fd);
private:
// Handlers for I/O events.
void in_event ();
// Accept the new connection. Returns the file descriptor of the
// newly created connection. The function may return retired_fd
// if the connection was dropped while waiting in the listen backlog
// or was denied because of accept filters.
fd_t accept ();
int create_socket (const char *addr_);
// Address to listen on.
ws_address_t _address;
bool _wss;
#ifdef ZMQ_HAVE_WSS
gnutls_certificate_credentials_t _tls_cred;
#endif
ZMQ_NON_COPYABLE_NOR_MOVABLE (ws_listener_t)
};
}
#endif
| 1,361
|
C++
|
.h
| 43
| 27.093023
| 75
| 0.671779
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,545
|
wss_engine.hpp
|
zeromq_libzmq/src/wss_engine.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_WSS_ENGINE_HPP_INCLUDED__
#define __ZMQ_WSS_ENGINE_HPP_INCLUDED__
#include <gnutls/gnutls.h>
#include "ws_engine.hpp"
#define WSS_BUFFER_SIZE 8192
namespace zmq
{
class wss_engine_t : public ws_engine_t
{
public:
wss_engine_t (fd_t fd_,
const options_t &options_,
const endpoint_uri_pair_t &endpoint_uri_pair_,
ws_address_t &address_,
bool client_,
void *tls_server_cred_,
const std::string &hostname_);
~wss_engine_t ();
void out_event ();
protected:
bool handshake ();
void plug_internal ();
int read (void *data, size_t size_);
int write (const void *data_, size_t size_);
private:
bool do_handshake ();
bool _established;
gnutls_certificate_credentials_t _tls_client_cred;
gnutls_session_t _tls_session;
};
}
#endif
| 940
|
C++
|
.h
| 33
| 22.424242
| 64
| 0.614699
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,551
|
raw_encoder.hpp
|
zeromq_libzmq/src/raw_encoder.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_RAW_ENCODER_HPP_INCLUDED__
#define __ZMQ_RAW_ENCODER_HPP_INCLUDED__
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include "encoder.hpp"
namespace zmq
{
// Encoder for 0MQ framing protocol. Converts messages into data batches.
class raw_encoder_t ZMQ_FINAL : public encoder_base_t<raw_encoder_t>
{
public:
raw_encoder_t (size_t bufsize_);
~raw_encoder_t ();
private:
void raw_message_ready ();
ZMQ_NON_COPYABLE_NOR_MOVABLE (raw_encoder_t)
};
}
#endif
| 547
|
C++
|
.h
| 21
| 23.714286
| 74
| 0.723938
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| true
| true
| true
| false
|
14,556
|
zmq_draft.h
|
zeromq_libzmq/src/zmq_draft.h
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_DRAFT_H_INCLUDED__
#define __ZMQ_DRAFT_H_INCLUDED__
/******************************************************************************/
/* These functions are DRAFT and disabled in stable releases, and subject to */
/* change at ANY time until declared stable. */
/******************************************************************************/
#ifndef ZMQ_BUILD_DRAFT_API
/* DRAFT Socket types. */
#define ZMQ_SERVER 12
#define ZMQ_CLIENT 13
#define ZMQ_RADIO 14
#define ZMQ_DISH 15
#define ZMQ_GATHER 16
#define ZMQ_SCATTER 17
#define ZMQ_DGRAM 18
#define ZMQ_PEER 19
#define ZMQ_CHANNEL 20
/* DRAFT Socket options. */
#define ZMQ_ZAP_ENFORCE_DOMAIN 93
#define ZMQ_LOOPBACK_FASTPATH 94
#define ZMQ_METADATA 95
#define ZMQ_MULTICAST_LOOP 96
#define ZMQ_ROUTER_NOTIFY 97
#define ZMQ_XPUB_MANUAL_LAST_VALUE 98
#define ZMQ_SOCKS_USERNAME 99
#define ZMQ_SOCKS_PASSWORD 100
#define ZMQ_IN_BATCH_SIZE 101
#define ZMQ_OUT_BATCH_SIZE 102
#define ZMQ_WSS_KEY_PEM 103
#define ZMQ_WSS_CERT_PEM 104
#define ZMQ_WSS_TRUST_PEM 105
#define ZMQ_WSS_HOSTNAME 106
#define ZMQ_WSS_TRUST_SYSTEM 107
#define ZMQ_ONLY_FIRST_SUBSCRIBE 108
#define ZMQ_RECONNECT_STOP 109
#define ZMQ_HELLO_MSG 110
#define ZMQ_DISCONNECT_MSG 111
#define ZMQ_PRIORITY 112
#define ZMQ_BUSY_POLL 113
#define ZMQ_HICCUP_MSG 114
#define ZMQ_XSUB_VERBOSE_UNSUBSCRIBE 115
#define ZMQ_TOPICS_COUNT 116
#define ZMQ_NORM_MODE 117
#define ZMQ_NORM_UNICAST_NACK 118
#define ZMQ_NORM_BUFFER_SIZE 119
#define ZMQ_NORM_SEGMENT_SIZE 120
#define ZMQ_NORM_BLOCK_SIZE 121
#define ZMQ_NORM_NUM_PARITY 122
#define ZMQ_NORM_NUM_AUTOPARITY 123
#define ZMQ_NORM_PUSH 124
/* DRAFT ZMQ_NORM_MODE options */
#define ZMQ_NORM_FIXED 0
#define ZMQ_NORM_CC 1
#define ZMQ_NORM_CCL 2
#define ZMQ_NORM_CCE 3
#define ZMQ_NORM_CCE_ECNONLY 4
/* DRAFT ZMQ_RECONNECT_STOP options */
#define ZMQ_RECONNECT_STOP_CONN_REFUSED 0x1
#define ZMQ_RECONNECT_STOP_HANDSHAKE_FAILED 0x2
#define ZMQ_RECONNECT_STOP_AFTER_DISCONNECT 0x4
/* DRAFT Context options */
#define ZMQ_ZERO_COPY_RECV 10
/* DRAFT Context methods. */
int zmq_ctx_set_ext (void *context_,
int option_,
const void *optval_,
size_t optvallen_);
int zmq_ctx_get_ext (void *context_,
int option_,
void *optval_,
size_t *optvallen_);
/* DRAFT Socket methods. */
int zmq_join (void *s_, const char *group_);
int zmq_leave (void *s_, const char *group_);
/* DRAFT Msg methods. */
int zmq_msg_set_routing_id (zmq_msg_t *msg_, uint32_t routing_id_);
uint32_t zmq_msg_routing_id (zmq_msg_t *msg_);
int zmq_msg_set_group (zmq_msg_t *msg_, const char *group_);
const char *zmq_msg_group (zmq_msg_t *msg_);
int zmq_msg_init_buffer (zmq_msg_t *msg_, const void *buf_, size_t size_);
/* DRAFT Msg property names. */
#define ZMQ_MSG_PROPERTY_ROUTING_ID "Routing-Id"
#define ZMQ_MSG_PROPERTY_SOCKET_TYPE "Socket-Type"
#define ZMQ_MSG_PROPERTY_USER_ID "User-Id"
#define ZMQ_MSG_PROPERTY_PEER_ADDRESS "Peer-Address"
/* Router notify options */
#define ZMQ_NOTIFY_CONNECT 1
#define ZMQ_NOTIFY_DISCONNECT 2
/******************************************************************************/
/* Poller polling on sockets,fd and thread-safe sockets */
/******************************************************************************/
#if defined _WIN32
typedef SOCKET zmq_fd_t;
#else
typedef int zmq_fd_t;
#endif
typedef struct zmq_poller_event_t
{
void *socket;
zmq_fd_t fd;
void *user_data;
short events;
} zmq_poller_event_t;
void *zmq_poller_new (void);
int zmq_poller_destroy (void **poller_p_);
int zmq_poller_size (void *poller_);
int zmq_poller_add (void *poller_,
void *socket_,
void *user_data_,
short events_);
int zmq_poller_modify (void *poller_, void *socket_, short events_);
int zmq_poller_remove (void *poller_, void *socket_);
int zmq_poller_wait (void *poller_, zmq_poller_event_t *event_, long timeout_);
int zmq_poller_wait_all (void *poller_,
zmq_poller_event_t *events_,
int n_events_,
long timeout_);
zmq_fd_t zmq_poller_fd (void *poller_);
int zmq_poller_add_fd (void *poller_,
zmq_fd_t fd_,
void *user_data_,
short events_);
int zmq_poller_modify_fd (void *poller_, zmq_fd_t fd_, short events_);
int zmq_poller_remove_fd (void *poller_, zmq_fd_t fd_);
int zmq_socket_get_peer_state (void *socket_,
const void *routing_id_,
size_t routing_id_size_);
/* DRAFT Socket monitoring events */
#define ZMQ_EVENT_PIPES_STATS 0x10000
#define ZMQ_CURRENT_EVENT_VERSION 1
#define ZMQ_CURRENT_EVENT_VERSION_DRAFT 2
#define ZMQ_EVENT_ALL_V1 ZMQ_EVENT_ALL
#define ZMQ_EVENT_ALL_V2 ZMQ_EVENT_ALL_V1 | ZMQ_EVENT_PIPES_STATS
int zmq_socket_monitor_versioned (
void *s_, const char *addr_, uint64_t events_, int event_version_, int type_);
int zmq_socket_monitor_pipes_stats (void *s_);
#if !defined _WIN32
int zmq_ppoll (zmq_pollitem_t *items_,
int nitems_,
long timeout_,
const sigset_t *sigmask_);
#else
// Windows has no sigset_t
int zmq_ppoll (zmq_pollitem_t *items_,
int nitems_,
long timeout_,
const void *sigmask_);
#endif
#endif // ZMQ_BUILD_DRAFT_API
#endif //ifndef __ZMQ_DRAFT_H_INCLUDED__
| 6,149
|
C++
|
.h
| 151
| 36.238411
| 80
| 0.576356
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
14,557
|
fd.hpp
|
zeromq_libzmq/src/fd.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_FD_HPP_INCLUDED__
#define __ZMQ_FD_HPP_INCLUDED__
#if defined _WIN32
#include "windows.hpp"
#endif
namespace zmq
{
typedef zmq_fd_t fd_t;
#ifdef ZMQ_HAVE_WINDOWS
#if defined _MSC_VER && _MSC_VER <= 1400
enum
{
retired_fd = (fd_t) (~0)
};
#else
enum
#if _MSC_VER >= 1800
: fd_t
#endif
{
retired_fd = INVALID_SOCKET
};
#endif
#else
enum
{
retired_fd = -1
};
#endif
}
#endif
| 443
|
C++
|
.h
| 32
| 12.28125
| 40
| 0.683047
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,559
|
channel.hpp
|
zeromq_libzmq/src/channel.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_CHANNEL_HPP_INCLUDED__
#define __ZMQ_CHANNEL_HPP_INCLUDED__
#include "blob.hpp"
#include "socket_base.hpp"
#include "session_base.hpp"
namespace zmq
{
class ctx_t;
class msg_t;
class pipe_t;
class io_thread_t;
class channel_t ZMQ_FINAL : public socket_base_t
{
public:
channel_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_);
~channel_t ();
// Overrides of functions from socket_base_t.
void xattach_pipe (zmq::pipe_t *pipe_,
bool subscribe_to_all_,
bool locally_initiated_);
int xsend (zmq::msg_t *msg_);
int xrecv (zmq::msg_t *msg_);
bool xhas_in ();
bool xhas_out ();
void xread_activated (zmq::pipe_t *pipe_);
void xwrite_activated (zmq::pipe_t *pipe_);
void xpipe_terminated (zmq::pipe_t *pipe_);
private:
zmq::pipe_t *_pipe;
ZMQ_NON_COPYABLE_NOR_MOVABLE (channel_t)
};
}
#endif
| 949
|
C++
|
.h
| 34
| 23.676471
| 61
| 0.642778
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| true
| true
| true
| false
|
14,566
|
curve_mechanism_base.hpp
|
zeromq_libzmq/src/curve_mechanism_base.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_CURVE_MECHANISM_BASE_HPP_INCLUDED__
#define __ZMQ_CURVE_MECHANISM_BASE_HPP_INCLUDED__
#ifdef ZMQ_HAVE_CURVE
#if defined(ZMQ_USE_LIBSODIUM)
#include "sodium.h"
#endif
#if crypto_box_NONCEBYTES != 24 || crypto_box_PUBLICKEYBYTES != 32 \
|| crypto_box_SECRETKEYBYTES != 32 || crypto_box_ZEROBYTES != 32 \
|| crypto_box_BOXZEROBYTES != 16 || crypto_secretbox_NONCEBYTES != 24 \
|| crypto_secretbox_ZEROBYTES != 32 || crypto_secretbox_BOXZEROBYTES != 16
#error "CURVE library not built properly"
#endif
#include "mechanism_base.hpp"
#include "options.hpp"
#include <memory>
namespace zmq
{
class curve_encoding_t
{
public:
curve_encoding_t (const char *encode_nonce_prefix_,
const char *decode_nonce_prefix_,
const bool downgrade_sub_);
int encode (msg_t *msg_);
int decode (msg_t *msg_, int *error_event_code_);
uint8_t *get_writable_precom_buffer () { return _cn_precom; }
const uint8_t *get_precom_buffer () const { return _cn_precom; }
typedef uint64_t nonce_t;
nonce_t get_and_inc_nonce () { return _cn_nonce++; }
void set_peer_nonce (nonce_t peer_nonce_) { _cn_peer_nonce = peer_nonce_; };
private:
int check_validity (msg_t *msg_, int *error_event_code_);
const char *_encode_nonce_prefix;
const char *_decode_nonce_prefix;
nonce_t _cn_nonce;
nonce_t _cn_peer_nonce;
// Intermediary buffer used to speed up boxing and unboxing.
uint8_t _cn_precom[crypto_box_BEFORENMBYTES];
const bool _downgrade_sub;
ZMQ_NON_COPYABLE_NOR_MOVABLE (curve_encoding_t)
};
class curve_mechanism_base_t : public virtual mechanism_base_t,
public curve_encoding_t
{
public:
curve_mechanism_base_t (session_base_t *session_,
const options_t &options_,
const char *encode_nonce_prefix_,
const char *decode_nonce_prefix_,
const bool downgrade_sub_);
// mechanism implementation
int encode (msg_t *msg_) ZMQ_OVERRIDE;
int decode (msg_t *msg_) ZMQ_OVERRIDE;
};
}
#endif
#endif
| 2,239
|
C++
|
.h
| 58
| 32.362069
| 80
| 0.640278
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
14,570
|
dist.hpp
|
zeromq_libzmq/src/dist.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_DIST_HPP_INCLUDED__
#define __ZMQ_DIST_HPP_INCLUDED__
#include <vector>
#include "array.hpp"
#include "macros.hpp"
namespace zmq
{
class pipe_t;
class msg_t;
// Class manages a set of outbound pipes. It sends each messages to
// each of them.
class dist_t
{
public:
dist_t ();
~dist_t ();
// Adds the pipe to the distributor object.
void attach (zmq::pipe_t *pipe_);
// Checks if this pipe is present in the distributor.
bool has_pipe (zmq::pipe_t *pipe_);
// Activates pipe that have previously reached high watermark.
void activated (zmq::pipe_t *pipe_);
// Mark the pipe as matching. Subsequent call to send_to_matching
// will send message also to this pipe.
void match (zmq::pipe_t *pipe_);
// Marks all pipes that are not matched as matched and vice-versa.
void reverse_match ();
// Mark all pipes as non-matching.
void unmatch ();
// Removes the pipe from the distributor object.
void pipe_terminated (zmq::pipe_t *pipe_);
// Send the message to the matching outbound pipes.
int send_to_matching (zmq::msg_t *msg_);
// Send the message to all the outbound pipes.
int send_to_all (zmq::msg_t *msg_);
static bool has_out ();
// check HWM of all pipes matching
bool check_hwm ();
private:
// Write the message to the pipe. Make the pipe inactive if writing
// fails. In such a case false is returned.
bool write (zmq::pipe_t *pipe_, zmq::msg_t *msg_);
// Put the message to all active pipes.
void distribute (zmq::msg_t *msg_);
// List of outbound pipes.
typedef array_t<zmq::pipe_t, 2> pipes_t;
pipes_t _pipes;
// Number of all the pipes to send the next message to.
pipes_t::size_type _matching;
// Number of active pipes. All the active pipes are located at the
// beginning of the pipes array. These are the pipes the messages
// can be sent to at the moment.
pipes_t::size_type _active;
// Number of pipes eligible for sending messages to. This includes all
// the active pipes plus all the pipes that we can in theory send
// messages to (the HWM is not yet reached), but sending a message
// to them would result in partial message being delivered, ie. message
// with initial parts missing.
pipes_t::size_type _eligible;
// True if last we are in the middle of a multipart message.
bool _more;
ZMQ_NON_COPYABLE_NOR_MOVABLE (dist_t)
};
}
#endif
| 2,552
|
C++
|
.h
| 66
| 34.378788
| 76
| 0.676148
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| true
| true
| false
|
14,593
|
v2_encoder.hpp
|
zeromq_libzmq/src/v2_encoder.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_V2_ENCODER_HPP_INCLUDED__
#define __ZMQ_V2_ENCODER_HPP_INCLUDED__
#include "encoder.hpp"
namespace zmq
{
// Encoder for 0MQ framing protocol. Converts messages into data stream.
class v2_encoder_t ZMQ_FINAL : public encoder_base_t<v2_encoder_t>
{
public:
v2_encoder_t (size_t bufsize_);
~v2_encoder_t ();
private:
void size_ready ();
void message_ready ();
// flags byte + size byte (or 8 bytes) + sub/cancel byte
unsigned char _tmp_buf[10];
ZMQ_NON_COPYABLE_NOR_MOVABLE (v2_encoder_t)
};
}
#endif
| 593
|
C++
|
.h
| 21
| 25.333333
| 73
| 0.696809
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| true
| true
| true
| false
|
14,596
|
trie.hpp
|
zeromq_libzmq/src/trie.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_TRIE_HPP_INCLUDED__
#define __ZMQ_TRIE_HPP_INCLUDED__
#include <stddef.h>
#include "macros.hpp"
#include "stdint.hpp"
#include "atomic_counter.hpp"
namespace zmq
{
class trie_t
{
public:
trie_t ();
~trie_t ();
// Add key to the trie. Returns true if this is a new item in the trie
// rather than a duplicate.
bool add (unsigned char *prefix_, size_t size_);
// Remove key from the trie. Returns true if the item is actually
// removed from the trie.
bool rm (unsigned char *prefix_, size_t size_);
// Check whether particular key is in the trie.
bool check (const unsigned char *data_, size_t size_) const;
// Apply the function supplied to each subscription in the trie.
void apply (void (*func_) (unsigned char *data_, size_t size_, void *arg_),
void *arg_);
private:
void apply_helper (unsigned char **buff_,
size_t buffsize_,
size_t maxbuffsize_,
void (*func_) (unsigned char *data_,
size_t size_,
void *arg_),
void *arg_) const;
bool is_redundant () const;
uint32_t _refcnt;
unsigned char _min;
unsigned short _count;
unsigned short _live_nodes;
union
{
class trie_t *node;
class trie_t **table;
} _next;
ZMQ_NON_COPYABLE_NOR_MOVABLE (trie_t)
};
// lightweight wrapper around trie_t adding tracking of total number of prefixes
class trie_with_size_t
{
public:
trie_with_size_t () {}
~trie_with_size_t () {}
bool add (unsigned char *prefix_, size_t size_)
{
if (_trie.add (prefix_, size_)) {
_num_prefixes.add (1);
return true;
} else
return false;
}
bool rm (unsigned char *prefix_, size_t size_)
{
if (_trie.rm (prefix_, size_)) {
_num_prefixes.sub (1);
return true;
} else
return false;
}
bool check (const unsigned char *data_, size_t size_) const
{
return _trie.check (data_, size_);
}
void apply (void (*func_) (unsigned char *data_, size_t size_, void *arg_),
void *arg_)
{
_trie.apply (func_, arg_);
}
// Retrieve the number of prefixes stored in this trie (added - removed)
// Note this is a multithread safe function.
uint32_t num_prefixes () const { return _num_prefixes.get (); }
private:
atomic_counter_t _num_prefixes;
trie_t _trie;
};
}
#endif
| 2,653
|
C++
|
.h
| 85
| 23.988235
| 80
| 0.575186
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
14,598
|
metadata.hpp
|
zeromq_libzmq/src/metadata.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_METADATA_HPP_INCLUDED__
#define __ZMQ_METADATA_HPP_INCLUDED__
#include <map>
#include <string>
#include "atomic_counter.hpp"
namespace zmq
{
class metadata_t
{
public:
typedef std::map<std::string, std::string> dict_t;
metadata_t (const dict_t &dict_);
// Returns pointer to property value or NULL if
// property is not found.
const char *get (const std::string &property_) const;
void add_ref ();
// Drop reference. Returns true iff the reference
// counter drops to zero.
bool drop_ref ();
private:
// Reference counter.
atomic_counter_t _ref_cnt;
// Dictionary holding metadata.
const dict_t _dict;
ZMQ_NON_COPYABLE_NOR_MOVABLE (metadata_t)
};
}
#endif
| 787
|
C++
|
.h
| 29
| 23.655172
| 57
| 0.684987
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| true
| true
| true
| false
|
14,612
|
session_base.hpp
|
zeromq_libzmq/src/session_base.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_SESSION_BASE_HPP_INCLUDED__
#define __ZMQ_SESSION_BASE_HPP_INCLUDED__
#include <stdarg.h>
#include "own.hpp"
#include "io_object.hpp"
#include "pipe.hpp"
#include "socket_base.hpp"
#include "i_engine.hpp"
#include "msg.hpp"
namespace zmq
{
class io_thread_t;
struct i_engine;
struct address_t;
class session_base_t : public own_t, public io_object_t, public i_pipe_events
{
public:
// Create a session of the particular type.
static session_base_t *create (zmq::io_thread_t *io_thread_,
bool active_,
zmq::socket_base_t *socket_,
const options_t &options_,
address_t *addr_);
// To be used once only, when creating the session.
void attach_pipe (zmq::pipe_t *pipe_);
// Following functions are the interface exposed towards the engine.
virtual void reset ();
void flush ();
void rollback ();
void engine_error (bool handshaked_, zmq::i_engine::error_reason_t reason_);
void engine_ready ();
// i_pipe_events interface implementation.
void read_activated (zmq::pipe_t *pipe_) ZMQ_FINAL;
void write_activated (zmq::pipe_t *pipe_) ZMQ_FINAL;
void hiccuped (zmq::pipe_t *pipe_) ZMQ_FINAL;
void pipe_terminated (zmq::pipe_t *pipe_) ZMQ_FINAL;
// Delivers a message. Returns 0 if successful; -1 otherwise.
// The function takes ownership of the message.
virtual int push_msg (msg_t *msg_);
int zap_connect ();
bool zap_enabled () const;
// Fetches a message. Returns 0 if successful; -1 otherwise.
// The caller is responsible for freeing the message when no
// longer used.
virtual int pull_msg (msg_t *msg_);
// Receives message from ZAP socket.
// Returns 0 on success; -1 otherwise.
// The caller is responsible for freeing the message.
int read_zap_msg (msg_t *msg_);
// Sends message to ZAP socket.
// Returns 0 on success; -1 otherwise.
// The function takes ownership of the message.
int write_zap_msg (msg_t *msg_);
socket_base_t *get_socket () const;
const endpoint_uri_pair_t &get_endpoint () const;
protected:
session_base_t (zmq::io_thread_t *io_thread_,
bool active_,
zmq::socket_base_t *socket_,
const options_t &options_,
address_t *addr_);
~session_base_t () ZMQ_OVERRIDE;
private:
void start_connecting (bool wait_);
void reconnect ();
// Handlers for incoming commands.
void process_plug () ZMQ_FINAL;
void process_attach (zmq::i_engine *engine_) ZMQ_FINAL;
void process_term (int linger_) ZMQ_FINAL;
void process_conn_failed () ZMQ_OVERRIDE;
// i_poll_events handlers.
void timer_event (int id_) ZMQ_FINAL;
// Remove any half processed messages. Flush unflushed messages.
// Call this function when engine disconnect to get rid of leftovers.
void clean_pipes ();
// If true, this session (re)connects to the peer. Otherwise, it's
// a transient session created by the listener.
const bool _active;
// Pipe connecting the session to its socket.
zmq::pipe_t *_pipe;
// Pipe used to exchange messages with ZAP socket.
zmq::pipe_t *_zap_pipe;
// This set is added to with pipes we are disconnecting, but haven't yet completed
std::set<pipe_t *> _terminating_pipes;
// This flag is true if the remainder of the message being processed
// is still in the in pipe.
bool _incomplete_in;
// True if termination have been suspended to push the pending
// messages to the network.
bool _pending;
// The protocol I/O engine connected to the session.
zmq::i_engine *_engine;
// The socket the session belongs to.
zmq::socket_base_t *_socket;
// I/O thread the session is living in. It will be used to plug in
// the engines into the same thread.
zmq::io_thread_t *_io_thread;
// ID of the linger timer
enum
{
linger_timer_id = 0x20
};
// True is linger timer is running.
bool _has_linger_timer;
// Protocol and address to use when connecting.
address_t *_addr;
#ifdef ZMQ_HAVE_WSS
// TLS handshake, we need to take a copy when the session is created,
// in order to maintain the value at the creation time
const std::string _wss_hostname;
#endif
ZMQ_NON_COPYABLE_NOR_MOVABLE (session_base_t)
};
class hello_msg_session_t ZMQ_FINAL : public session_base_t
{
public:
hello_msg_session_t (zmq::io_thread_t *io_thread_,
bool connect_,
zmq::socket_base_t *socket_,
const options_t &options_,
address_t *addr_);
~hello_msg_session_t ();
// Overrides of the functions from session_base_t.
int pull_msg (msg_t *msg_);
void reset ();
private:
bool _new_pipe;
ZMQ_NON_COPYABLE_NOR_MOVABLE (hello_msg_session_t)
};
}
#endif
| 5,138
|
C++
|
.h
| 132
| 32.371212
| 87
| 0.638816
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
14,618
|
generic_mtrie_impl.hpp
|
zeromq_libzmq/src/generic_mtrie_impl.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_GENERIC_MTRIE_IMPL_HPP_INCLUDED__
#define __ZMQ_GENERIC_MTRIE_IMPL_HPP_INCLUDED__
#include <stdlib.h>
#include <new>
#include <algorithm>
#include <list>
#include "err.hpp"
#include "macros.hpp"
#include "generic_mtrie.hpp"
namespace zmq
{
template <typename T>
generic_mtrie_t<T>::generic_mtrie_t () :
_pipes (0), _num_prefixes (0), _min (0), _count (0), _live_nodes (0)
{
}
template <typename T> generic_mtrie_t<T>::~generic_mtrie_t ()
{
LIBZMQ_DELETE (_pipes);
if (_count == 1) {
zmq_assert (_next.node);
LIBZMQ_DELETE (_next.node);
} else if (_count > 1) {
for (unsigned short i = 0; i != _count; ++i) {
LIBZMQ_DELETE (_next.table[i]);
}
free (_next.table);
}
}
template <typename T>
bool generic_mtrie_t<T>::add (prefix_t prefix_, size_t size_, value_t *pipe_)
{
generic_mtrie_t<value_t> *it = this;
while (size_) {
const unsigned char c = *prefix_;
if (c < it->_min || c >= it->_min + it->_count) {
// The character is out of range of currently handled
// characters. We have to extend the table.
if (!it->_count) {
it->_min = c;
it->_count = 1;
it->_next.node = NULL;
} else if (it->_count == 1) {
const unsigned char oldc = it->_min;
generic_mtrie_t *oldp = it->_next.node;
it->_count = (it->_min < c ? c - it->_min : it->_min - c) + 1;
it->_next.table = static_cast<generic_mtrie_t **> (
malloc (sizeof (generic_mtrie_t *) * it->_count));
alloc_assert (it->_next.table);
for (unsigned short i = 0; i != it->_count; ++i)
it->_next.table[i] = 0;
it->_min = std::min (it->_min, c);
it->_next.table[oldc - it->_min] = oldp;
} else if (it->_min < c) {
// The new character is above the current character range.
const unsigned short old_count = it->_count;
it->_count = c - it->_min + 1;
it->_next.table = static_cast<generic_mtrie_t **> (realloc (
it->_next.table, sizeof (generic_mtrie_t *) * it->_count));
alloc_assert (it->_next.table);
for (unsigned short i = old_count; i != it->_count; i++)
it->_next.table[i] = NULL;
} else {
// The new character is below the current character range.
const unsigned short old_count = it->_count;
it->_count = (it->_min + old_count) - c;
it->_next.table = static_cast<generic_mtrie_t **> (realloc (
it->_next.table, sizeof (generic_mtrie_t *) * it->_count));
alloc_assert (it->_next.table);
memmove (it->_next.table + it->_min - c, it->_next.table,
old_count * sizeof (generic_mtrie_t *));
for (unsigned short i = 0; i != it->_min - c; i++)
it->_next.table[i] = NULL;
it->_min = c;
}
}
// If next node does not exist, create one.
if (it->_count == 1) {
if (!it->_next.node) {
it->_next.node = new (std::nothrow) generic_mtrie_t;
alloc_assert (it->_next.node);
++(it->_live_nodes);
}
++prefix_;
--size_;
it = it->_next.node;
} else {
if (!it->_next.table[c - it->_min]) {
it->_next.table[c - it->_min] =
new (std::nothrow) generic_mtrie_t;
alloc_assert (it->_next.table[c - it->_min]);
++(it->_live_nodes);
}
++prefix_;
--size_;
it = it->_next.table[c - it->_min];
}
}
// We are at the node corresponding to the prefix. We are done.
const bool result = !it->_pipes;
if (!it->_pipes) {
it->_pipes = new (std::nothrow) pipes_t;
alloc_assert (it->_pipes);
_num_prefixes.add (1);
}
it->_pipes->insert (pipe_);
return result;
}
template <typename T>
template <typename Arg>
void generic_mtrie_t<T>::rm (value_t *pipe_,
void (*func_) (prefix_t data_,
size_t size_,
Arg arg_),
Arg arg_,
bool call_on_uniq_)
{
// This used to be implemented as a non-tail recursive traversal of the trie,
// which means remote clients controlled the depth of the recursion and the
// stack size.
// To simulate the non-tail recursion, with post-recursion changes depending on
// the result of the recursive call, a stack is used to re-visit the same node
// and operate on it again after children have been visited.
// A boolean is used to record whether the node had already been visited and to
// determine if the pre- or post- children visit actions have to be taken.
// In the case of a node with (N > 1) children, the node has to be re-visited
// N times, in the correct order after each child visit.
std::list<struct iter> stack;
unsigned char *buff = NULL;
size_t maxbuffsize = 0;
struct iter it = {this, NULL, NULL, 0, 0, 0, 0, false};
stack.push_back (it);
while (!stack.empty ()) {
it = stack.back ();
stack.pop_back ();
if (!it.processed_for_removal) {
// Remove the subscription from this node.
if (it.node->_pipes && it.node->_pipes->erase (pipe_)) {
if (!call_on_uniq_ || it.node->_pipes->empty ()) {
func_ (buff, it.size, arg_);
}
if (it.node->_pipes->empty ()) {
LIBZMQ_DELETE (it.node->_pipes);
}
}
// Adjust the buffer.
if (it.size >= maxbuffsize) {
maxbuffsize = it.size + 256;
buff =
static_cast<unsigned char *> (realloc (buff, maxbuffsize));
alloc_assert (buff);
}
switch (it.node->_count) {
case 0:
// If there are no subnodes in the trie, we are done with this node
// pre-processing.
break;
case 1: {
// If there's one subnode (optimisation).
buff[it.size] = it.node->_min;
// Mark this node as pre-processed and push it, so that the next
// visit after the operation on the child can do the removals.
it.processed_for_removal = true;
stack.push_back (it);
struct iter next = {it.node->_next.node,
NULL,
NULL,
++it.size,
0,
0,
0,
false};
stack.push_back (next);
break;
}
default: {
// If there are multiple subnodes.
// When first visiting this node, initialize the new_min/max parameters
// which will then be used after each child has been processed, on the
// post-children iterations.
if (it.current_child == 0) {
// New min non-null character in the node table after the removal
it.new_min = it.node->_min + it.node->_count - 1;
// New max non-null character in the node table after the removal
it.new_max = it.node->_min;
}
// Mark this node as pre-processed and push it, so that the next
// visit after the operation on the child can do the removals.
buff[it.size] = it.node->_min + it.current_child;
it.processed_for_removal = true;
stack.push_back (it);
if (it.node->_next.table[it.current_child]) {
struct iter next = {
it.node->_next.table[it.current_child],
NULL,
NULL,
it.size + 1,
0,
0,
0,
false};
stack.push_back (next);
}
}
}
} else {
// Reset back for the next time, in case this node doesn't get deleted.
// This is done unconditionally, unlike when setting this variable to true.
it.processed_for_removal = false;
switch (it.node->_count) {
case 0:
// If there are no subnodes in the trie, we are done with this node
// post-processing.
break;
case 1:
// If there's one subnode (optimisation).
// Prune the node if it was made redundant by the removal
if (it.node->_next.node->is_redundant ()) {
LIBZMQ_DELETE (it.node->_next.node);
it.node->_count = 0;
--it.node->_live_nodes;
zmq_assert (it.node->_live_nodes == 0);
}
break;
default:
// If there are multiple subnodes.
{
if (it.node->_next.table[it.current_child]) {
// Prune redundant nodes from the mtrie
if (it.node->_next.table[it.current_child]
->is_redundant ()) {
LIBZMQ_DELETE (
it.node->_next.table[it.current_child]);
zmq_assert (it.node->_live_nodes > 0);
--it.node->_live_nodes;
} else {
// The node is not redundant, so it's a candidate for being
// the new min/max node.
//
// We loop through the node array from left to right, so the
// first non-null, non-redundant node encountered is the new
// minimum index. Conversely, the last non-redundant, non-null
// node encountered is the new maximum index.
if (it.current_child + it.node->_min
< it.new_min)
it.new_min =
it.current_child + it.node->_min;
if (it.current_child + it.node->_min
> it.new_max)
it.new_max =
it.current_child + it.node->_min;
}
}
// If there are more children to visit, push again the current
// node, so that pre-processing can happen on the next child.
// If we are done, reset the child index so that the ::rm is
// fully idempotent.
++it.current_child;
if (it.current_child >= it.node->_count)
it.current_child = 0;
else {
stack.push_back (it);
continue;
}
// All children have been visited and removed if needed, and
// all pre- and post-visit operations have been carried.
// Resize/free the node table if needed.
zmq_assert (it.node->_count > 1);
// Free the node table if it's no longer used.
switch (it.node->_live_nodes) {
case 0:
free (it.node->_next.table);
it.node->_next.table = NULL;
it.node->_count = 0;
break;
case 1:
// Compact the node table if possible
// If there's only one live node in the table we can
// switch to using the more compact single-node
// representation
zmq_assert (it.new_min == it.new_max);
zmq_assert (it.new_min >= it.node->_min);
zmq_assert (it.new_min
< it.node->_min + it.node->_count);
{
generic_mtrie_t *node =
it.node->_next
.table[it.new_min - it.node->_min];
zmq_assert (node);
free (it.node->_next.table);
it.node->_next.node = node;
}
it.node->_count = 1;
it.node->_min = it.new_min;
break;
default:
if (it.new_min > it.node->_min
|| it.new_max < it.node->_min
+ it.node->_count - 1) {
zmq_assert (it.new_max - it.new_min + 1
> 1);
generic_mtrie_t **old_table =
it.node->_next.table;
zmq_assert (it.new_min > it.node->_min
|| it.new_max
< it.node->_min
+ it.node->_count - 1);
zmq_assert (it.new_min >= it.node->_min);
zmq_assert (it.new_max
<= it.node->_min
+ it.node->_count - 1);
zmq_assert (it.new_max - it.new_min + 1
< it.node->_count);
it.node->_count =
it.new_max - it.new_min + 1;
it.node->_next.table =
static_cast<generic_mtrie_t **> (
malloc (sizeof (generic_mtrie_t *)
* it.node->_count));
alloc_assert (it.node->_next.table);
memmove (it.node->_next.table,
old_table
+ (it.new_min - it.node->_min),
sizeof (generic_mtrie_t *)
* it.node->_count);
free (old_table);
it.node->_min = it.new_min;
}
}
}
}
}
}
free (buff);
}
template <typename T>
typename generic_mtrie_t<T>::rm_result
generic_mtrie_t<T>::rm (prefix_t prefix_, size_t size_, value_t *pipe_)
{
// This used to be implemented as a non-tail recursive traversal of the trie,
// which means remote clients controlled the depth of the recursion and the
// stack size.
// To simulate the non-tail recursion, with post-recursion changes depending on
// the result of the recursive call, a stack is used to re-visit the same node
// and operate on it again after children have been visited.
// A boolean is used to record whether the node had already been visited and to
// determine if the pre- or post- children visit actions have to be taken.
rm_result ret = not_found;
std::list<struct iter> stack;
struct iter it = {this, NULL, prefix_, size_, 0, 0, 0, false};
stack.push_back (it);
while (!stack.empty ()) {
it = stack.back ();
stack.pop_back ();
if (!it.processed_for_removal) {
if (!it.size) {
if (!it.node->_pipes) {
ret = not_found;
continue;
}
typename pipes_t::size_type erased =
it.node->_pipes->erase (pipe_);
if (it.node->_pipes->empty ()) {
zmq_assert (erased == 1);
LIBZMQ_DELETE (it.node->_pipes);
ret = last_value_removed;
continue;
}
ret = (erased == 1) ? values_remain : not_found;
continue;
}
it.current_child = *it.prefix;
if (!it.node->_count || it.current_child < it.node->_min
|| it.current_child >= it.node->_min + it.node->_count) {
ret = not_found;
continue;
}
it.next_node =
it.node->_count == 1
? it.node->_next.node
: it.node->_next.table[it.current_child - it.node->_min];
if (!it.next_node) {
ret = not_found;
continue;
}
it.processed_for_removal = true;
stack.push_back (it);
struct iter next = {
it.next_node, NULL, it.prefix + 1, it.size - 1, 0, 0, 0, false};
stack.push_back (next);
} else {
it.processed_for_removal = false;
if (it.next_node->is_redundant ()) {
LIBZMQ_DELETE (it.next_node);
zmq_assert (it.node->_count > 0);
if (it.node->_count == 1) {
it.node->_next.node = NULL;
it.node->_count = 0;
--it.node->_live_nodes;
zmq_assert (it.node->_live_nodes == 0);
} else {
it.node->_next.table[it.current_child - it.node->_min] = 0;
zmq_assert (it.node->_live_nodes > 1);
--it.node->_live_nodes;
// Compact the table if possible
if (it.node->_live_nodes == 1) {
// If there's only one live node in the table we can
// switch to using the more compact single-node
// representation
unsigned short i;
for (i = 0; i < it.node->_count; ++i)
if (it.node->_next.table[i])
break;
zmq_assert (i < it.node->_count);
it.node->_min += i;
it.node->_count = 1;
generic_mtrie_t *oldp = it.node->_next.table[i];
free (it.node->_next.table);
it.node->_next.table = NULL;
it.node->_next.node = oldp;
} else if (it.current_child == it.node->_min) {
// We can compact the table "from the left"
unsigned short i;
for (i = 1; i < it.node->_count; ++i)
if (it.node->_next.table[i])
break;
zmq_assert (i < it.node->_count);
it.node->_min += i;
it.node->_count -= i;
generic_mtrie_t **old_table = it.node->_next.table;
it.node->_next.table =
static_cast<generic_mtrie_t **> (malloc (
sizeof (generic_mtrie_t *) * it.node->_count));
alloc_assert (it.node->_next.table);
memmove (it.node->_next.table, old_table + i,
sizeof (generic_mtrie_t *) * it.node->_count);
free (old_table);
} else if (it.current_child
== it.node->_min + it.node->_count - 1) {
// We can compact the table "from the right"
unsigned short i;
for (i = 1; i < it.node->_count; ++i)
if (it.node->_next.table[it.node->_count - 1 - i])
break;
zmq_assert (i < it.node->_count);
it.node->_count -= i;
generic_mtrie_t **old_table = it.node->_next.table;
it.node->_next.table =
static_cast<generic_mtrie_t **> (malloc (
sizeof (generic_mtrie_t *) * it.node->_count));
alloc_assert (it.node->_next.table);
memmove (it.node->_next.table, old_table,
sizeof (generic_mtrie_t *) * it.node->_count);
free (old_table);
}
}
}
}
}
if (ret == last_value_removed) {
zmq_assert (_num_prefixes.get () > 0);
_num_prefixes.sub (1);
}
return ret;
}
template <typename T>
template <typename Arg>
void generic_mtrie_t<T>::match (prefix_t data_,
size_t size_,
void (*func_) (value_t *pipe_, Arg arg_),
Arg arg_)
{
for (generic_mtrie_t *current = this; current; data_++, size_--) {
// Signal the pipes attached to this node.
if (current->_pipes) {
for (typename pipes_t::iterator it = current->_pipes->begin (),
end = current->_pipes->end ();
it != end; ++it) {
func_ (*it, arg_);
}
}
// If we are at the end of the message, there's nothing more to match.
if (!size_)
break;
// If there are no subnodes in the trie, return.
if (current->_count == 0)
break;
if (current->_count == 1) {
// If there's one subnode (optimisation).
if (data_[0] != current->_min) {
break;
}
current = current->_next.node;
} else {
// If there are multiple subnodes.
if (data_[0] < current->_min
|| data_[0] >= current->_min + current->_count) {
break;
}
current = current->_next.table[data_[0] - current->_min];
}
}
}
template <typename T> bool generic_mtrie_t<T>::is_redundant () const
{
return !_pipes && _live_nodes == 0;
}
}
#endif
| 24,131
|
C++
|
.h
| 510
| 27.870588
| 95
| 0.410679
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
14,619
|
v3_1_encoder.hpp
|
zeromq_libzmq/src/v3_1_encoder.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_V3_1_ENCODER_HPP_INCLUDED__
#define __ZMQ_V3_1_ENCODER_HPP_INCLUDED__
#include "encoder.hpp"
#include "msg.hpp"
namespace zmq
{
// Encoder for 0MQ framing protocol. Converts messages into data stream.
class v3_1_encoder_t ZMQ_FINAL : public encoder_base_t<v3_1_encoder_t>
{
public:
v3_1_encoder_t (size_t bufsize_);
~v3_1_encoder_t () ZMQ_FINAL;
private:
void size_ready ();
void message_ready ();
unsigned char _tmp_buf[9 + zmq::msg_t::sub_cmd_name_size];
ZMQ_NON_COPYABLE_NOR_MOVABLE (v3_1_encoder_t)
};
}
#endif
| 605
|
C++
|
.h
| 21
| 26.095238
| 73
| 0.699653
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,621
|
wss_address.hpp
|
zeromq_libzmq/src/wss_address.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_WSS_ADDRESS_HPP_INCLUDED__
#define __ZMQ_WSS_ADDRESS_HPP_INCLUDED__
#include "ws_address.hpp"
namespace zmq
{
class wss_address_t : public ws_address_t
{
public:
wss_address_t ();
wss_address_t (const sockaddr *sa_, socklen_t sa_len_);
// The opposite to resolve()
int to_string (std::string &addr_) const;
};
}
#endif
| 395
|
C++
|
.h
| 16
| 22.3125
| 59
| 0.690667
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| true
| true
| true
| false
|
14,622
|
ypipe_conflate.hpp
|
zeromq_libzmq/src/ypipe_conflate.hpp
|
/* SPDX-License-Identifier: MPL-2.0 */
#ifndef __ZMQ_YPIPE_CONFLATE_HPP_INCLUDED__
#define __ZMQ_YPIPE_CONFLATE_HPP_INCLUDED__
#include "platform.hpp"
#include "dbuffer.hpp"
#include "ypipe_base.hpp"
namespace zmq
{
// Adapter for dbuffer, to plug it in instead of a queue for the sake
// of implementing the conflate socket option, which, if set, makes
// the receiving side to discard all incoming messages but the last one.
//
// reader_awake flag is needed here to mimic ypipe delicate behaviour
// around the reader being asleep (see 'c' pointer being NULL in ypipe.hpp)
template <typename T> class ypipe_conflate_t ZMQ_FINAL : public ypipe_base_t<T>
{
public:
// Initialises the pipe.
ypipe_conflate_t () : reader_awake (false) {}
// Following function (write) deliberately copies uninitialised data
// when used with zmq_msg. Initialising the VSM body for
// non-VSM messages won't be good for performance.
#ifdef ZMQ_HAVE_OPENVMS
#pragma message save
#pragma message disable(UNINIT)
#endif
void write (const T &value_, bool incomplete_)
{
(void) incomplete_;
dbuffer.write (value_);
}
#ifdef ZMQ_HAVE_OPENVMS
#pragma message restore
#endif
// There are no incomplete items for conflate ypipe
bool unwrite (T *)
{
return false;
}
// Flush is no-op for conflate ypipe. Reader asleep behaviour
// is as of the usual ypipe.
// Returns false if the reader thread is sleeping. In that case,
// caller is obliged to wake the reader up before using the pipe again.
bool flush ()
{
return reader_awake;
}
// Check whether item is available for reading.
bool check_read ()
{
const bool res = dbuffer.check_read ();
if (!res)
reader_awake = false;
return res;
}
// Reads an item from the pipe. Returns false if there is no value.
// available.
bool read (T *value_)
{
if (!check_read ())
return false;
return dbuffer.read (value_);
}
// Applies the function fn to the first element in the pipe
// and returns the value returned by the fn.
// The pipe mustn't be empty or the function crashes.
bool probe (bool (*fn_) (const T &))
{
return dbuffer.probe (fn_);
}
protected:
dbuffer_t<T> dbuffer;
bool reader_awake;
ZMQ_NON_COPYABLE_NOR_MOVABLE (ypipe_conflate_t)
};
}
#endif
| 2,464
|
C++
|
.h
| 77
| 27.441558
| 79
| 0.670747
|
zeromq/libzmq
| 9,642
| 2,351
| 329
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
14,642
|
Enums.cpp
|
Studio3T_robomongo/src/robomongo/core/Enums.cpp
|
#include "robomongo/core/Enums.h"
#include <string.h>
namespace
{
const char *viewModeAsoc[Robomongo::Custom+1] = {"Text mode", "Tree mode", "Table mode", "Custom mode"};
const char *timesAsoc[Robomongo::LocalTime+1] = {"UTC", "Local Timezone"};
const char *uuidAsoc[Robomongo::PythonLegacy+1] = {"Default encoding", "Java encoding", "CSharp encoding", "Python encoding"};
template<typename type, int size>
inline type findTypeInArray(const char *(&arr)[size], const char *text)
{
for (int i = 0; i < size; ++i )
{
if (strcmp(text, arr[i]) == 0)
{
return static_cast<type>(i);
}
}
return static_cast<type>(0);
}
}
namespace Robomongo
{
const char *convertUUIDEncodingToString(UUIDEncoding uuidCode)
{
return uuidAsoc[uuidCode];
}
UUIDEncoding convertStringToUUIDEncoding(const char *text)
{
return findTypeInArray<UUIDEncoding>(uuidAsoc, text);
}
const char *convertTimesToString(SupportedTimes time)
{
return timesAsoc[time];
}
SupportedTimes convertStringToTimes(const char *text)
{
return findTypeInArray<SupportedTimes>(timesAsoc, text);
}
const char *convertViewModeToString(ViewMode mode)
{
return viewModeAsoc[mode];
}
ViewMode convertStringToViewMode(const char *text)
{
return findTypeInArray<ViewMode>(viewModeAsoc, text);
}
}
| 1,477
|
C++
|
.cpp
| 47
| 25.319149
| 130
| 0.655172
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,643
|
KeyboardManager.cpp
|
Studio3T_robomongo/src/robomongo/core/KeyboardManager.cpp
|
#include "robomongo/core/KeyboardManager.h"
namespace Robomongo
{
bool KeyboardManager::isNewTabShortcut(QKeyEvent *keyEvent)
{
bool ctrlShiftReturn = (keyEvent->modifiers() & Qt::ControlModifier) &&
(keyEvent->modifiers() & Qt::ShiftModifier) &&
(keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter);
// TODO: compare with QKeySequence::AddTab rather than Ctrl+T
bool ctrlT = (keyEvent->modifiers() & Qt::ControlModifier) && !(keyEvent->modifiers() & Qt::ShiftModifier) && (keyEvent->key() == Qt::Key_T);
return ctrlShiftReturn || ctrlT;
}
bool KeyboardManager::isDuplicateTabShortcut(QKeyEvent *keyEvent)
{
bool ctrlShiftT = (keyEvent->modifiers() & Qt::ControlModifier) &&
(keyEvent->modifiers() & Qt::ShiftModifier) &&
(keyEvent->key() == Qt::Key_T);
return ctrlShiftT;
}
bool KeyboardManager::isSetFocusOnQueryLineShortcut(QKeyEvent *keyEvent)
{
return keyEvent->key() == Qt::Key_F6;
}
bool KeyboardManager::isExecuteScriptShortcut(QKeyEvent *keyEvent)
{
return (keyEvent->modifiers() & Qt::ControlModifier)
&&
(keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter);
}
bool KeyboardManager::isAutoCompleteShortcut(QKeyEvent *keyEvent)
{
return (keyEvent->modifiers() & Qt::ControlModifier)
&&
(keyEvent->key() == Qt::Key_Space);
}
bool KeyboardManager::isHideAutoCompleteShortcut(QKeyEvent *keyEvent)
{
return (keyEvent->key() == Qt::Key_Escape);
}
bool KeyboardManager::isNextTabShortcut(QKeyEvent *keyEvent)
{
return (keyEvent->modifiers() & Qt::ControlModifier)
&& (keyEvent->modifiers() & Qt::AltModifier)
&& (keyEvent->key() == Qt::Key_Right);
}
bool KeyboardManager::isPreviousTabShortcut(QKeyEvent *keyEvent)
{
return (keyEvent->modifiers() & Qt::ControlModifier)
&& (keyEvent->modifiers() & Qt::AltModifier)
&& (keyEvent->key() == Qt::Key_Left);
}
bool KeyboardManager::isToggleCommentsShortcut(QKeyEvent *keyEvent)
{
return ((keyEvent->modifiers() & Qt::ControlModifier)
&& (keyEvent->key() == Qt::Key_Slash))
||
((keyEvent->modifiers() & Qt::ControlModifier)
&& (keyEvent->modifiers() & Qt::ShiftModifier)
&& (keyEvent->key() == Qt::Key_C));
}
}
| 2,540
|
C++
|
.cpp
| 61
| 33.360656
| 149
| 0.611449
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,644
|
EventError.cpp
|
Studio3T_robomongo/src/robomongo/core/EventError.cpp
|
#include "robomongo/core/EventError.h"
#include "robomongo/utils/StringOperations.h"
namespace Robomongo
{
EventError::EventError() :
_isNull(true) {}
EventError::EventError(const std::string &errorMessage, ErrorCode errorCode /*= Unknown*/,
bool showErrorWindow /* = true */) :
_errorMessage(captilizeFirstChar(errorMessage)),
_errorCode(errorCode),
_showErrorWindow(showErrorWindow),
_isNull(false) {}
EventError::EventError(const std::string &errorMessage, ReplicaSet const& replicaSetInfo,
bool showErrorWindow /* = true */ ) :
_errorMessage(errorMessage),
_errorCode(SetPrimaryUnreachable),
_replicaSetInfo(replicaSetInfo),
_showErrorWindow(showErrorWindow),
_isNull(false) {}
bool EventError::isNull() const
{
return _isNull;
}
const std::string &EventError::errorMessage() const
{
return _errorMessage;
}
}
| 1,010
|
C++
|
.cpp
| 28
| 28.071429
| 94
| 0.645128
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,647
|
HexUtils.cpp
|
Studio3T_robomongo/src/robomongo/core/HexUtils.cpp
|
#include "robomongo/core/HexUtils.h"
#include <mongo/util/hex.h>
#include <pcrecpp.h>
#include <iostream>
namespace Robomongo
{
namespace HexUtils
{
bool isHexString(const std::string &str)
{
std::size_t i;
for (i = 0; i < str.size(); i++) {
if (!isxdigit(str[i])) {
return false;
}
}
return true;
}
std::string toStdHexLower(const char *raw, int len)
{
const void* in = reinterpret_cast<const void*>(raw);
std::string stdstr = mongo::toHexLower(in, len);
return stdstr;
}
const char *fromHex(const std::string &s, int *outBytes)
{
const int size = s.size();
if (size % 2 != 0)
return NULL;
const int bytes = size / 2; // number of bytes
char *data = new char[bytes];
const char *p = s.c_str();
for (size_t i = 0; i < bytes; i++) {
data[i] = mongo::fromHex(p).getValue();
p += 2;
}
*outBytes = bytes;
return data;
}
std::string hexToUuid(const std::string &hex, UUIDEncoding encoding)
{
switch(encoding) {
case DefaultEncoding: return hexToUuid(hex);
case JavaLegacy: return hexToJavaUuid(hex);
case CSharpLegacy: return hexToCSharpUuid(hex);
case PythonLegacy: return hexToPythonUuid(hex);
default: return hexToUuid(hex);
}
}
std::string hexToUuid(const std::string &hex)
{
std::string uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12);
return uuid;
}
std::string hexToCSharpUuid(const std::string &hex)
{
std::string a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2);
std::string b = hex.substr(10, 2) + hex.substr(8, 2);
std::string c = hex.substr(14, 2) + hex.substr(12, 2);
std::string d = hex.substr(16, 16);
std::string temp = a + b + c + d;
std::string uuid = temp.substr(0, 8) + '-' + temp.substr(8, 4) + '-' + temp.substr(12, 4) + '-' + temp.substr(16, 4) + '-' + temp.substr(20, 12);
return uuid;
}
std::string hexToJavaUuid(const std::string &hex)
{
std::string msb = hex.substr(0, 16);
std::string lsb = hex.substr(16, 16);
msb = msb.substr(14, 2) + msb.substr(12, 2) + msb.substr(10, 2) + msb.substr(8, 2) + msb.substr(6, 2) + msb.substr(4, 2) + msb.substr(2, 2) + msb.substr(0, 2);
lsb = lsb.substr(14, 2) + lsb.substr(12, 2) + lsb.substr(10, 2) + lsb.substr(8, 2) + lsb.substr(6, 2) + lsb.substr(4, 2) + lsb.substr(2, 2) + lsb.substr(0, 2);
std::string temp = msb + lsb;
std::string uuid = temp.substr(0, 8) + '-' + temp.substr(8, 4) + '-' + temp.substr(12, 4) + '-' + temp.substr(16, 4) + '-' + temp.substr(20, 12);
return uuid;
}
std::string hexToPythonUuid(const std::string &hex)
{
return hexToUuid(hex);
}
std::string uuidToHex(const std::string &uuid, Robomongo::UUIDEncoding encoding)
{
switch(encoding) {
case DefaultEncoding: return uuidToHex(uuid);
case JavaLegacy: return javaUuidToHex(uuid);
case CSharpLegacy: return csharpUuidToHex(uuid);
case PythonLegacy: return pythonUuidToHex(uuid);
default: return uuidToHex(uuid);
}
}
std::string uuidToHex(const std::string &uuid)
{
// remove extra characters
std::string hex = uuid;
pcrecpp::RE re("[{}-]");
re.GlobalReplace("", &hex);
if (hex.size() != 32)
return "";
return hex;
}
std::string csharpUuidToHex(const std::string &uuid)
{
// remove extra characters
std::string hex = uuid;
pcrecpp::RE re("[{}-]");
re.GlobalReplace("", &hex);
if (hex.size() != 32)
return "";
std::string a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2);
std::string b = hex.substr(10, 2) + hex.substr(8, 2);
std::string c = hex.substr(14, 2) + hex.substr(12, 2);
std::string d = hex.substr(16, 16);
std::string result = a + b + c + d;
return result;
}
std::string javaUuidToHex(const std::string &uuid)
{
// remove extra characters
std::string hex = uuid;
pcrecpp::RE re("[{}-]");
re.GlobalReplace("", &hex);
if (hex.size() != 32)
return "";
std::string msb = hex.substr(0, 16);
std::string lsb = hex.substr(16, 16);
msb = msb.substr(14, 2) + msb.substr(12, 2) + msb.substr(10, 2) + msb.substr(8, 2) + msb.substr(6, 2) + msb.substr(4, 2) + msb.substr(2, 2) + msb.substr(0, 2);
lsb = lsb.substr(14, 2) + lsb.substr(12, 2) + lsb.substr(10, 2) + lsb.substr(8, 2) + lsb.substr(6, 2) + lsb.substr(4, 2) + lsb.substr(2, 2) + lsb.substr(0, 2);
std::string result = msb + lsb;
return result;
}
std::string pythonUuidToHex(const std::string &uuid)
{
return uuidToHex(uuid);
}
std::string formatUuid(const mongo::BSONElement &element, Robomongo::UUIDEncoding encoding)
{
mongo::BinDataType binType = element.binDataType();
if (binType != mongo::newUUID && binType != mongo::bdtUUID)
throw std::invalid_argument("Binary subtype should be 3 (bdtUUID) or 4 (newUUID)");
int len;
const char *data = element.binData(len);
std::string hex = HexUtils::toStdHexLower(data, len);
if (binType == mongo::bdtUUID) {
std::string uuid = HexUtils::hexToUuid(hex, encoding);
switch(encoding) {
case DefaultEncoding: return "LUUID(\"" + uuid + "\")";
case JavaLegacy: return "JUUID(\"" + uuid + "\")";
case CSharpLegacy: return "NUUID(\"" + uuid + "\")";
case PythonLegacy: return "PYUUID(\"" + uuid + "\")";
default: return "LUUID(\"" + uuid + "\")";
}
} else {
std::string uuid = HexUtils::hexToUuid(hex, DefaultEncoding);
return "UUID(\"" + uuid + "\")";
}
}
}
}
| 6,909
|
C++
|
.cpp
| 156
| 32.339744
| 171
| 0.500074
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,648
|
HexUtils_test.cpp
|
Studio3T_robomongo/src/robomongo/core/HexUtils_test.cpp
|
#include "gtest/gtest.h"
#include "HexUtils.h"
#include <string>
/* Example Test:
*
* TEST( [Test_Case_Name], [Test_Name] )
* TEST( [Test_Case_Name], [UnitOfWorkName_ScenarioUnderTest_ExpectedBehavior] )
* TEST( StringParserTests, NumberLeftOf_StringWithoutNumber_ReturnsFalse) {
// ...
}
*/
TEST(hex_utils_tests, test_1)
{
EXPECT_TRUE(Robomongo::HexUtils::isHexString("a"));
}
| 386
|
C++
|
.cpp
| 15
| 24.2
| 79
| 0.735695
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,649
|
AppRegistry.cpp
|
Studio3T_robomongo/src/robomongo/core/AppRegistry.cpp
|
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/EventBus.h"
#include "robomongo/core/settings/SettingsManager.h"
#include "robomongo/core/domain/App.h"
namespace Robomongo
{
AppRegistry::AppRegistry() :
_bus(new EventBus()),
_settingsManager(new SettingsManager()),
_app(new App(_bus.get()))
{
}
AppRegistry::~AppRegistry()
{
}
}
| 402
|
C++
|
.cpp
| 16
| 20.6875
| 52
| 0.67801
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,650
|
SshTunnelWorker.cpp
|
Studio3T_robomongo/src/robomongo/core/mongodb/SshTunnelWorker.cpp
|
#include "robomongo/core/mongodb/SshTunnelWorker.h"
#include <QThread>
#include <QElapsedTimer>
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/core/utils/Logger.h"
#include "robomongo/core/settings/ConnectionSettings.h"
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/EventBus.h"
#include "robomongo/core/settings/SshSettings.h"
#include "robomongo/core/events/MongoEvents.h"
#include "robomongo/ssh/ssh.h"
#include "robomongo/core/domain/App.h"
namespace Robomongo
{
SshTunnelWorker::SshTunnelWorker(ConnectionSettings *settings) : QObject(),
_settings(settings),
_sshSession(NULL),
_configCreator(settings)
{
_thread = new QThread();
moveToThread(_thread);
VERIFY(connect(_thread, SIGNAL(finished()), _thread, SLOT(deleteLater())));
VERIFY(connect(_thread, SIGNAL(finished()), this, SLOT(deleteLater())));
_thread->start();
}
SshTunnelWorker::~SshTunnelWorker()
{
// QThread "_thread" and MongoWorker itself will be deleted later
// (see MongoWorker() constructor)
delete _settings;
printf("SSH tunnel closed.\n");
}
void SshTunnelWorker::stopAndDelete() {
_isQuiting = 1;
_thread->quit();
}
void SshTunnelWorker::handle(EstablishSshConnectionRequest *event) {
try {
if (_isQuiting)
return;
// Additionally configure "rbm_ssh_tunnel_config"
_configCreator.config()->logcontext = this;
_configCreator.config()->logcallback = &SshTunnelWorker::logCallbackHandler;
_configCreator.config()->loglevel = (rbm_ssh_log_type) _settings->sshSettings()->logLevel(); // RBM_SSH_LOG_TYPE_DEBUG;
if ((_sshSession = rbm_ssh_session_create(_configCreator.config())) == 0) {
// Not much we can say about this error
throw std::runtime_error("Failed to create SSH session");
}
if (rbm_ssh_session_setup(_sshSession) == -1) {
// Prepare copy of error message (if any)
std::string error(_sshSession->lasterror);
std::stringstream ss;
ss << "Failed to create SSH tunnel to "
<< _settings->sshSettings()->host() << ":"
<< _settings->sshSettings()->port() << ".\n\nError:\n"
<< error;
// Cleanup session
rbm_ssh_session_close(_sshSession);
_sshSession = NULL;
throw std::runtime_error(ss.str());
}
reply(event->sender(), new EstablishSshConnectionResponse(
this, event->serverHandle, event->worker, event->settings, event->connectionType, _configCreator.config()->localport));
} catch (const std::exception& ex) {
reply(event->sender(),
new EstablishSshConnectionResponse(this, event->serverHandle, EventError(ex.what()),
event->worker, event->settings, event->connectionType));
// In case of error in connection, we should cleanup SshTunnelWorker
stopAndDelete();
}
}
void SshTunnelWorker::handle(ListenSshConnectionRequest *event) {
try {
if (_isQuiting)
return;
if (_sshSession == NULL)
return;
// We are running this timer in order to distinguish between two
// types of errors:
// 1) SSH tunnel wasn't successfully created
// 2) SSH tunnel was disconnected
// This is used now only for UI error message, that we show to user.
QElapsedTimer timer;
timer.start();
// This function will block until all TCP connections disconnects.
// Initially, it will wait for at least one such connection.
if (rbm_ssh_open_tunnel(_sshSession) != 0) {
qint64 elapsed = timer.elapsed();
bool wasDisconnected = elapsed > 20000; // More than 20 seconds passed
// Prepare copy of error message (if any)
std::string error(_sshSession->lasterror);
std::stringstream ss;
if (wasDisconnected) {
ss << "You are disconnected from SSH tunnel ("
<< _settings->sshSettings()->host() << ":"
<< _settings->sshSettings()->port() << "). "
<< "Please initiate a new connection and reopen all tabs.\n\nError:\n"
<< error;
} else {
ss << "Cannot establish SSH tunnel ("
<< _settings->sshSettings()->host() << ":"
<< _settings->sshSettings()->port() << "). "
<< "\n\nError:\n"
<< error;
}
// Cleanup session
rbm_ssh_session_close(_sshSession);
_sshSession = NULL;
throw std::runtime_error(ss.str());
}
log("SSH tunnel stopped normally.", false);
} catch (const std::exception& ex) {
reply(event->sender(),
new ListenSshConnectionResponse(this, EventError(ex.what()), event->serverHandle, _settings, event->connectionType));
}
// When we done with SSH (i.e. rbm_ssh_open_tunnel exits) regardless
// of the error or success state, we should cleanup SshTunnelWorker.
stopAndDelete();
}
/**
* @brief Send reply event to object 'receiver'
*/
void SshTunnelWorker::reply(QObject *receiver, Event *event)
{
if (_isQuiting)
return;
AppRegistry::instance().bus()->send(receiver, event);
}
void SshTunnelWorker::log(const std::string &message, int level) {
if (_isQuiting)
return;
AppRegistry::instance().bus()->send(
AppRegistry::instance().app(),
new LogEvent(this, message, (LogEvent::LogLevel)level));
}
void SshTunnelWorker::logCallbackHandler(void *context, char *message, int level) {
static_cast<SshTunnelWorker*>(context)->log(message, level);
}
/*
* SshTunnelConfigCreator
*/
SshTunnelConfigCreator::SshTunnelConfigCreator(ConnectionSettings *settings) {
SshSettings *ssh = settings->sshSettings();
// We are going to access raw char* buffers, so prepare copies
// of strings (and rest of the things for symmetry)
_sshhost = ssh->host();
_sshport = ssh->port();
_remotehost = settings->serverHost();
_remoteport = settings->serverPort();
_localip = "127.0.0.1";
_localport = 27040;
_userName = ssh->userName();
_userPassword = ssh->userPassword();
_privateKeyFile = ssh->privateKeyFile();
_publicKeyFile = ssh->publicKeyFile();
_passphrase = ssh->passphrase();
_authMethod = ssh->authMethod(); // "password" or "publickey"
// Use "askedPassword" for both passphrase and password if required
if (ssh->askPassword()) {
_passphrase = ssh->askedPassword();
_userPassword = ssh->askedPassword();
}
_sshConfig = new rbm_ssh_tunnel_config;
_sshConfig->sshserverhost = const_cast<char*>(_sshhost.c_str());
_sshConfig->sshserverport = static_cast<unsigned int>(_sshport);
_sshConfig->remotehost = const_cast<char*>(_remotehost.c_str());
_sshConfig->remoteport = static_cast<unsigned int>(_remoteport);
_sshConfig->localip = const_cast<char*>(_localip.c_str());
_sshConfig->localport = static_cast<unsigned int>(_localport);
_sshConfig->username = const_cast<char*>(_userName.c_str());
_sshConfig->password = const_cast<char*>(_userPassword.c_str());
_sshConfig->privatekeyfile = const_cast<char*>(_privateKeyFile.c_str());
_sshConfig->publickeyfile = _publicKeyFile.empty() ? NULL : const_cast<char*>(_publicKeyFile.c_str());
_sshConfig->passphrase = const_cast<char*>(_passphrase.c_str());
_sshConfig->authtype = (_authMethod == "publickey") ? RBM_SSH_AUTH_TYPE_PUBLICKEY : RBM_SSH_AUTH_TYPE_PASSWORD;
// Default settings
_sshConfig->logcontext = NULL;
_sshConfig->logcallback = NULL;
_sshConfig->loglevel = RBM_SSH_LOG_TYPE_ERROR;
}
SshTunnelConfigCreator::~SshTunnelConfigCreator() {
delete _sshConfig;
}
}
| 8,625
|
C++
|
.cpp
| 184
| 35.836957
| 139
| 0.589805
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,651
|
ReplicaSet.cpp
|
Studio3T_robomongo/src/robomongo/core/mongodb/ReplicaSet.cpp
|
#include "robomongo/core/mongodb/ReplicaSet.h"
namespace Robomongo
{
ReplicaSet::ReplicaSet(std::string const& setName, const mongo::HostAndPort primary,
std::vector<std::pair<std::string, bool>> const& membersAndHealths,
std::string const& errorStr)
: setName(setName), primary(primary), membersAndHealths(membersAndHealths),
errorStr(errorStr)
{}
}
| 471
|
C++
|
.cpp
| 10
| 34.1
| 103
| 0.601307
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,652
|
MongoClient.cpp
|
Studio3T_robomongo/src/robomongo/core/mongodb/MongoClient.cpp
|
#include "robomongo/core/mongodb/MongoClient.h"
#include "mongo/db/namespace_string.h"
#include "robomongo/core/domain/MongoDocument.h"
#include "robomongo/core/utils/BsonUtils.h"
#include "robomongo/shell/bson/json.h"
namespace
{
Robomongo::IndexInfo makeIndexInfoFromBsonObj(
const Robomongo::MongoCollectionInfo &collection,
const mongo::BSONObj &obj)
{
using namespace Robomongo::BsonUtils;
Robomongo::IndexInfo info(collection);
info._name = obj.getStringField("name");
mongo::BSONObj keyObj = obj.getObjectField("key");
if (keyObj.isValid())
info._keys = jsonString(keyObj, mongo::TenGen, 1, Robomongo::DefaultEncoding, Robomongo::Utc);
info._unique = obj.getBoolField("unique");
info._backGround = obj.getBoolField("background");
info._sparse = obj.getBoolField("sparse");
info._ttl = obj.getIntField("expireAfterSeconds");
info._defaultLanguage = obj.getStringField("default_language");
info._languageOverride = obj.getStringField("language_override");
mongo::BSONObj weightsObj = obj.getObjectField("weights");
if (weightsObj.isValid())
info._textWeights = jsonString(weightsObj, mongo::TenGen, 1, Robomongo::DefaultEncoding,
Robomongo::Utc);
return info;
}
}
namespace Robomongo
{
MongoClient::MongoClient(mongo::DBClientBase *const dbclient) :
_dbclient(dbclient) { }
std::vector<std::string> MongoClient::getCollectionNamesWithDbname(const std::string &dbname) const
{
std::list<mongo::BSONObj> collList = _dbclient->getCollectionInfos(dbname);
std::vector<std::string> collNames;
for (auto const& coll : collList)
collNames.push_back(dbname + '.' + coll.getStringField("name")); // todo: verify
std::sort(collNames.begin(), collNames.end());
return collNames;
}
// Warning:
// Use string version dbVersionStr(), version number is corrupted after conversion to float
// Todo: Remove this function
float MongoClient::getVersion() const
{
float result = 0.0f;
mongo::BSONObj resultObj;
_dbclient->runCommand("db", BSON("buildInfo" << "1"), resultObj);
std::string resultStr = BsonUtils::getField<mongo::String>(resultObj, "version");
result = atof(resultStr.c_str());
return result;
}
std::string MongoClient::dbVersionStr() const
{
mongo::BSONObj resultObj;
_dbclient->runCommand("db", BSON("buildInfo" << "1"), resultObj);
std::string const resultStr = BsonUtils::getField<mongo::String>(resultObj, "version");
return resultStr;
}
std::string MongoClient::getStorageEngineType() const
{
mongo::BSONObj resultObj;
_dbclient->runCommand("db", BSON("serverStatus" << "1"), resultObj);
return resultObj.getObjectField("storageEngine").getStringField("name");
}
std::vector<std::string> MongoClient::getDatabaseNames() const
{
std::list<std::string> const& dbs = _dbclient->getDatabaseNames();
std::vector<std::string> dbNames = {dbs.begin(), dbs.end()};
std::sort(dbNames.begin(), dbNames.end());
return dbNames;
}
std::vector<MongoUser> MongoClient::getUsers(const std::string &dbName)
{
mongo::BSONObjBuilder cmd;
cmd.append("usersInfo", 1);
mongo::BSONObj result;
if (!_dbclient->runCommand(dbName, cmd.done(), result)) {
std::string errStr = result.getStringField("errmsg");
if (errStr.empty())
errStr = "Failed to get error message.";
throw std::runtime_error(errStr);
}
std::vector<MongoUser> users;
for (auto const& usr : result.getField("users").Array())
users.push_back(MongoUser(getVersion(), usr.embeddedObject()));
return users;
}
void MongoClient::createUser(const std::string &dbName, const MongoUser &user)
{
mongo::BSONObjBuilder cmd;
cmd.append("createUser", user.name());
cmd.append("pwd", user.password());
mongo::BSONArrayBuilder roles;
auto const& rolesStrs = user.roles();
for (auto const& roleStr : rolesStrs) {
mongo::BSONObjBuilder role;
role.append("role", roleStr).append("db", user.userSource());
roles.append(role.done());
}
cmd.appendArray("roles", roles.done());
mongo::BSONObj result;
if (!_dbclient->runCommand(dbName, cmd.done(), result)) {
std::string errStr = result.getStringField("errmsg");
if (errStr.empty())
errStr = "Failed to get error message.";
throw std::runtime_error(errStr);
}
}
void MongoClient::dropUser(const std::string &dbName, const std::string &user)
{
mongo::BSONObjBuilder cmd;
cmd.append("dropUser", user);
mongo::BSONObj result;
if (!_dbclient->runCommand(dbName, cmd.done(), result)) {
std::string errStr = result.getStringField("errmsg");
if (errStr.empty())
errStr = "Failed to get error message.";
throw std::runtime_error(errStr);
}
}
std::vector<MongoFunction> MongoClient::getFunctions(const std::string &dbName) const
{
std::vector<MongoFunction> functions;
std::unique_ptr<mongo::DBClientCursor> cursor(
_dbclient->query(mongo::NamespaceString(dbName, "system.js"), mongo::Query().sort("_id")));
// Cursor may be NULL, it means we have connectivity problem
if (!cursor)
throw std::runtime_error("Network error while attempting to load list of functions.");
while (cursor->more()) {
mongo::BSONObj bsonObj = cursor->next();
try {
MongoFunction func(bsonObj);
functions.push_back(func);
} catch (const std::exception &) {
// skip invalid docs
}
}
return functions;
}
std::vector<IndexInfo> MongoClient::getIndexes(const MongoCollectionInfo &collection) const
{
std::vector<IndexInfo> result;
std::list<mongo::BSONObj> indexes = _dbclient->getIndexSpecs(collection.ns().toString());
for (std::list<mongo::BSONObj>::iterator it = indexes.begin(); it != indexes.end(); ++it) {
mongo::BSONObj bsonObj = *it;
result.push_back(makeIndexInfoFromBsonObj(collection, bsonObj));
}
return result;
}
void MongoClient::addEditIndex(const IndexInfo &oldInfo, const IndexInfo &newInfo) const
{
bool const editIndex = !oldInfo._name.empty();
// 1.Step: Drop Index (if this is an Edit Index action).
// MongoDB docs: To modify an existing index, you need to drop and recreate the index.
std::string const ns = newInfo._collection.ns().toString();
if (editIndex)
_dbclient->dropIndex(ns, oldInfo._name);
// 2.Step: Add/Edit Index
auto const createIndexSpec = [](IndexInfo const& indexInfo) {
mongo::IndexSpec indexSpec;
indexSpec.name(indexInfo._name);
indexSpec.addKeys(mongo::Robomongo::fromjson(indexInfo._keys));
mongo::BSONObjBuilder optionsBuilder;
auto const addIfTrue = [&](auto const& keyValuePair) {
if (keyValuePair.second)
optionsBuilder.appendBool(keyValuePair.first, true);
};
addIfTrue(std::pair{ "unique", indexInfo._unique });
addIfTrue(std::pair{ "background", indexInfo._backGround });
addIfTrue(std::pair{ "sparse", indexInfo._sparse });
if (!indexInfo._defaultLanguage.empty())
optionsBuilder.append("default_language", indexInfo._defaultLanguage);
if (!indexInfo._languageOverride.empty())
optionsBuilder.append("language_override", indexInfo._languageOverride);
if (!mongo::Robomongo::fromjson(indexInfo._textWeights).isEmpty())
optionsBuilder.append("weights", mongo::Robomongo::fromjson(indexInfo._textWeights));
if (indexInfo._ttl > 0)
optionsBuilder.append("expireAfterSeconds", indexInfo._ttl);
indexSpec.addOptions(optionsBuilder.obj());
return indexSpec;
};
try {
_dbclient->createIndex(ns, createIndexSpec(newInfo));
}
catch (std::exception const& /*ex*/) { // Logging of "ex" is done in upper scope
if (editIndex) {
// If we are here, index that is being edited, must have already been dropped and
// creation of new index failed. So, we try to at least recover the dropped (old) index
_dbclient->createIndex(ns, createIndexSpec(oldInfo));
}
throw;
}
std::string const errorStr = _dbclient->getLastError();
if (!errorStr.empty())
throw std::runtime_error(errorStr);
}
void MongoClient::renameIndexFromCollection(const MongoCollectionInfo &collection, const std::string &oldIndexName, const std::string &newIndexName) const
{
// This is simply an example of how to perform modifications of
// BSON objects. Because BSONObj is immutable, you need to create
// copy of this object, using BSONObjBuilder and BSONObjIterator.
//
// But we need to do not just simple renaming of Index name, we
// also should allow our users to fully modify Index
// (i.e. change name, keys, unique flag, sparse flag etc.)
//
// This should be done using the same dialog as for "Add Index".
MongoNamespace ns(collection.ns().databaseName(), "system.indexes");
std::string systemIndexesNs = ns.toString();
// Building this JSON: { "name" : "oldIndexName" }
mongo::BSONObj query(mongo::BSONObjBuilder()
.append("name", oldIndexName)
.obj());
// Searching for index with "oldIndexName"
// with this query: db.system.indexes.find({ name : "oldIndexName"}
mongo::BSONObj indexBson = _dbclient->findOne(systemIndexesNs, mongo::Query(query));
if (indexBson.isEmpty())
return;
// Here we are building copy of "indexBson" object and
// changing "name" field's value from "oldIndexText" to "newIndexText":
mongo::BSONObjBuilder builder;
mongo::BSONObjIterator i(indexBson);
while (i.more()) {
mongo::BSONElement element = i.next();
if (mongo::StringData(element.fieldName()).compare("name") == 0) {
builder.append("name", newIndexName);
continue;
}
builder.append(element);
}
std::string collectionNs = collection.ns().toString();
_dbclient->dropIndex(collectionNs, oldIndexName);
_dbclient->insert(systemIndexesNs, builder.obj());
}
void MongoClient::dropIndexFromCollection(const MongoCollectionInfo &collection, const std::string &indexName) const
{
_dbclient->dropIndex(collection.ns().toString(), indexName);
}
void MongoClient::createFunction(const std::string &dbName, const MongoFunction &fun,
const std::string &existingFunctionName /* = QString() */)
{
MongoNamespace ns(dbName, "system.js");
mongo::BSONObj obj = fun.toBson();
if (existingFunctionName.empty()) { // create new function
_dbclient->insert(ns.toString(), obj);
std::string errorStr = _dbclient->getLastError();
if (!errorStr.empty())
throw std::runtime_error(errorStr/* , 0 */);
} else { // this is update
std::string name = fun.name();
if (existingFunctionName == name) { // update existing function code
mongo::BSONObjBuilder builder;
builder.append("_id", name);
mongo::BSONObj bsonQuery = builder.obj();
mongo::Query query(bsonQuery);
_dbclient->update(ns.toString(), query, obj, true, false);
std::string errorStr = _dbclient->getLastError();
if (!errorStr.empty())
throw std::runtime_error(errorStr);
} else { // update function name (remove & insert)
_dbclient->insert(ns.toString(), obj);
std::string errorStr = _dbclient->getLastError();
// if no errors
if (errorStr.empty()) {
mongo::BSONObjBuilder builder;
builder.append("_id", existingFunctionName);
mongo::BSONObj bsonQuery = builder.obj();
mongo::Query query(bsonQuery);
_dbclient->remove(ns.toString(), query, true);
}
else {
throw std::runtime_error(errorStr);
}
}
}
}
void MongoClient::dropFunction(const std::string &dbName, const std::string &name)
{
MongoNamespace ns(dbName, "system.js");
mongo::BSONObjBuilder builder;
builder.append("_id", name);
mongo::BSONObj bsonQuery = builder.obj();
mongo::Query query(bsonQuery);
_dbclient->remove(ns.toString(), query, true);
std::string errorStr = _dbclient->getLastError();
if (!errorStr.empty())
throw std::runtime_error(errorStr);
}
void MongoClient::createDatabase(const std::string &dbName)
{
/*
* Here we are going to insert temp document to "<dbName>.temp" collection.
* This will create <dbName> database for us.
* Finally we are dropping just created temporary collection.
*/
MongoNamespace ns(dbName, "temp");
// If <dbName>.temp already exists, stop.
if (_dbclient->exists(ns.toString()))
throw std::runtime_error(dbName + ".temp already exists.");
// Building { _id : "temp" } document
mongo::BSONObjBuilder builder;
builder.append("_id", "temp");
mongo::BSONObj obj = builder.obj();
// Insert this document
_dbclient->insert(ns.toString(), obj);
std::string errorStr = _dbclient->getLastError();
if (!errorStr.empty())
throw std::runtime_error(errorStr);
// Drop temp collection
_dbclient->dropCollection(ns.toString());
}
void MongoClient::dropDatabase(const std::string &dbName)
{
mongo::BSONObj info;
if (!_dbclient->dropDatabase(dbName, mongo::WriteConcernOptions(), &info)) { // todo: do we catch errorStr via info - test it??
std::string errStr = info.toString();
if (errStr.empty())
errStr = "Failed to get error message.";
throw std::runtime_error(errStr);
}
}
void MongoClient::createCollection(const std::string& ns, long long size, bool capped, int max,
const mongo::BSONObj& extraOptions, mongo::BSONObj* info)
{
verify(!capped || size);
mongo::BSONObj o;
if (info == 0)
info = &o;
mongo::BSONObjBuilder b;
std::string db = mongo::nsToDatabase(ns);
b.append("create", ns.c_str() + db.length() + 1);
if (size) {
b.append("size", size);
}
if (capped) {
b.append("capped", true);
}
if (max) {
b.append("max", max);
}
b.appendElements(extraOptions);
if (!_dbclient->exists(ns)) {
mongo::BSONObj result;
if (!_dbclient->runCommand(db.c_str(), b.done(), result)) {
std::string errStr = result.getStringField("errmsg");
if (errStr.empty())
errStr = "Failed to get error message.";
throw std::runtime_error(errStr);
}
}
else {
throw std::runtime_error("Collection with same name already exists.");
}
}
void MongoClient::renameCollection(const MongoNamespace &ns, const std::string &newCollectionName)
{
MongoNamespace from(ns);
MongoNamespace to(ns.databaseName(), newCollectionName);
// Building { renameCollection: <source-namespace>, to: <target-namespace> }
mongo::BSONObjBuilder command; // { collStats: "db.collection", scale : 1 }
command.append("renameCollection", from.toString());
command.append("to", to.toString());
mongo::BSONObj result;
if (!_dbclient->runCommand("admin", command.obj(), result)) { // this command should be run against "admin" db
std::string errStr = result.getStringField("errmsg");
if (errStr.empty())
errStr = "Failed to get error message.";
throw std::runtime_error(errStr);
}
}
void MongoClient::duplicateCollection(const MongoNamespace &ns, const std::string &newCollectionName)
{
MongoNamespace const newCollection(ns.databaseName(), newCollectionName);
if (!_dbclient->exists(newCollection.toString())) {
mongo::BSONObj result;
// todo: Issue #1258 : Duplicate Collection should support advanced collection options.
// _dbclient->createCollection() should be called with properties of source collection
// not with default parameters as below.
if (!_dbclient->createCollection(newCollection.toString(), 0, false, 0, &result)) {
std::string errStr = result.getStringField("errmsg");
if (errStr.empty())
errStr = "Failed to get error message.";
throw std::runtime_error(errStr);
}
}
else {
throw std::runtime_error("Collection with same name already exists.");
}
std::unique_ptr<mongo::DBClientCursor> cursor {
_dbclient->query(mongo::NamespaceString(ns.databaseName(), ns.collectionName()), mongo::Query())
};
// Cursor may be NULL, it means we have connectivity problem
if (!cursor)
throw std::runtime_error("Network error while attempting to run query");
while (cursor->more()) {
mongo::BSONObj bsonObj = cursor->next();
_dbclient->insert(newCollection.toString(), bsonObj);
}
}
void MongoClient::copyCollectionToDiffServer(mongo::DBClientBase *const fromServ, const MongoNamespace &from,
const MongoNamespace &to)
{
if (!_dbclient->exists(to.toString()))
_dbclient->createCollection(to.toString());
std::unique_ptr<mongo::DBClientCursor> cursor{fromServ->query(
mongo::NamespaceString(from.databaseName(), from.collectionName()),
mongo::Query())
};
// Cursor may be NULL, it means we have connectivity problem
if (!cursor)
throw std::runtime_error("Network error while attempting to run query");
while (cursor->more()) {
mongo::BSONObj bsonObj = cursor->next();
_dbclient->insert(to.toString(), bsonObj);
}
}
void MongoClient::dropCollection(const MongoNamespace &ns)
{
if (_dbclient->exists(ns.toString())) {
mongo::BSONObj info;
if (!_dbclient->dropCollection(ns.toString(), mongo::WriteConcernOptions(), &info)) {
std::string errStr = info.toString();
if (errStr.empty())
errStr = "Failed to get error message.";
throw std::runtime_error(errStr);
}
}
else {
throw std::runtime_error("Collection does not exist.");
}
}
void MongoClient::insertDocument(const mongo::BSONObj &obj, const MongoNamespace &ns)
{
_dbclient->insert(ns.toString(), obj);
checkLastErrorAndThrow(ns.databaseName());
}
void MongoClient::saveDocument(const mongo::BSONObj &obj, const MongoNamespace &ns)
{
mongo::BSONElement id = obj.getField("_id");
mongo::BSONObjBuilder builder;
builder.append(id);
mongo::BSONObj bsonQuery = builder.obj();
mongo::Query query(bsonQuery);
_dbclient->update(ns.toString(), query, obj, true, false);
checkLastErrorAndThrow(ns.databaseName());
}
void MongoClient::removeDocuments(const MongoNamespace &ns, mongo::Query query, bool justOne /*= true*/)
{
_dbclient->remove(ns.toString(), query, justOne);
checkLastErrorAndThrow(ns.databaseName());
}
std::vector<MongoDocumentPtr> MongoClient::query(const MongoQueryInfo &info)
{
MongoNamespace ns(info._info._ns);
//int limit = (info.limit <= 0) ? 50 : info.limit;
std::vector<MongoDocumentPtr> docs;
if (info._limit == -1) // it means that we do not need to load any documents
return docs;
std::unique_ptr<mongo::DBClientCursor> cursor = _dbclient->query(
mongo::NamespaceString(ns.databaseName(), ns.collectionName()),
info._query, info._limit, info._skip, info._fields.nFields() ? &info._fields : 0,
info._options, info._batchSize
);
// DBClientBase::query may return nullptr
if (!cursor)
throw std::runtime_error("Network error while attempting to run query");
while (cursor->more()) {
mongo::BSONObj bsonObj = cursor->next();
MongoDocumentPtr doc(new MongoDocument(bsonObj.getOwned()));
docs.push_back(doc);
}
return docs;
}
MongoCollectionInfo MongoClient::runCollStatsCommand(const std::string &ns)
{
MongoCollectionInfo info(ns);
return info;
/* // Commented for now, to speedup load of collection names
MongoNamespace mongons(ns);
mongo::BSONObjBuilder command; // { collStats: "db.collection", scale : 1 }
command.append("collStats", mongons.collectionName());
command.append("scale", 1);
mongo::BSONObj result;
_dbclient->runCommand(mongons.databaseName(), command.obj(), result);
std::string isCV = result.toString();
MongoCollectionInfo newInfo(result);
return newInfo;
*/
}
std::vector<MongoCollectionInfo> MongoClient::runCollStatsCommand(const std::vector<std::string> &namespaces)
{
std::vector<MongoCollectionInfo> infos;
for (auto const& ns : namespaces) {
MongoCollectionInfo info = runCollStatsCommand(ns);
if (info.ns().isValid())
infos.push_back(info);
}
return infos;
}
void MongoClient::done()
{
// do nothing here, because we are not using ScopedDbConnection now
//_scopedConnection->done();
}
void MongoClient::checkLastErrorAndThrow(const std::string &db)
{
std::string const lastError = _dbclient->getLastError(db);
if (lastError.empty())
return;
throw std::runtime_error(lastError/*, mongo::ErrorCodes::InternalError*/);
}
}
| 23,543
|
C++
|
.cpp
| 516
| 35.313953
| 158
| 0.605972
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,653
|
MongoWorker.cpp
|
Studio3T_robomongo/src/robomongo/core/mongodb/MongoWorker.cpp
|
#include "robomongo/core/mongodb/MongoWorker.h"
#include <algorithm>
#include <exception>
#include <QThread>
#include <mongo/client/global_conn_pool.h>
#include <mongo/client/replica_set_monitor.h>
#include <mongo/util/net/ssl_manager.h>
#include <mongo/util/net/ssl_options.h>
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/domain/App.h"
#include "robomongo/core/domain/MongoShellResult.h"
#include "robomongo/core/domain/MongoCollectionInfo.h"
#include "robomongo/core/events/MongoEvents.h"
#include "robomongo/core/engine/ScriptEngine.h"
#include "robomongo/core/EventBus.h"
#include "robomongo/core/mongodb/MongoClient.h"
#include "robomongo/core/settings/ConnectionSettings.h"
#include "robomongo/core/settings/ReplicaSetSettings.h"
#include "robomongo/core/settings/CredentialSettings.h"
#include "robomongo/core/settings/SettingsManager.h"
#include "robomongo/core/settings/SslSettings.h"
#include "robomongo/core/utils/BsonUtils.h"
#include "robomongo/core/utils/Logger.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/utils/StringOperations.h"
namespace Robomongo
{
std::string const APP_VERSION = PROJECT_VERSION;
std::string const APP_NAME_VERSION { "robo3t-" + APP_VERSION };
MongoWorker::MongoWorker(ConnectionSettings *connection, bool isLoadMongoRcJs, int batchSize,
double mongoTimeoutSec, int shellTimeoutSec, QObject *parent)
: QObject(parent),
_scriptEngine(nullptr),
_isLoadMongoRcJs(isLoadMongoRcJs),
_batchSize(batchSize),
_timerId(-1),
_dbAutocompleteCacheTimerId(-1),
_mongoTimeoutSec(mongoTimeoutSec),
_shellTimeoutSec(shellTimeoutSec),
_isQuiting(0),
_dbclient(nullptr),
_dbclientRepSet(nullptr),
_connSettings(connection)
{
// Whitespace removed from the start and the end of host string
_connSettings->setServerHost(QString::fromStdString(_connSettings->serverHost()).trimmed().toStdString());
_thread = new QThread();
moveToThread(_thread);
VERIFY(connect( _thread, SIGNAL(finished()), _thread, SLOT(deleteLater()) ));
VERIFY(connect( _thread, SIGNAL(finished()), this, SLOT(deleteLater()) ));
_thread->start();
}
void MongoWorker::timerEvent(QTimerEvent *event)
{
if (_timerId == event->timerId()) {
keepAlive();
return;
}
if (_dbAutocompleteCacheTimerId == event->timerId() && !_scriptEngine) {
_scriptEngine->invalidateDbCollectionsCache();
return;
}
}
void MongoWorker::restartReplicaSetConnection()
{
if (!_connSettings->hasEnabledPrimaryCredential())
return;
CredentialSettings *credentials = _connSettings->primaryCredential();
mongo::BSONObj authParams {
mongo::BSONObjBuilder()
.append("user", credentials->userName())
.append("db", credentials->databaseName())
.append("pwd", credentials->userPassword())
.append("mechanism", credentials->mechanism())
.obj()
};
_dbclientRepSet.release();
if(mongo::DBClientBase *conn = getConnection(true).first)
conn->auth(authParams);
}
void MongoWorker::keepAlive()
{
try {
if (_dbclient)
pingDatabase(_dbclient.get());
if (_dbclientRepSet)
pingDatabase(_dbclientRepSet.get());
if (_scriptEngine)
_scriptEngine->ping();
}
catch(std::exception &ex) {
sendLog(this, LogEvent::RBM_WARN,
"Failed to ping the server. " + std::string(ex.what()));
}
}
void MongoWorker::init()
{
try {
_scriptEngine.reset(new ScriptEngine(_connSettings, _shellTimeoutSec));
_scriptEngine->init(_isLoadMongoRcJs);
_scriptEngine->use(_connSettings->defaultDatabase());
_scriptEngine->setBatchSize(_batchSize);
constexpr int PING_INTERVAL_MSEC { 60 * 1000 }; // 60 seconds
_timerId = startTimer(PING_INTERVAL_MSEC);
_dbAutocompleteCacheTimerId = startTimer(30000);
} catch (const std::exception &ex) {
auto const msg { "Failed to initialize MongoWorker. Reason: "};
sendLog(this, LogEvent::RBM_ERROR, msg + std::string(ex.what()));
throw std::runtime_error(msg + std::string(ex.what()));
}
}
void MongoWorker::interrupt() {
try {
if (_isQuiting || !_scriptEngine)
return;
_scriptEngine->interrupt();
} catch(const std::exception &ex) {
sendLog(this, LogEvent::RBM_ERROR, std::string(ex.what()));
}
}
MongoWorker::~MongoWorker()
{
if (_timerId != -1)
killTimer(_timerId);
if (_dbAutocompleteCacheTimerId != -1)
killTimer(_dbAutocompleteCacheTimerId);
delete _connSettings;
// QThread "_thread" and MongoWorker itself will be deleted later
// (see MongoWorker() constructor)
}
void MongoWorker::stopAndDelete()
{
_isQuiting = 1;
_thread->quit();
}
void MongoWorker::changeTimeout(int newTimeout)
{
_scriptEngine->changeTimeout(newTimeout);
}
/**
* @brief Initiate connection to MongoDB
*/
bool MongoWorker::handle(EstablishConnectionRequest *event)
{
QMutexLocker lock(&_firstConnectionMutex);
std::unique_ptr<ReplicaSet> repSetInfo(new ReplicaSet);
auto errorCode = EventError::ErrorCode::Unknown;
try {
auto const& connAndErrorStr = getConnection(true);
mongo::DBClientBase *conn = connAndErrorStr.first;
// --- Connection failed for single server & replica set (no member of the set is reachable)
if (!conn)
{
auto errorReason = std::string("Connection failure: Unknown error.");
auto const& connErrorStr = connAndErrorStr.second;
if (_connSettings->sslSettings()->sslEnabled())
errorReason =
"TLS tunnel failure: Network is unreachable or TLS connection rejected by server." +
(connErrorStr.empty() ? "" : " Reason: " + connErrorStr);
else { // Non-TLS connections
if (_connSettings->isReplicaSet()) {
errorReason = "No member of the set is reachable." +
(connErrorStr.empty() ? "" : " Reason: " + connErrorStr);
std::vector<std::pair<std::string, bool>> membersAndHealths;
for (auto const& member : _connSettings->replicaSetSettings()->members())
membersAndHealths.push_back({ member, false });
repSetInfo.reset(new ReplicaSet("", mongo::HostAndPort(), membersAndHealths, errorReason));
}
else // single server
errorReason = "Network is unreachable." + (connErrorStr.empty() ? "" : " Reason: " + connErrorStr);
}
resetGlobalSSLparams();
reply(event->sender(), new EstablishConnectionResponse(this, EventError(errorReason, errorCode),
event->connectionType, event->uuid, *repSetInfo.release(),
EstablishConnectionResponse::MongoConnection));
return false;
}
// --- Single server: Connection successful
// --- Replica set: Connection successful (primary reachable) or
// Connection failed (primary unreachable with at least one reachable member)
if (_connSettings->isReplicaSet()) {
ReplicaSet const& setInfo = getReplicaSetInfo();
// Check if same set name used with different members which is not supported
auto const& members = _connSettings->replicaSetSettings()->members();
if (std::find(members.cbegin(), members.cend(), setInfo.primary.toString()) == members.cend())
{ // primary not found between user entered members
std::string const errorStr {
"Different members found under same replica set name \"" +
setInfo.setName + "\"."
};
repSetInfo.reset(new ReplicaSet(setInfo));
errorCode = EventError::ErrorCode::ServerHasDifferentMembers;
sendLog(this, LogEvent::RBM_ERROR, errorStr);
throw std::runtime_error(errorStr);
}
if (setInfo.primary.empty()) { // No reachable primary
// Pass possible reachable secondary(ies) info
repSetInfo.reset(new ReplicaSet(setInfo));
sendLog(this, LogEvent::RBM_ERROR, setInfo.errorStr);
throw std::runtime_error(setInfo.errorStr);
}
else { // Primary is reachable, save setInfo and continue
repSetInfo.reset(new ReplicaSet(setInfo));
}
}
if (_connSettings->hasEnabledPrimaryCredential()) {
CredentialSettings const * const credentials = _connSettings->primaryCredential();
// Building BSON object:
mongo::BSONObj const authParams {
mongo::BSONObjBuilder()
.append("user", credentials->userName())
.append("db", credentials->databaseName())
.append("pwd", credentials->userPassword())
.append("mechanism", credentials->mechanism())
.obj()
};
conn->auth(authParams);
}
boost::scoped_ptr<MongoClient> client(getClient());
std::vector<std::string> const dbNames = getDatabaseNamesSafe(event);
// If we do not have databases, it means that we are unable to
// execute "listdatabases" command and we have nothing to show.
if (dbNames.size() == 0)
throw std::runtime_error("Failed to execute \"listdatabases\" command.");
if (!_connSettings->isReplicaSet())
init(); // Init MongoWorker for single server (for replica set connections early init is used)
resetGlobalSSLparams();
auto connInfo = ConnectionInfo(_connSettings->getFullAddress(), dbNames, client->getVersion(),
client->dbVersionStr(), client->getStorageEngineType(), event->uuid);
// todo: two ctors for rep.set and single server.
reply(event->sender(), new EstablishConnectionResponse(this, connInfo, event->connectionType,
*repSetInfo.release()));
return true;
}
catch(const std::exception &ex) {
resetGlobalSSLparams();
auto errorReason = _connSettings->sslSettings()->sslEnabled() ?
EstablishConnectionResponse::ErrorReason::MongoSslConnection :
EstablishConnectionResponse::ErrorReason::MongoAuth;
reply(event->sender(), new EstablishConnectionResponse(this, EventError(ex.what(), errorCode),
event->connectionType, ConnectionInfo(event->uuid), *repSetInfo.release(), errorReason));
sendLog(this, LogEvent::RBM_ERROR, ex.what()); // todo: duplicate logging?
}
return false;
}
void MongoWorker::handle(RefreshReplicaSetFolderRequest *event)
{
configureSSL();
try {
ReplicaSet const& replicaSetInfo = getReplicaSetInfo();
// Primary is unreachable, but there might be reachable secondary(ies)
if (replicaSetInfo.primary.empty()) {
reply(
event->sender(),
new RefreshReplicaSetFolderResponse(
this, replicaSetInfo, event->expanded, EventError(replicaSetInfo.errorStr)
)
);
sendLog(this, LogEvent::RBM_ERROR, replicaSetInfo.errorStr);
return;
}
else { // Primary is reachable
reply(event->sender(),
new RefreshReplicaSetFolderResponse(this, replicaSetInfo, event->expanded));
}
}
catch (const std::exception &ex) {
reply(
event->sender(),
new RefreshReplicaSetFolderResponse(
this, ReplicaSet(), event->expanded, EventError(ex.what())
)
);
sendLog(this, LogEvent::RBM_ERROR, ex.what());
}
}
std::string MongoWorker::getAuthBase() const
{
if (_connSettings->hasEnabledPrimaryCredential())
return _connSettings->primaryCredential()->databaseName();
return std::string();
}
std::vector<std::string> MongoWorker::getDatabaseNamesSafe(EstablishConnectionRequest* event /*= nullptr*/)
{
std::set<std::string> dbNames;
auto const primaryCredential { _connSettings->primaryCredential() };
try {
boost::scoped_ptr<MongoClient> client(getClient());
std::vector<std::string> dbNamesFetched { client->getDatabaseNames() };
dbNames = std::set<std::string> { dbNamesFetched.cbegin(), dbNamesFetched.cend() };
}
catch(const std::exception &ex) {
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wlogical-op-parentheses"
#endif
bool const informUser {
event != nullptr &&
event->connectionType == ConnectionType::ConnectionPrimary &&
_connSettings->credentialCount() > 0 &&
!primaryCredential->useManuallyVisibleDbs() ||
primaryCredential->manuallyVisibleDbs().empty()
};
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
std::string const hint {
"\n\nHint: If this user has access to a specific database, "
"please use \"Manually specify visible databases\" option in "
"Connection Settings window -> Authentication tab."
};
sendLog(this, LogEvent::RBM_WARN, ex.what() + hint, informUser);
}
if (_connSettings->credentialCount() > 0 &&
primaryCredential->useManuallyVisibleDbs() &&
!primaryCredential->manuallyVisibleDbs().empty()
)
{
QString const manuallyVisibleDbs {
QString::fromStdString(primaryCredential->manuallyVisibleDbs())
};
for (auto const& db : manuallyVisibleDbs.split(',').toStdList())
dbNames.insert(db.toStdString());
}
std::string const authBase = getAuthBase();
if (!authBase.empty())
dbNames.insert(authBase);
return std::vector<std::string> { dbNames.cbegin(), dbNames.cend() };
}
/**
* @brief Load list of all database names
*/
void MongoWorker::handle(LoadDatabaseNamesRequest *event)
{
try {
// If user not an admin - he doesn't have access to mongodb 'listDatabases' command
// Non admin user has access only to the single database he specified while performing auth.
std::vector<std::string> dbNames = getDatabaseNamesSafe();
// Remove from list of created databases existing databases
for (std::vector<std::string>::iterator it = dbNames.begin(); it != dbNames.end(); ++it) {
std::unordered_set<std::string>::const_iterator exists = _createdDbs.find(*it);
if (exists != _createdDbs.end()) {
_createdDbs.erase(*it);
}
}
// Merge with list of created databases
for (std::unordered_set<std::string>::iterator it = _createdDbs.begin(); it != _createdDbs.end(); ++it) {
dbNames.push_back(*it);
}
if (dbNames.size()) {
reply(event->sender(), new LoadDatabaseNamesResponse(this, dbNames));
} else {
auto const errorStr{ "Failed to execute \"listdatabases\" command." };
reply(event->sender(), new LoadDatabaseNamesResponse(this, EventError(errorStr)));
}
} catch(const std::exception &ex) {
reply(event->sender(), new LoadDatabaseNamesResponse(this, EventError(ex.what())));
sendLog(this, LogEvent::RBM_ERROR, ex.what());
}
}
/**
* @brief Load list of all collection names
*/
void MongoWorker::handle(LoadCollectionNamesRequest *event)
{
try {
boost::scoped_ptr<MongoClient> client(getClient());
auto const& namespaces = client->getCollectionNamesWithDbname(event->databaseName());
std::vector<MongoCollectionInfo> const& collInfos = client->runCollStatsCommand(namespaces);
client->done();
reply(event->sender(), new LoadCollectionNamesResponse(this, event->databaseName(), collInfos));
} catch(const std::exception &ex) {
reply(event->sender(), new LoadCollectionNamesResponse(this, EventError(ex.what())));
// Logging handled in main thread
}
}
void MongoWorker::handle(LoadUsersRequest *event)
{
try {
boost::scoped_ptr<MongoClient> client(getClient());
const std::vector<MongoUser> &users = client->getUsers(event->databaseName());
client->done();
reply(event->sender(), new LoadUsersResponse(this, event->databaseName(), users));
} catch(const std::exception &ex) {
reply(event->sender(), new LoadUsersResponse(this, EventError(ex.what())));
// Logging handled in main thread
}
}
void MongoWorker::handle(LoadCollectionIndexesRequest *event)
{
try {
boost::scoped_ptr<MongoClient> client(getClient());
const std::vector<IndexInfo> &ind = client->getIndexes(event->collection());
client->done();
reply(event->sender(), new LoadCollectionIndexesResponse(this, ind));
} catch(const std::exception &ex) {
reply(event->sender(), new LoadCollectionIndexesResponse(this, EventError(ex.what())));
sendLog(this, LogEvent::RBM_ERROR, ex.what());
}
}
void MongoWorker::handle(AddEditIndexRequest *event)
{
const IndexInfo &newIndex = event->newInfo();
const IndexInfo &oldIndex = event->oldInfo();
try {
boost::scoped_ptr<MongoClient> client(getClient());
client->addEditIndex(oldIndex, newIndex);
client->done();
reply(event->sender(), new AddEditIndexResponse(this, oldIndex, newIndex));
std::vector<IndexInfo> const &indexes = client->getIndexes(newIndex._collection);
reply(event->sender(), new LoadCollectionIndexesResponse(this, indexes));
} catch(const std::exception &ex) {
reply(event->sender(),
new AddEditIndexResponse(this, EventError(ex.what()), oldIndex, newIndex)
);
// Logging handled in main thread
}
}
void MongoWorker::handle(DropCollectionIndexRequest *event)
{
try {
boost::scoped_ptr<MongoClient> client(getClient());
client->dropIndexFromCollection(event->collection(), event->index());
client->done();
reply(event->sender(),
new DropCollectionIndexResponse(this, event->collection(), event->index()));
} catch(const std::exception &ex) {
reply(event->sender(),
new DropCollectionIndexResponse(this, EventError(ex.what()), event->index()));
// Logging handled in main thread
}
}
void MongoWorker::handle(LoadFunctionsRequest *event)
{
try {
boost::scoped_ptr<MongoClient> client(getClient());
const std::vector<MongoFunction> &funcs = client->getFunctions(event->databaseName());
client->done();
// If list of functions from client is empty, try getting it with script engine
if (funcs.empty()) {
MongoShellExecResult const& result = _scriptEngine->exec("db.system.js.find()", event->databaseName());
std::vector<MongoFunction> functions;
if (!result.results().empty()) {
auto const& resultDocs = result.results().front().documents();
for (auto const res : resultDocs)
functions.push_back(MongoFunction(res->bsonObj()));
}
reply(event->sender(), new LoadFunctionsResponse(this, event->databaseName(), functions));
return;
}
reply(event->sender(), new LoadFunctionsResponse(this, event->databaseName(), funcs));
} catch(const std::exception &ex) {
reply(event->sender(), new LoadFunctionsResponse(this, EventError(ex.what())));
// Logging handled in main thread
}
}
void MongoWorker::handle(InsertDocumentRequest *event)
{
try {
boost::scoped_ptr<MongoClient> client(getClient());
if (event->overwrite())
client->saveDocument(event->obj(), event->ns());
else
client->insertDocument(event->obj(), event->ns());
client->done();
reply(event->sender(), new InsertDocumentResponse(this));
}
catch(const std::exception &ex) {
reply(event->sender(), new InsertDocumentResponse(this, EventError(ex.what())));
sendLog(this, LogEvent::RBM_ERROR, ex.what());
}
}
void MongoWorker::handle(RemoveDocumentRequest *event)
{
try {
boost::scoped_ptr<MongoClient> client(getClient());
client->removeDocuments(event->ns(), event->query(),
event->removeCount() == RemoveDocumentCount::ONE);
client->done();
reply(event->sender(), new RemoveDocumentResponse(this, event->removeCount(), event->index()));
}
catch(const std::exception &ex) {
reply(event->sender(), new RemoveDocumentResponse(this, EventError(ex.what()),
event->removeCount(), event->index()));
// Logging handled in main thread
}
}
void MongoWorker::handle(ExecuteQueryRequest *event)
{
auto const executeQuery = [&]() {
boost::scoped_ptr<MongoClient> client { getClient() };
std::vector<MongoDocumentPtr> docs = client->query(event->queryInfo());
client->done();
reply(event->sender(),
new ExecuteQueryResponse(this, event->resultIndex(), event->queryInfo(), docs)
);
};
try {
executeQuery();
} catch(const std::exception &ex) {
QString const NTORETURN_ERROR { "unrecognized field: 'ntoreturn'" };
bool const ntoreturnError {
QString(ex.what()).compare(NTORETURN_ERROR, Qt::CaseInsensitive) == 0
};
// If we have this DocumentDB specific error, try again
if (ntoreturnError && _dbclient) {
sendLog(this, LogEvent::RBM_ERROR, std::string(ex.what()));
try {
_dbclient->tagAsDocDb(true);
executeQuery();
return;
}
catch (const std::exception &ex) {
sendLog(this, LogEvent::RBM_ERROR, "Re-try: " + std::string(ex.what()));
}
}
reply(event->sender(), new ExecuteQueryResponse(this, EventError(ex.what())));
sendLog(this, LogEvent::RBM_ERROR, std::string(ex.what()));
}
}
/**
* @brief Execute javascript
*/
void MongoWorker::handle(ExecuteScriptRequest *event)
{
try {
if(!_scriptEngine ||
(_connSettings->isReplicaSet() && !_dbclientRepSet)) {
auto const error{
EventError("MongoDB Shell was not initialized or connection failure")
};
reply(event->sender(), new ExecuteScriptResponse(this, error));
return;
}
// Try to handle case where new shell (which was opened when server unreachable)
// was re-executed
if (_scriptEngine->failedScope()) {
try {
_scriptEngine->init(_isLoadMongoRcJs);
}
catch (std::exception const& ex) {
sendLog(this, LogEvent::RBM_ERROR,
captilizeFirstChar(ex.what()) + ", cannot init mongo scope");
}
}
// todo: should we use dbName from event or _connSettings?
MongoShellExecResult result {
_scriptEngine->exec(
event->script, _connSettings->defaultDatabase(), event->aggrInfo
)
};
// To fix the problem where 'result' comes with old primary address.
if (_connSettings->isReplicaSet())
result.setCurrentServer(
_dbclientRepSet->getSuspectedPrimaryHostAndPort().toString()
);
if (!result.error()) {
reply(
event->sender(),
new ExecuteScriptResponse(this, result, event->script.empty(),
result.timeoutReached()) // todo: rename to shellTimeout...
);
return;
}
retry(event);
}
catch(const std::exception &ex) {
auto const error { EventError(ex.what(), EventError::Unknown) };
reply(event->sender(), new ExecuteScriptResponse(this, error));
sendLog(this, LogEvent::RBM_ERROR, ex.what());
}
}
void MongoWorker::retry(ExecuteScriptRequest * event)
{
mongo::DBClientBase* mongodbClient {
_dbclient ? _dbclient.get() :
dynamic_cast<mongo::DBClientBase*>(_dbclientRepSet.get())
};
if (!mongodbClient->isStillConnected())
mongodbClient->checkConnection();
MongoShellExecResult const result {
_scriptEngine->exec(event->script, _connSettings->defaultDatabase())
};
if (result.error()) {
auto const error { EventError(result.errorMessage()) };
reply(event->sender(), new ExecuteScriptResponse(this, error));
}
else {
reply(
event->sender(),
new ExecuteScriptResponse(this, result, event->script.empty(),
result.timeoutReached())
);
}
}
/**
* @brief Interrupt javascript execution
*/
void MongoWorker::handle(StopScriptRequest *)
{
try {
if (!_scriptEngine) {
return;
}
_scriptEngine->interrupt();
} catch(const std::exception &ex) {
sendLog(this, LogEvent::RBM_ERROR, std::string(ex.what()));
}
}
void MongoWorker::handle(AutocompleteRequest *event)
{
try {
if (!_scriptEngine) {
reply(event->sender(),
new AutocompleteResponse(this, EventError("MongoDB Shell was not initialized")));
return;
}
QStringList list = _scriptEngine->complete(event->prefix, event->mode);
reply(event->sender(), new AutocompleteResponse(this, list, event->prefix));
} catch(const std::exception &ex) {
reply(event->sender(), new AutocompleteResponse(this, EventError(ex.what())));
sendLog(this, LogEvent::RBM_ERROR, std::string(ex.what()));
}
}
void MongoWorker::handle(CreateDatabaseRequest *event)
{
std::string dbname = event->database();
try {
boost::scoped_ptr<MongoClient> client(getClient());
client->createDatabase(dbname);
// Insert to list of created database. Read docs for this hashset in the header
_createdDbs.insert(dbname);
reply(event->sender(), new CreateDatabaseResponse(this, dbname));
} catch(const std::exception &ex) {
reply(event->sender(), new CreateDatabaseResponse(this, dbname,
EventError(ex.what()))
);
// Logging handled in main thread
}
}
void MongoWorker::handle(DropDatabaseRequest *event)
{
try {
boost::scoped_ptr<MongoClient> client(getClient());
client->dropDatabase(event->database);
// Remove from the list of created database, Read docs for this hashset in the header
_createdDbs.erase(event->database);
reply(event->sender(), new DropDatabaseResponse(this, event->database));
}
catch(const std::exception &ex) {
reply(event->sender(),
new DropDatabaseResponse(this, event->database, EventError(ex.what()))
);
// Logging handled in main thread
}
}
void MongoWorker::handle(CreateCollectionRequest *event)
{
std::string const& collection = event->ns().collectionName();
try {
boost::scoped_ptr<MongoClient> client(getClient());
client->createCollection(event->ns().toString(), event->getSize(), event->getCapped(),
event->getMaxDocNum(), event->getExtraOptions());
client->done();
reply(event->sender(), new CreateCollectionResponse(this, collection));
} catch(const std::exception &ex) {
reply(event->sender(),
new CreateCollectionResponse(this, collection, EventError(ex.what()))
);
// Logging handled in main thread
}
}
void MongoWorker::handle(DropCollectionRequest *event)
{
std::string const& collection = event->ns().collectionName();
try {
boost::scoped_ptr<MongoClient> client(getClient());
client->dropCollection(event->ns());
client->done();
reply(event->sender(), new DropCollectionResponse(this, collection));
} catch(const std::exception &ex) {
reply(event->sender(),
new DropCollectionResponse(this, collection, EventError(ex.what()))
);
// Logging handled in main thread
}
}
void MongoWorker::handle(RenameCollectionRequest *event)
{
try {
boost::scoped_ptr<MongoClient> client(getClient());
client->renameCollection(event->ns(), event->newCollection());
client->done();
reply(event->sender(), new RenameCollectionResponse(this, event->ns().collectionName(),
event->newCollection()));
} catch(const std::exception &ex) {
reply(event->sender(), new RenameCollectionResponse(this, EventError(ex.what())));
// Logging handled in main thread
}
}
void MongoWorker::handle(DuplicateCollectionRequest *event)
{
std::string const& sourceCollection = event->ns().collectionName();
try {
boost::scoped_ptr<MongoClient> client(getClient());
client->duplicateCollection(event->ns(), event->newCollection());
client->done();
reply(event->sender(),
new DuplicateCollectionResponse(this, sourceCollection, event->newCollection())
);
}
catch (const std::exception &ex) {
reply(event->sender(),
new DuplicateCollectionResponse(this, sourceCollection, EventError(ex.what()))
);
// Logging handled in main thread
}
}
void MongoWorker::handle(CopyCollectionToDiffServerRequest *event)
{
try {
boost::scoped_ptr<MongoClient> client(getClient());
MongoWorker *cl = event->worker();
client->copyCollectionToDiffServer(
cl->_dbclient.get(), event->from(), event->to()
);
client->done();
reply(event->sender(), new CopyCollectionToDiffServerResponse(this));
} catch(const std::exception &ex) {
reply(event->sender(),
new CopyCollectionToDiffServerResponse(this, EventError(ex.what()))
);
sendLog(this, LogEvent::RBM_ERROR, std::string(ex.what()));
}
}
void MongoWorker::handle(CreateUserRequest *event)
{
try {
boost::scoped_ptr<MongoClient> client(getClient());
client->createUser(event->database(), event->user());
client->done();
reply(event->sender(), new CreateUserResponse(this, event->user().name()));
} catch(const std::exception &ex) {
reply(event->sender(),
new CreateUserResponse(this, event->user().name(), EventError(ex.what()))
);
// Logging handled in main thread
}
}
void MongoWorker::handle(DropUserRequest *event)
{
try {
boost::scoped_ptr<MongoClient> client(getClient());
client->dropUser(event->database(), event->username());
client->done();
reply(event->sender(), new DropUserResponse(this, event->username()));
} catch(const std::exception &ex) {
reply(event->sender(),
new DropUserResponse(this, event->username(), EventError(ex.what()))
);
// Logging handled in main thread
}
}
void MongoWorker::handle(CreateFunctionRequest *event)
{
std::string const& functionName = event->function().name();
try {
if (event->dbVersion() >= 3.4) {
auto const cmd = "db.system.js.save(" + event->function().toBson().toString() + ')';
MongoShellExecResult const& result = _scriptEngine->exec(cmd, event->database());
if (result.error())
throw std::runtime_error(result.errorMessage());
}
else {
boost::scoped_ptr<MongoClient> client(getClient());
client->createFunction(event->database(), event->function(), event->existingFunctionName());
client->done();
}
reply(event->sender(), new CreateFunctionResponse(this, functionName));
} catch(const std::exception &ex) {
reply(event->sender(),
new CreateFunctionResponse(this, functionName, EventError(ex.what()))
);
// Logging handled in main thread
}
}
void MongoWorker::handle(DropFunctionRequest *event)
{
try {
if (event->dbVersion() >= 3.4) {
auto const cmd = "db.system.js.remove( { _id : \"" + event->functionName() + "\" } )";
MongoShellExecResult const& result = _scriptEngine->exec(cmd, event->database());
if (result.error())
throw std::runtime_error(result.errorMessage());
}
else {
boost::scoped_ptr<MongoClient> client(getClient());
client->dropFunction(event->database(), event->functionName());
client->done();
}
reply(event->sender(), new DropFunctionResponse(this, event->functionName()));
}
catch (const std::exception &ex) {
reply(event->sender(),
new DropFunctionResponse(this, event->functionName(), EventError(ex.what()))
);
// Logging handled in main thread
}
}
std::pair<mongo::DBClientBase*, std::string> MongoWorker::getConnection(bool mayReturnNull /* = false */)
{
configureSSL();
// --- Perform connection ---
if (_connSettings->isReplicaSet()) { // connection to replica set
if(_dbclientRepSet)
return { _dbclientRepSet.get(), "" };
init(); // Init mongoworker for early-use of _scriptEngine
// Step-1: Use user entered set name or retrieve set name from cache or from a reachable member
std::string setName = _connSettings->replicaSetSettings()->setNameUserEntered();
if (setName.empty()) {
setName = _connSettings->replicaSetSettings()->cachedSetName();
if (setName.empty()) // If there is no cached set name, get it from an on-line replica node
setName = connectAndGetReplicaSetName();
if (setName.empty()) // It is not possible to continue with empty set name
return { nullptr, "It is not possible to continue with empty set name" };
}
// Step-2: Try connect to replica set with set name
auto const& membersHostsAndPorts = _connSettings->replicaSetSettings()->membersToHostAndPort();
_dbclientRepSet.reset(new mongo::DBClientReplicaSet {
setName, membersHostsAndPorts, APP_NAME_VERSION, _mongoTimeoutSec
});
if (!_dbclientRepSet->connect())
return { nullptr, "Connect failed" };
else
return { _dbclientRepSet.get(), "" };
}
else { // connection to single server
if(_dbclient)
return { _dbclient.get(), "" };
// Timeout for operations
// Connect timeout is fixed, but short, at 5 seconds (see headers for DBClientConnection)
_dbclient.reset(new mongo::DBClientConnection { true, _mongoTimeoutSec });
mongo::Status const& status = _dbclient->connect(_connSettings->hostAndPort(), APP_NAME_VERSION);
if (!status.isOK() && mayReturnNull)
return { nullptr, status.reason() };
else
return { _dbclient.get(), "" };
}
}
MongoClient *MongoWorker::getClient()
{
return new MongoClient(getConnection().first);
}
void MongoWorker::configureSSL()
{
// As a precaution reset SSL global params for any kind of connection request (SSL or non-SSL)
resetGlobalSSLparams();
// Update global SSL mode and global mongo SSL settings
if (_connSettings->sslSettings()->sslEnabled()) {
// Force SSL mode for outgoing connections
mongo::sslGlobalParams.sslMode.store(mongo::SSLParams::SSLMode_requireSSL);
updateGlobalSSLparams();
}
else {
// Disable forced SSL mode for outgoing connections
mongo::sslGlobalParams.sslMode.store(mongo::SSLParams::SSLMode_allowSSL);
}
}
void MongoWorker::updateGlobalSSLparams() const
{
resetGlobalSSLparams();
const SslSettings * const sslSettings = _connSettings->sslSettings();
mongo::sslGlobalParams.sslAllowInvalidCertificates = sslSettings->allowInvalidCertificates();
if (!mongo::sslGlobalParams.sslAllowInvalidCertificates)
{
mongo::sslGlobalParams.sslCAFile = sslSettings->caFile();
}
if (sslSettings->usePemFile())
{
mongo::sslGlobalParams.sslPEMKeyFile = sslSettings->pemKeyFile();
mongo::sslGlobalParams.sslPEMKeyPassword = sslSettings->pemPassPhrase();
}
if (sslSettings->useAdvancedOptions())
{
mongo::sslGlobalParams.sslCRLFile = sslSettings->crlFile();
mongo::sslGlobalParams.sslAllowInvalidHostnames = sslSettings->allowInvalidHostnames();
}
}
void MongoWorker::resetGlobalSSLparams() const
{
mongo::sslGlobalParams.sslAllowInvalidCertificates = false;
mongo::sslGlobalParams.sslCAFile = "";
mongo::sslGlobalParams.sslPEMKeyFile = "";
mongo::sslGlobalParams.sslPEMKeyPassword = "";
mongo::sslGlobalParams.sslCRLFile = "";
mongo::sslGlobalParams.sslAllowInvalidHostnames = false;
}
// todo: From 1.4, this function started to return incorrect member healths when set is unreachable.
// Needs more investigation.
ReplicaSet MongoWorker::getReplicaSetInfo() const
{
std::string setName;
mongo::HostAndPort primary;
std::vector<std::pair<std::string, bool>> membersAndHealths;
// Refresh view of Replica Set Monitor to get live data
auto repSetMonitor = mongo::globalRSMonitorManager.getMonitor(_dbclientRepSet->getSetName());
// Handle long lasting (e.g. overnight) connections which causes replica set monitor to be null
if (!repSetMonitor) {
mongo::ReplicaSetMonitor::createIfNeeded(_dbclientRepSet->getSetName(),
_connSettings->replicaSetSettings()->membersToHostAndPortAsSet());
repSetMonitor = mongo::globalRSMonitorManager.getMonitor(_dbclientRepSet->getSetName());
if (!repSetMonitor) // if nullptr again even if the set is reachable, something went really wrong.
return ReplicaSet(setName, primary, membersAndHealths,
"Unexpected error. Unable to get replica set monitor for set name: " +
_dbclientRepSet->getSetName() + "\nPlease open a new connection.");
}
setName = repSetMonitor->getName();
auto const readPrimaryOnly = mongo::ReadPreferenceSetting(mongo::ReadPreference::PrimaryOnly, mongo::TagSet());
auto const primaryFuture =
repSetMonitor->getHostOrRefresh(readPrimaryOnly, mongo::Milliseconds(2000));
auto const& primaryStatus{ primaryFuture.waitNoThrow() };
if (primaryStatus.isOK())
primary = primaryFuture.get();
QStringList servers;
// i.e. setNameAndMembers: "repset/localhost:27017,localhost:27018,localhost:27019"
QString const setNameAndMembers = QString::fromStdString(repSetMonitor->getServerAddress());
QStringList const result = setNameAndMembers.split("/");
if (result.size() > 1)
servers = result[1].split(",");
// Save address and health of replica members
for (QString const& server : servers) {
auto const hostAndPort = mongo::HostAndPort(mongo::StringData(server.toStdString()));
membersAndHealths.push_back({ server.toStdString(), repSetMonitor->isHostUp(hostAndPort) });
}
return ReplicaSet(setName, primary, membersAndHealths, primaryStatus.reason());
}
std::string MongoWorker::connectAndGetReplicaSetName() const
{
auto const dbclientTemp { std::make_unique<mongo::DBClientConnection>(true, 10) };
std::string setName = "";
// Try connecting to the nodes one by one until getting replica set name.
for (auto const& node : _connSettings->replicaSetSettings()->membersToHostAndPort())
{
if (!dbclientTemp->connect(node, APP_NAME_VERSION).isOK())
return "";
_scriptEngine->init(_isLoadMongoRcJs, node.toString());
MongoShellExecResult const& result = _scriptEngine->exec("rs.status()", "");
if (!result.results().empty()) {
auto const& resultDocs = result.results().front().documents();
if (!resultDocs.empty()) {
setName = resultDocs.front()->bsonObj().getStringField("set");
if (!setName.empty()) // We get the information, finish the loop
break;
}
}
}
return setName;
}
/**
* @brief Send event to this MongoWorker
*/
void MongoWorker::send(Event *event)
{
if (_isQuiting)
return;
AppRegistry::instance().bus()->send(this, event);
}
/**
* @brief Send reply event to object 'receiver'
*/
void MongoWorker::reply(QObject *receiver, Event *event)
{
if (_isQuiting)
return;
AppRegistry::instance().bus()->send(receiver, event);
}
void MongoWorker::pingDatabase(mongo::DBClientBase *dbclient) const
{
// Building { ping: 1 }
mongo::BSONObjBuilder command;
command.append("ping", 1);
mongo::BSONObj result;
std::string const authBase = getAuthBase();
dbclient->runCommand(authBase.empty() ? "admin" : authBase, command.obj(), result);
}
}
| 45,642
|
C++
|
.cpp
| 986
| 34.130832
| 125
| 0.583127
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,654
|
StdUtils.cpp
|
Studio3T_robomongo/src/robomongo/core/utils/StdUtils.cpp
|
#include "robomongo/core/utils/StdUtils.h"
namespace Robomongo
{
namespace stdutils
{
}
}
| 111
|
C++
|
.cpp
| 7
| 11.857143
| 42
| 0.726316
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,655
|
Logger.cpp
|
Studio3T_robomongo/src/robomongo/core/utils/Logger.cpp
|
#include "robomongo/core/utils/Logger.h"
#include <QDir>
#include <QMetaType>
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/domain/App.h"
#include "robomongo/core/EventBus.h"
#include "robomongo/core/settings/SettingsManager.h"
#include "robomongo/core/utils/QtUtils.h"
namespace Robomongo
{
Logger::Logger()
{
QFile file {
QString("%1/" PROJECT_NAME_LOWERCASE ".log").arg(QDir::tempPath())
};
//delete file if it size more than 5mb
if (file.exists() && file.size() > 5 * 1024 * 1024)
file.remove();
}
Logger::~Logger()
{
}
void Logger::print(const char *mess, mongo::logger::LogSeverity level, bool notify)
{
print(std::string(mess), level, notify);
}
void Logger::print(const std::string &mess, mongo::logger::LogSeverity level, bool notify)
{
print(QtUtils::toQString(mess), level, notify);
}
void Logger::print(const QString &msg, mongo::logger::LogSeverity level, bool notify)
{
if (!notify)
return;
// Make uniform log level strings e.g "Error: ", "Info: " etc...
auto logLevelStr = QString::fromStdString(level.toStringData().toString());
if (!logLevelStr.isEmpty()) {
logLevelStr = logLevelStr.toLower();
logLevelStr[0] = logLevelStr[0].toUpper();
logLevelStr += ": ";
}
emit printed(logLevelStr + msg.simplified(), level);
}
void sendLog(
QObject *sender, LogEvent::LogLevel const& severity,
std::string const& msg, bool const informUser /*= false*/)
{
AppRegistry::instance().bus()->send(
AppRegistry::instance().app(),
new LogEvent(sender, msg, severity, informUser)
);
}
void debugLog(std::string_view msg) {
if (!AppRegistry::instance().settingsManager()->debugMode())
return;
std::cout << msg << std::endl;
}
}
| 2,005
|
C++
|
.cpp
| 58
| 27.344828
| 94
| 0.609504
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,656
|
BsonUtils.cpp
|
Studio3T_robomongo/src/robomongo/core/utils/BsonUtils.cpp
|
#include "robomongo/core/utils/BsonUtils.h"
#include <mongo/client/dbclient_base.h>
//#include <mongo/bson/bsonobjiterator.h>
#include "mongo/util/base64.h"
#include "mongo/util/str.h"
#include "robomongo/core/utils/Logger.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/core/HexUtils.h"
// v0.9
#include "robomongo/shell/db/ptimeutil.h"
using namespace mongo;
namespace Robomongo
{
namespace BsonUtils
{
namespace detail
{
template<>
mongo::BSONObj getField<mongo::BSONObj>(const mongo::BSONElement &elem)
{
return elem.embeddedObject();
}
template<>
bool getField<bool>(const mongo::BSONElement &elem)
{
return elem.Bool();
}
template<>
std::string getField<std::string>(const mongo::BSONElement &elem)
{
return elem.String();
}
template<>
std::vector<BSONElement> getField<std::vector<BSONElement> >(const mongo::BSONElement &elem)
{
return elem.Array();
}
template<>
int getField<int>(const mongo::BSONElement &elem)
{
return elem.Int();
}
template<>
double getField<double>(const mongo::BSONElement &elem)
{
return elem.numberDouble();
}
template<>
long long getField<long long>(const mongo::BSONElement &elem)
{
return elem.safeNumberLong();
}
}
std::string jsonString(const BSONObj &obj, JsonStringFormat format, int pretty, UUIDEncoding uuidEncoding, SupportedTimes timeFormat, bool isArray)
{
using namespace std;
// Use of method, that is implemented in Robomongo Shell
// Method "isArray()" is not part of MongoDB.
// In order for this method to work, someone should
// explicetly call "markAsArray()" method on BSONObj.
// This is done in the Robomongo Shell (MongoDB fork)
if (obj.isArray()) {
isArray = true;
}
if ( obj.isEmpty() ) {
return isArray? "[]" : "{}";
}
StringBuilder s;
s << (isArray ? "[" : "{");
BSONObjIterator i(obj);
BSONElement e = i.next();
if ( !e.eoo() ) {
while ( 1 ) {
if ( pretty ) {
s << '\n';
for( int x = 0; x < pretty; x++ ) {
s << " ";
}
}
else {
s << " ";
}
s << jsonString(e, format, true, pretty ? pretty + 1 : 0, uuidEncoding, timeFormat, isArray);
e = i.next();
if (e.eoo()) {
s << '\n';
for( int x = 0; x < pretty - 1; x++ ) {
s << " ";
}
s << (isArray ? "]" : "}");
break;
}
s << ",";
}
}
return s.str();
}
std::string jsonString(const BSONElement &elem, JsonStringFormat format, bool includeFieldNames,
int pretty, UUIDEncoding uuidEncoding, SupportedTimes timeFormat, bool isArray)
{
using namespace std;
BSONType t = elem.type();
std::stringstream s;
if ( includeFieldNames && !isArray)
s << '"' << mongo::str::escape(elem.fieldName()) << "\" : ";
switch ( t ) {
case Undefined:
s << "undefined";
break;
case mongo::String:
case Symbol:
s << '"' << mongo::str::escape(std::string(elem.valuestr(), elem.valuestrsize() - 1))
<< '"';
break;
case NumberLong:
s << "NumberLong(" << elem._numberLong() << ")";
break;
case NumberInt:
s << elem._numberInt();
break;
case NumberDouble:
{
if ( elem.number() >= -std::numeric_limits< double >::max() &&
elem.number() <= std::numeric_limits< double >::max() ) {
std::stringstream ss;
ss.precision(std::numeric_limits<double>::digits10);
ss << elem.Double();
std::string const str =
reformatDoubleString(QString::fromStdString(ss.str()), elem.Double());
s << (str);
}
else if (std::isnan(elem.number()) ) {
s << "NaN";
}
else if (std::isinf(elem.number()) ) {
s << (std::to_string(elem.number()) == "inf" ? "Infinity" : "-Infinity");
}
else {
StringBuilder ss;
ss << "BsonUtils::jsonString(): Number " << elem.number()
<< " cannot be represented in JSON";
LOG_MSG(ss.str(), mongo::logger::LogSeverity::Error());
}
break;
}
case NumberDecimal:
s << "NumberDecimal(\"" << elem._numberDecimal().toString() << "\")";
break;
case mongo::Bool:
s << ( elem.boolean() ? "true" : "false" );
break;
case jstNULL:
s << "null";
break;
case Object: {
BSONObj obj = elem.embeddedObject();
s << jsonString(obj, format, pretty, uuidEncoding, timeFormat);
}
break;
case mongo::Array: {
if ( elem.embeddedObject().isEmpty() ) {
s << "[]";
break;
}
s << "[ ";
BSONObjIterator i( elem.embeddedObject() );
BSONElement e = i.next();
if ( !e.eoo() ) {
int count = 0;
while ( 1 ) {
if ( pretty ) {
s << '\n';
for( int x = 0; x < pretty; x++ )
s << " ";
}
if (strtol(e.fieldName(), 0, 10) > count) {
s << "undefined";
}
else {
s << jsonString(e, format, false, pretty ? pretty + 1 : 0, uuidEncoding, timeFormat, true);
e = i.next();
}
count++;
if ( e.eoo() ) {
s << '\n';
for( int x = 0; x < pretty - 1; x++ )
s << " ";
s << "]";
break;
}
s << ", ";
}
}
//s << " ]";
break;
}
case DBRef: {
mongo::OID *x = (mongo::OID *) (elem.valuestr() + elem.valuestrsize());
if ( format == TenGen )
s << "DBRef(";
else
s << "{ \"$ref\" : ";
s << '"' << elem.valuestr() << "\", ";
if ( format != TenGen )
s << "\"$id\" : ";
s << '"' << *x << "\"";
if ( format == TenGen )
s << ')';
else
s << '}';
break;
}
case jstOID:
if ( format == TenGen ) {
s << "ObjectId(";
}
else {
s << "{ \"$oid\" : ";
}
s << '"' << elem.__oid() << '"';
if ( format == TenGen ) {
s << ")";
}
else {
s << " }";
}
break;
case BinData: {
int len = *(int *)( elem.value() );
BinDataType type = BinDataType( *(char *)( (int *)( elem.value() ) + 1 ) );
if (type == mongo::bdtUUID || type == mongo::newUUID) {
s << HexUtils::formatUuid(elem, uuidEncoding);
break;
}
s << "{ \"$binary\" : \"";
char *start = ( char * )( elem.value() ) + sizeof( int ) + 1;
base64::encode( s , start , len );
s << "\", \"$type\" : \"" << hex;
s.width( 2 );
s.fill( '0' );
s << type << dec;
s << "\" }";
break;
}
case mongo::Date:
{
Date_t d = elem.date();
long long ms = d.toMillisSinceEpoch(); //static_cast<long long>(d.millis);
bool isSupportedDate = miutil::minDate < ms && ms < miutil::maxDate;
if ( format == Strict )
s << "{ \"$date\" : ";
else{
if (isSupportedDate) {
s << "ISODate(";
}
else{
s << "Date(";
}
}
if ( pretty && isSupportedDate) {
boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
boost::posix_time::time_duration diff = boost::posix_time::millisec(ms);
boost::posix_time::ptime time = epoch + diff;
std::string timestr = miutil::isotimeString(time, true, timeFormat == LocalTime);
s << '"' << timestr << '"';
}
else
s << ms;
if ( format == Strict )
s << " }";
else
s << ")";
break;
}
case RegEx:
if ( format == Strict ) {
s << "{ \"$regex\" : \"" << mongo::str::escape(elem.regex());
s << "\", \"$options\" : \"" << elem.regexFlags() << "\" }";
}
else {
s << "/" << mongo::str::escape(elem.regex(), true) << "/";
// FIXME Worry about alpha order?
for ( const char *f = elem.regexFlags(); *f; ++f ) {
switch ( *f ) {
case 'g':
case 'i':
case 'm':
s << *f;
default:
break;
}
}
}
break;
case CodeWScope: {
BSONObj scope = elem.codeWScopeObject();
if ( ! scope.isEmpty() ) {
s << "{ \"$code\" : " << elem._asCode() << " , "
<< " \"$scope\" : " << scope.jsonString() << " }";
break;
}
}
case Code:
s << elem._asCode();
break;
case bsonTimestamp:
if ( format == TenGen )
s << "Timestamp(" << elem.timestamp().getSecs() << ", " << elem.timestampInc() << ")";
else
s << "{ \"$timestamp\" : { \"t\" : " << elem.timestamp().getSecs() << ", \"i\" : "
<< elem.timestampInc() << " } }";
break;
case MinKey:
s << "{ \"$minKey\" : 1 }";
break;
case MaxKey:
s << "{ \"$maxKey\" : 1 }";
break;
default:
StringBuilder ss;
ss << "Cannot create a properly formatted JSON string with "
<< "element: " << elem.toString() << " of type: " << elem.type();
}
return s.str();
}
bool isArray(const mongo::BSONElement &elem)
{
return isArray(elem.type());
}
bool isArray(mongo::BSONType type)
{
return type == mongo::Array ;
}
bool isDocument(const mongo::BSONElement &elem)
{
return isDocument(elem.type());
}
bool isDocument(mongo::BSONType type)
{
switch( type ) {
case mongo::Object:
case mongo::Array:
return true;
default:
return false;
}
}
bool isSimpleType(const mongo::BSONType type)
{
switch( type ) {
case NumberLong:
case NumberDouble:
case NumberDecimal:
case NumberInt:
case mongo::String:
case mongo::Bool:
case mongo::Date:
case jstOID:
return true;
default:
return false;
}
}
bool isUuidType(const mongo::BSONType type, mongo::BinDataType binDataType)
{
if (type != mongo::BinData)
return false;
return (binDataType == mongo::newUUID || binDataType == mongo::bdtUUID);
}
bool isSimpleType(const mongo::BSONElement &elem)
{
return isSimpleType(elem.type());
}
bool isUuidType(const mongo::BSONElement &elem)
{
if (elem.type() != mongo::BinData)
return false;
mongo::BinDataType binType = elem.binDataType();
return (binType == mongo::newUUID || binType == mongo::bdtUUID);
}
const char* BSONTypeToString(mongo::BSONType type, mongo::BinDataType binDataType, UUIDEncoding uuidEncoding)
{
switch (type)
{
/** double precision floating point value */
case NumberDouble:
{
return "Double";
}
/** double precision floating point value */
case NumberDecimal:
{
return "Decimal128";
}
/** character string, stored in utf8 */
case String:
{
return "String";
}
/** an embedded object */
case Object:
{
return "Object";
}
/** an embedded array */
case Array:
{
return "Array";
}
case BinData:
{
if (binDataType == mongo::newUUID) {
return "UUID";
} else if (binDataType == mongo::bdtUUID) {
const char* type;
switch(uuidEncoding) {
case DefaultEncoding: type = "Legacy UUID"; break;
case JavaLegacy: type = "Java UUID (Legacy)"; break;
case CSharpLegacy: type = ".NET UUID (Legacy)"; break;
case PythonLegacy: type = "Python UUID (Legacy)"; break;
default: type = "Legacy UUID"; break;
}
return type;
} else {
return "Binary";
}
}
/** Undefined type */
case Undefined:
{
return "Undefined";
}
/** ObjectId */
case jstOID:
{
return "ObjectId";
}
/** boolean type */
case Bool:
{
return "Boolean";
}
/** date type */
case Date:
{
return "Date";
}
/** null type */
case jstNULL:
{
return "Null";
}
break;
/** regular expression, a pattern with options */
case RegEx:
{
return "Regular Expression";
}
/** deprecated / will be redesigned */
case DBRef:
{
return "DBRef";
}
/** deprecated / use CodeWScope */
case Code:
{
return "Code";
}
break;
/** a programming language (e.g., Python) symbol */
case Symbol:
{
return "Symbol";
}
/** javascript code that can execute on the database server, with SavedContext */
case CodeWScope:
{
return "CodeWScope";
}
/** 32 bit signed integer */
case NumberInt:
{
return "Int32";
}
/** Updated to a Date with value next OpTime on insert */
case bsonTimestamp:
{
return "Timestamp";
}
/** 64 bit integer */
case NumberLong:
{
return "Int64";
}
break;
default:
{
return "Type is not supported";
}
}
}
void buildJsonString(const mongo::BSONObj &obj, std::string &con, UUIDEncoding uuid, SupportedTimes tz)
{
mongo::BSONObjIterator iterator(obj);
con.append("{ \n");
while (iterator.more())
{
mongo::BSONElement e = iterator.next();
con.append("\"");
con.append(e.fieldName());
con.append("\"");
con.append(" : ");
buildJsonString(e, con, uuid, tz);
con.append(", \n");
}
con.append("\n}\n\n");
}
void buildJsonString(const mongo::BSONElement &elem, std::string &con, UUIDEncoding uuid, SupportedTimes tz)
{
switch (elem.type())
{
case NumberDouble:
{
if (elem.number() >= -std::numeric_limits< double >::max() &&
elem.number() <= std::numeric_limits< double >::max()) {
std::stringstream ss;
ss.precision(std::numeric_limits<double>::digits10);
ss << elem.Double();
std::string const str =
reformatDoubleString(QString::fromStdString(ss.str()), elem.Double());
con.append(str);
}
else if (std::isnan(elem.number())) {
con.append("NaN");
}
else if (std::isinf(elem.number())) {
con.append(std::to_string(elem.number()) == "inf" ? "Infinity" : "-Infinity");
}
else {
StringBuilder ss;
ss << "BsonUtils::buildJsonString(): Number " << elem.number()
<< " cannot be represented in JSON";
LOG_MSG(ss.str(), mongo::logger::LogSeverity::Error());
}
}
break;
case String:
{
con.append(elem.valuestr(), elem.valuestrsize() - 1);
}
break;
case Object:
{
buildJsonString(elem.Obj(), con, uuid, tz);
}
break;
case Array:
{
buildJsonString(elem.Obj(), con, uuid, tz);
}
break;
case BinData:
{
mongo::BinDataType binType = elem.binDataType();
if (binType == mongo::newUUID || binType == mongo::bdtUUID) {
std::string uu = HexUtils::formatUuid(elem, uuid);
con.append(uu);
break;
}
con.append("<binary>");
}
break;
case Undefined:
con.append("undefined");
break;
case jstOID:
{
std::string idValue = elem.OID().toString();
char buff[256] = {0};
sprintf(buff, "ObjectId(\"%s\")", idValue.c_str());
con.append(buff);
}
break;
case Bool:
con.append(elem.Bool() ? "true" : "false");
break;
case Date:
{
long long ms = (long long) elem.Date().toMillisSinceEpoch();
bool isSupportedDate = miutil::minDate < ms && ms < miutil::maxDate;
boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
boost::posix_time::time_duration diff = boost::posix_time::millisec(ms);
boost::posix_time::ptime time = epoch + diff;
std::string date;
if (isSupportedDate)
date = miutil::isotimeString(time, false, tz == LocalTime);
else
date = boost::lexical_cast<std::string>(ms);
con.append(date);
break;
}
case jstNULL:
con.append("null");
break;
case RegEx:
{
con.append("/" + std::string(elem.regex()) + "/");
for ( const char *f = elem.regexFlags(); *f; ++f ) {
switch ( *f ) {
case 'g':
case 'i':
case 'm':
con += *f;
default:
break;
}
}
}
break;
case DBRef:
break;
case Code:
con.append(elem._asCode());
break;
case Symbol:
con.append(elem.valuestr(), elem.valuestrsize() - 1);
break;
case CodeWScope:
{
mongo::BSONObj scope = elem.codeWScopeObject();
if (!scope.isEmpty() ) {
con.append(elem._asCode());
break;
}
}
break;
case NumberInt:
{
char num[16] = {0};
sprintf(num, "%d", elem.Int());
con.append(num);
break;
}
case bsonTimestamp:
{
Date_t date = elem.timestampTime();
unsigned long long millis = date.toMillisSinceEpoch(); // millis;
if ((long long)millis >= 0 &&
((long long)millis/1000) < (std::numeric_limits<time_t>::max)()) {
con.append(date.toString());
}
break;
}
case NumberLong:
{
char num[32] = {0};
sprintf(num, "%lld", elem.Long());
con.append(num);
break;
}
case NumberDecimal:
{
con.append(elem.numberDecimal().toString());
break;
}
default:
con.append("<unsupported>");
break;
}
}
mongo::BSONElement indexOf(const mongo::BSONObj &doc, int index)
{
mongo::BSONObjIterator iterator(doc);
for (int i = 0; iterator.more(); ++i)
{
mongo::BSONElement element = iterator.next();
if (i == index) {
return element;
}
}
return mongo::BSONElement();
}
int elementsCount(const mongo::BSONObj &doc)
{
mongo::BSONObjIterator iterator(doc);
int i = 0;
for (; iterator.more(); ++i)
{
iterator.next();
}
return i;
}
std::string reformatDoubleString(QString str, double elemDouble)
{
// Leave trailing zero if needed
if (!str.contains("e+", Qt::CaseInsensitive) &&
!str.contains("e-", Qt::CaseInsensitive) && elemDouble == (long long)elemDouble)
str.append(".0");
else if (str.endsWith("e+15", Qt::CaseInsensitive) ||
str.endsWith("e+16", Qt::CaseInsensitive)) {
// Disable scientific format
std::stringstream ss2;
ss2.precision(std::numeric_limits<double>::digits10);
ss2 << std::fixed << elemDouble;
str = QString::fromStdString(ss2.str());
while (str.contains('.') && str.endsWith("00"))
str.chop(1);
}
return str.toStdString();
}
} // BsonUtils
} // Robomongo
| 26,730
|
C++
|
.cpp
| 712
| 20.132022
| 155
| 0.374094
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,657
|
QtUtils.cpp
|
Studio3T_robomongo/src/robomongo/core/utils/QtUtils.cpp
|
#include "robomongo/core/utils/QtUtils.h"
#include <QThread>
#include <QTreeWidgetItem>
namespace Robomongo
{
namespace QtUtils
{
template<>
QString toQString<std::string>(const std::string &value)
{
//static QTextCodec *LOCALECODEC = QTextCodec::codecForLocale();
return QString::fromUtf8(value.c_str(), value.size());
}
template<>
QString toQString<std::wstring>(const std::wstring &value)
{
return QString((const QChar*)value.c_str(), value.length());
}
std::string toStdString(const QString &value)
{
QByteArray sUtf8 = value.toUtf8();
return std::string(sUtf8.constData(), sUtf8.length());
}
std::string toStdStringSafe(const QString &value)
{
#ifdef Q_OS_WIN
QByteArray sUtf8 = value.toLocal8Bit();
#else
QByteArray sUtf8 = value.toUtf8();
#endif
return std::string(sUtf8.constData(), sUtf8.length());
}
void cleanUpThread(QThread *const thread)
{
if (thread && thread->isRunning()) {
//thread->stop();
thread->wait();
}
}
void clearChildItems(QTreeWidgetItem *const root)
{
int itemCount = root->childCount();
for (int i = 0; i < itemCount; ++i) {
QTreeWidgetItem *item = root->child(0);
root->removeChild(item);
delete item;
}
}
}
}
| 1,573
|
C++
|
.cpp
| 50
| 21.84
| 76
| 0.545515
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,658
|
MongoEvents.cpp
|
Studio3T_robomongo/src/robomongo/core/events/MongoEvents.cpp
|
#include "robomongo/core/events/MongoEvents.h"
#include "robomongo/core/Core.h"
namespace Robomongo
{
R_REGISTER_EVENT(EstablishConnectionRequest)
R_REGISTER_EVENT(EstablishConnectionResponse)
R_REGISTER_EVENT(ReplicaSetRefreshed)
R_REGISTER_EVENT(RefreshReplicaSetFolderRequest)
R_REGISTER_EVENT(RefreshReplicaSetFolderResponse)
R_REGISTER_EVENT(ReplicaSetFolderLoading)
R_REGISTER_EVENT(ReplicaSetFolderRefreshed)
R_REGISTER_EVENT(LoadDatabaseNamesRequest)
R_REGISTER_EVENT(LoadDatabaseNamesResponse)
R_REGISTER_EVENT(LoadCollectionNamesRequest)
R_REGISTER_EVENT(LoadCollectionNamesResponse)
R_REGISTER_EVENT(LoadUsersRequest)
R_REGISTER_EVENT(LoadCollectionIndexesRequest)
R_REGISTER_EVENT(LoadCollectionIndexesResponse)
R_REGISTER_EVENT(AddEditIndexRequest)
R_REGISTER_EVENT(AddEditIndexResponse)
R_REGISTER_EVENT(DropCollectionIndexRequest)
R_REGISTER_EVENT(DropCollectionIndexResponse)
R_REGISTER_EVENT(LoadUsersResponse)
R_REGISTER_EVENT(LoadFunctionsRequest)
R_REGISTER_EVENT(LoadFunctionsResponse)
R_REGISTER_EVENT(ConnectingEvent)
R_REGISTER_EVENT(ConnectionFailedEvent)
R_REGISTER_EVENT(ConnectionEstablishedEvent)
R_REGISTER_EVENT(DatabaseListLoadedEvent)
R_REGISTER_EVENT(OpeningShellEvent)
R_REGISTER_EVENT(ExecuteQueryRequest)
R_REGISTER_EVENT(ExecuteQueryResponse)
R_REGISTER_EVENT(DocumentListLoadedEvent)
R_REGISTER_EVENT(ExecuteScriptRequest)
R_REGISTER_EVENT(ExecuteScriptResponse)
R_REGISTER_EVENT(AutocompleteRequest)
R_REGISTER_EVENT(AutocompleteResponse)
R_REGISTER_EVENT(ScriptExecutedEvent)
R_REGISTER_EVENT(ScriptExecutingEvent)
R_REGISTER_EVENT(InsertDocumentRequest)
R_REGISTER_EVENT(InsertDocumentResponse)
R_REGISTER_EVENT(RemoveDocumentRequest)
R_REGISTER_EVENT(RemoveDocumentResponse)
R_REGISTER_EVENT(CreateDatabaseRequest)
R_REGISTER_EVENT(CreateDatabaseResponse)
R_REGISTER_EVENT(DropDatabaseRequest)
R_REGISTER_EVENT(DropDatabaseResponse)
R_REGISTER_EVENT(CreateCollectionRequest)
R_REGISTER_EVENT(CreateCollectionResponse)
R_REGISTER_EVENT(DropCollectionRequest)
R_REGISTER_EVENT(DropCollectionResponse)
R_REGISTER_EVENT(RenameCollectionRequest)
R_REGISTER_EVENT(RenameCollectionResponse)
R_REGISTER_EVENT(DuplicateCollectionRequest)
R_REGISTER_EVENT(DuplicateCollectionResponse)
R_REGISTER_EVENT(CopyCollectionToDiffServerRequest)
R_REGISTER_EVENT(CopyCollectionToDiffServerResponse)
R_REGISTER_EVENT(CreateUserRequest)
R_REGISTER_EVENT(CreateUserResponse)
R_REGISTER_EVENT(DropUserRequest)
R_REGISTER_EVENT(DropUserResponse)
R_REGISTER_EVENT(CreateFunctionRequest)
R_REGISTER_EVENT(CreateFunctionResponse)
R_REGISTER_EVENT(DropFunctionRequest)
R_REGISTER_EVENT(DropFunctionResponse)
R_REGISTER_EVENT(QueryWidgetUpdatedEvent)
R_REGISTER_EVENT(EstablishSshConnectionRequest)
R_REGISTER_EVENT(EstablishSshConnectionResponse)
R_REGISTER_EVENT(ListenSshConnectionRequest)
R_REGISTER_EVENT(ListenSshConnectionResponse)
R_REGISTER_EVENT(LogEvent)
R_REGISTER_EVENT(StopScriptRequest)
R_REGISTER_EVENT(OperationFailedEvent)
}
| 3,234
|
C++
|
.cpp
| 74
| 38.959459
| 56
| 0.819563
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,659
|
MongoEventsInfo.cpp
|
Studio3T_robomongo/src/robomongo/core/events/MongoEventsInfo.cpp
|
#include "robomongo/core/events/MongoEventsInfo.h"
namespace Robomongo
{
IndexInfo::IndexInfo(
const MongoCollectionInfo &collection, const std::string &name, const std::string &keys,
bool isUnique, bool isBackGround, bool isSparce, int expireAfter,
const std::string &defaultLanguage, const std::string &languageOverride, const std::string &textWeights) :
_name(name),
_collection(collection),
_keys(keys),
_unique(isUnique),
_backGround(isBackGround),
_sparse(isSparce),
_ttl(expireAfter),
_defaultLanguage(defaultLanguage),
_languageOverride(languageOverride),
_textWeights(textWeights) {}
ConnectionInfo::ConnectionInfo(std::string const& uuid) :
_address(),
_databases(),
_version(0.0f),
_dbVersionStr(),
_uuid(uuid)
{}
ConnectionInfo::ConnectionInfo(const std::string &address, const std::vector<std::string> &databases,
float version, const std::string& dbVersionStr, const std::string& storageEngine,
std::string const& uuid) :
_address(address),
_databases(databases),
_version(version),
_dbVersionStr(dbVersionStr),
_storageEngineType(storageEngine),
_uuid(uuid)
{}
}
| 1,373
|
C++
|
.cpp
| 35
| 29.8
| 114
| 0.624719
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,660
|
MongoFunction.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/MongoFunction.cpp
|
#include "robomongo/core/domain/MongoFunction.h"
#include "robomongo/core/utils/BsonUtils.h"
#include <mongo/client/dbclient_base.h>
namespace Robomongo
{
MongoFunction::MongoFunction(const mongo::BSONObj &obj)
{
_name = BsonUtils::getField<mongo::String>(obj, "_id");
_code = obj.getField("value")._asCode();
}
mongo::BSONObj MongoFunction::toBson() const
{
mongo::BSONObjBuilder builder;
mongo::BSONCode code = mongo::BSONCode(_code);
builder.append("_id", _name);
builder.append("value", code);
mongo::BSONObj obj = builder.obj();
return obj;
}
}
| 641
|
C++
|
.cpp
| 20
| 26.5
| 63
| 0.653722
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,661
|
CursorPosition.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/CursorPosition.cpp
|
#include "robomongo/core/domain/CursorPosition.h"
namespace Robomongo
{
CursorPosition::CursorPosition() :
_isNull(true),
_line(-1),
_column(-1) {}
CursorPosition::CursorPosition(int line, int column) :
_isNull(false),
_line(line),
_column(column) {}
}
| 311
|
C++
|
.cpp
| 12
| 20.083333
| 58
| 0.619529
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,662
|
MongoShell.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/MongoShell.cpp
|
#include "robomongo/core/domain/MongoShell.h"
#include "mongo/scripting/engine.h"
#include "robomongo/core/domain/MongoServer.h"
#include "robomongo/core/mongodb/MongoWorker.h"
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/EventBus.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/core/utils/Logger.h"
#include "robomongo/core/settings/SettingsManager.h"
namespace Robomongo
{
auto const& eventBus = []() { return AppRegistry::instance().bus(); };
MongoShell::MongoShell(MongoServer *server, ScriptInfo scriptInfo) :
QObject(),
_scriptInfo(scriptInfo),
_server(server)
{
}
void MongoShell::open(const std::string &script, const std::string &dbName)
{
eventBus()->publish(new ScriptExecutingEvent(this));
_scriptInfo.setScript(QtUtils::toQString(script));
eventBus()->send(_server->worker(), new ExecuteScriptRequest(this, query(), dbName));
LOG_MSG(_scriptInfo.script(), mongo::logger::LogSeverity::Info());
}
std::string MongoShell::query() const
{
return QtUtils::toStdString(_scriptInfo.script());
}
void MongoShell::execute(const std::string &script /* = "" */,
const std::string &dbName /* = "" */)
{
if (!_scriptInfo.execute())
return;
std::string const finalScript = script.empty() ? query() : script;
eventBus()->publish(new ScriptExecutingEvent(this));
eventBus()->send(_server->worker(),
new ExecuteScriptRequest(this, finalScript, dbName, _aggrInfo));
if (!_scriptInfo.script().isEmpty())
LOG_MSG(_scriptInfo.script(), mongo::logger::LogSeverity::Info());
}
void MongoShell::query(int resultIndex, const MongoQueryInfo &info)
{
eventBus()->send(_server->worker(), new ExecuteQueryRequest(this, resultIndex, info));
}
void MongoShell::autocomplete(const std::string &prefix)
{
AutocompletionMode autocompletionMode {
AppRegistry::instance().settingsManager()->autocompletionMode()
};
if (autocompletionMode == AutocompleteNone)
return;
eventBus()->send(_server->worker(),
new AutocompleteRequest(this, prefix, autocompletionMode)
);
}
void MongoShell::stop()
{
// _server->worker()->interrupt();
// mongo::Scope::setInterruptFlag(true);
}
bool MongoShell::loadFromFile()
{
return _scriptInfo.loadFromFile();
}
bool MongoShell::saveToFileAs()
{
return _scriptInfo.saveToFileAs();
}
bool MongoShell::saveToFile()
{
return _scriptInfo.saveToFile();
}
void MongoShell::handle(ExecuteQueryResponse *event)
{
if (event->isError()) {
eventBus()->publish(new DocumentListLoadedEvent(this, event->error()));
return;
}
eventBus()->publish(
new DocumentListLoadedEvent(this,
event->resultIndex, event->queryInfo, query(), event->documents)
);
}
void MongoShell::handle(ExecuteScriptResponse *event)
{
if (!event->isError()) {
eventBus()->publish(
new ScriptExecutedEvent(this, event->result, event->empty, event->timeoutReached())
);
return;
}
if (_server->connectionRecord()->isReplicaSet()) {
eventBus()->publish(
new ReplicaSetRefreshed(this, event->error(), event->error().replicaSetInfo())
);
eventBus()->publish(
new ScriptExecutedEvent(this, event->error(), event->timeoutReached())
);
return;
}
else { // single server
eventBus()->publish(
new ScriptExecutedEvent(this, event->error(), event->timeoutReached())
);
return;
}
}
void MongoShell::handle(AutocompleteResponse *event)
{
if (event->isError()) {
eventBus()->publish(new AutocompleteResponse(this, event->error()));
return;
}
eventBus()->publish(new AutocompleteResponse(this, event->list, event->prefix));
}
}
| 4,277
|
C++
|
.cpp
| 117
| 28.162393
| 99
| 0.61189
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,663
|
App.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/App.cpp
|
#include "robomongo/core/domain/App.h"
#include <QHash>
#include <QInputDialog>
#include <QMessageBox>
#include "robomongo/core/domain/MongoServer.h"
#include "robomongo/core/domain/MongoShell.h"
#include "robomongo/core/domain/MongoCollection.h"
#include "robomongo/core/settings/ConnectionSettings.h"
#include "robomongo/core/settings/ReplicaSetSettings.h"
#include "robomongo/core/settings/SshSettings.h"
#include "robomongo/core/settings/SslSettings.h"
#include "robomongo/core/mongodb/SshTunnelWorker.h"
#include "robomongo/core/EventBus.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/core/utils/StdUtils.h"
#include "robomongo/core/utils/Logger.h"
namespace Robomongo
{
namespace detail
{
QString buildCollectionQuery(const std::string &collectionName, const QString &postfix)
{
QString qCollectionName = QtUtils::toQString(collectionName);
QString pattern;
// Use db.getCollection() to avoid having to enumerate and special case "reserved" names
pattern = "db.getCollection(\'%1\').%2";
// Escape '\' symbol
qCollectionName.replace(QChar('\\'), "\\\\");
return pattern.arg(qCollectionName).arg(postfix);
}
}
App::~App()
{}
App::App(EventBus *const bus) : QObject(),
_bus(bus), _lastServerHandle(0) {
_bus->subscribe(this, EstablishSshConnectionResponse::Type);
_bus->subscribe(this, ListenSshConnectionResponse::Type);
_bus->subscribe(this, LogEvent::Type);
}
std::unique_ptr<MongoServer>
App::continueOpenServer(int serverHandle, ConnectionSettings* connSettings,
ConnectionType type, int localport)
{
ConnectionSettings* connSettingsClone = connSettings->clone();
// Modify connection settings when SSH tunnel is used
if ((type == ConnectionPrimary || type == ConnectionTest)
&& !connSettingsClone->isReplicaSet()
&& connSettingsClone->sshSettings()->enabled()
) {
connSettingsClone->setServerHost("127.0.0.1");
connSettingsClone->setServerPort(localport);
}
auto server { std::make_unique<MongoServer>(serverHandle, connSettingsClone, type) };
server->runWorkerThread();
auto replicaSetStr = QString::fromStdString(connSettings->connectionName()) + " [Replica Set]";
replicaSetStr = (connSettings->replicaSetSettings()->members().size() > 0)
? replicaSetStr + QString::fromStdString(connSettings->replicaSetSettings()->members()[0])
: replicaSetStr + "";
QString serverAddress = connSettings->isReplicaSet()
? replicaSetStr
: QString::fromStdString(connSettings->getFullAddress());
LOG_MSG(QString("Connecting to %1...").arg(serverAddress), mongo::logger::LogSeverity::Info());
server->tryConnect();
return server;
}
/**
* Creates and opens new server connection.
* @param connection: ConnectionSettings, that will be owned by MongoServer.
* @param visible: should this server be visible in UI (explorer) or not.
*/
std::unique_ptr<MongoServer>
App::openServerInternal(ConnectionSettings* connSettings, ConnectionType type)
{
++_lastServerHandle;
if (type == ConnectionPrimary)
_bus->publish(new ConnectingEvent(this));
// When connection is SECONDARY or SSH not enabled or replica set,
// then continue without SSH Tunnel
if (type == ConnectionSecondary || !connSettings->sshSettings()->enabled()
|| connSettings->isReplicaSet()
) {
return continueOpenServer(_lastServerHandle, connSettings, type);
}
// Open SSH channel and only after that open connection
LOG_MSG(QString("Creating SSH tunnel to %1:%2...")
.arg(QtUtils::toQString(connSettings->sshSettings()->host()))
.arg(connSettings->sshSettings()->port()), mongo::logger::LogSeverity::Info());
ConnectionSettings* settingsCopy = connSettings->clone();
SshTunnelWorker* sshWorker = new SshTunnelWorker(settingsCopy);
_bus->send(sshWorker, new EstablishSshConnectionRequest(this, _lastServerHandle, sshWorker, settingsCopy, type));
return nullptr;
}
bool App::openServer(ConnectionSettings *connection, ConnectionType type)
{
SshSettings *ssh = connection->sshSettings();
if (!connection->isReplicaSet() && ssh->enabled() && ssh->askPassword() &&
(type == ConnectionPrimary || type == ConnectionTest)) {
bool ok = false;
bool isByKey = ssh->authMethod() == "publickey";
std::string passText = isByKey ? "passphrase" : "password";
std::stringstream s;
s << "In order to continue, please provide the " << passText;
if (isByKey)
s << " for the key file";
s << "." << std::endl << std::endl;
if (ssh->authMethod() == "publickey")
s << "Private Key: " << ssh->privateKeyFile() << std::endl;
s << "Server: " << ssh->host() << std::endl;
s << "User: " << ssh->userName() << std::endl;
s << std::endl << "Enter your " << passText << " that will never be stored:";
QString userInput = QInputDialog::getText(NULL, tr("SSH Authentication"),
QtUtils::toQString(s.str()),
QLineEdit::Password, "", &ok);
if (!ok)
return false;
ssh->setAskedPassword(QtUtils::toStdString(userInput));
}
SslSettings *sslSettings = connection->sslSettings();
if (sslSettings->sslEnabled() && sslSettings->usePemFile() && sslSettings->askPassphrase()
&& (type == ConnectionPrimary || type == ConnectionTest))
{
if (!askSslPassphrasePromptDialog(connection))
{
return false;
}
}
_servers.push_back(move(openServerInternal(connection, type)));
return true;
}
/**
* @brief Closes MongoServer connection and frees all resources, owned
* by MongoServer. Finally, specified MongoServer will also be deleted.
*/
void App::closeServer(MongoServer *server)
{
_servers.erase(std::remove_if(_servers.begin(), _servers.end(),
[&](auto const& el) { return el.get() == server; }), _servers.end());
}
void App::openShell(MongoCollection *collection, const QString &filePathToSave)
{
ConnectionSettings *connection = collection->database()->server()->connectionRecord();
auto const& dbname = collection->database()->name();
connection->setDefaultDatabase(dbname);
QString const& script = detail::buildCollectionQuery(collection->name(), "find({})");
openShell(collection->database()->server(), connection,
ScriptInfo(script, true, dbname, CursorPosition(0, -2), QtUtils::toQString(dbname), filePathToSave)
);
}
void App::openShell(MongoServer *server, const QString &script, const std::string &dbName,
bool execute, const QString &shellName,
const CursorPosition &cursorPosition, const QString &filePathToSave)
{
ConnectionSettings *connection = server->connectionRecord();
if (!dbName.empty())
connection->setDefaultDatabase(dbName);
openShell(server, connection,
ScriptInfo(script, execute, dbName, cursorPosition, shellName, filePathToSave)
);
}
void App::openShell(MongoDatabase *database, const QString &script,
bool execute, const QString &shellName,
const CursorPosition &cursorPosition, const QString &filePathToSave)
{
ConnectionSettings *connection = database->server()->connectionRecord();
connection->setDefaultDatabase(database->name());
openShell(database->server(), connection, ScriptInfo(script, execute, database->name(),
cursorPosition, shellName, filePathToSave));
}
void App::openShell(MongoServer* server, ConnectionSettings* connection, const ScriptInfo &scriptInfo)
{
auto serverClone{ openServerInternal(connection, ConnectionSecondary) };
if (!serverClone || !server)
return;
auto shell{ std::make_unique<MongoShell>(serverClone.get(), scriptInfo) };
_servers.push_back(move(serverClone));
// Connection between explorer's server and tab's MongoShells
_bus->subscribe(server, ReplicaSetRefreshed::Type, shell.get());
_bus->publish(new OpeningShellEvent(this, shell.get()));
shell->execute();
_shells.push_back(move(shell));
return;
}
/**
* @brief Closes MongoShell and frees all resources, owned by specified MongoShell.
* Finally, specified MongoShell will also be deleted.
*/
void App::closeShell(MongoShell *shell)
{
auto const itr = std::find_if(_shells.begin(), _shells.end(),
[&](auto const& el) { return el.get() == shell; }
);
// Do nothing, if this shell not owned by this App.
if (itr == _shells.end())
return;
closeServer(shell->server());
_shells.erase(itr);
}
void App::handle(EstablishSshConnectionResponse *event) {
if (event->isError()) {
_bus->publish(new ConnectionFailedEvent(
this, event->serverHandle, event->connectionType, event->error().errorMessage(),
ConnectionFailedEvent::SshConnection));
return;
}
LOG_MSG(QString("SSH tunnel created successfully"), mongo::logger::LogSeverity::Info());
_servers.push_back(move(
continueOpenServer(event->serverHandle, event->settings, event->connectionType, event->localport)
));
_bus->send(event->worker, new ListenSshConnectionRequest(this, event->serverHandle, event->connectionType));
}
void App::handle(LogEvent *event) {
LOG_MSG(event->message, event->mongoLogSeverity());
if (!event->informUser)
return;
QMessageBox(
event->qMessageBoxIcon(),
QString::fromStdString(event->severity()),
QtUtils::toQString(event->severity() + ": " + event->message)
).exec();
}
void App::handle(ListenSshConnectionResponse *event) {
if (event->isError()) {
_bus->publish(
new ConnectionFailedEvent(this, event->serverHandle, event->connectionType,
event->error().errorMessage(), ConnectionFailedEvent::SshChannel)
);
return;
}
LOG_MSG(QString("SSH tunnel closed."), mongo::logger::LogSeverity::Error());
}
void App::fireConnectionFailedEvent(int serverHandle, ConnectionType type, std::string errormsg,
ConnectionFailedEvent::Reason reason) {
_bus->publish(new ConnectionFailedEvent(this, serverHandle, type, errormsg, reason));
}
bool App::askSslPassphrasePromptDialog(ConnectionSettings *connSettings) const
{
auto sslSettings = connSettings->sslSettings();
bool ok = false;
std::stringstream s;
s << "In order to continue, please provide the passphrase";
s << "." << std::endl << std::endl;
s << "Server: " << connSettings->serverHost() << ":" << connSettings->serverPort() << std::endl;
s << "PEM file: " << sslSettings->pemKeyFile() << std::endl;
s << std::endl << "Enter your PEM key passphrase (will never be stored):";
QString userInput = QInputDialog::getText(NULL, tr("TLS Authentication"),
QtUtils::toQString(s.str()),
QLineEdit::Password, "", &ok);
if (!ok)
{
return false;
}
sslSettings->setPemPassPhrase(QtUtils::toStdString(userInput));
return ok;
}
}
| 12,221
|
C++
|
.cpp
| 255
| 38.12549
| 121
| 0.62788
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,664
|
MongoNamespace.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/MongoNamespace.cpp
|
#include "robomongo/core/domain/MongoNamespace.h"
#include <stdio.h>
namespace Robomongo
{
MongoNamespace::MongoNamespace(const std::string &ns) :
_ns(ns)
{
size_t dot = ns.find_first_of('.');
_collectionName = ns.substr(dot + 1);
_databaseName = ns.substr(0, dot);
}
MongoNamespace::MongoNamespace(const std::string &database, const std::string &collection) :
_databaseName(database),
_collectionName(collection)
{
_ns = _databaseName + ".";
_ns += _collectionName;
}
}
| 562
|
C++
|
.cpp
| 19
| 23.789474
| 96
| 0.627778
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,665
|
ScriptInfo.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/ScriptInfo.cpp
|
#include "robomongo/core/domain/ScriptInfo.h"
#include <QTextStream>
#include <QApplication>
#include <QMessageBox>
#include <QFileDialog>
namespace
{
const QString filterForScripts = QObject::tr("JavaScript (*.js);; All Files (*.*)");
bool loadFromFileText(const QString &filePath, QString &text)
{
bool result = false;
QFile file(filePath);
if (file.open(QFile::ReadOnly | QFile::Text)) {
QTextStream in(&file);
QApplication::setOverrideCursor(Qt::WaitCursor);
text = in.readAll();
QApplication::restoreOverrideCursor();
result = true;
}
else {
QMessageBox::critical(QApplication::activeWindow(), QString("Error"),
QObject::tr(PROJECT_NAME" can't read from %1:\n%2.")
.arg(filePath)
.arg(file.errorString()));
}
return result;
}
bool saveToFileText(QString filePath, const QString &text)
{
if (filePath.isEmpty())
return false;
#ifdef Q_OS_LINUX
if (QFileInfo(filePath).suffix().isEmpty()) {
filePath += ".js";
}
#endif
bool result = false;
QFile file(filePath);
if (file.open(QFile::WriteOnly | QFile::Text)) {
QTextStream out(&file);
QApplication::setOverrideCursor(Qt::WaitCursor);
out << text;
QApplication::restoreOverrideCursor();
result = true;
}
else {
QMessageBox::critical(QApplication::activeWindow(), QString("Error"),
QObject::tr(PROJECT_NAME" can't save to %1:\n%2.")
.arg(filePath)
.arg(file.errorString()));
}
return result;
}
}
namespace Robomongo
{
ScriptInfo::ScriptInfo(const QString &script, bool execute, const std::string &dbname,
const CursorPosition &position, const QString &title, const QString &filePath) :
_script(script),
_execute(execute),
_dbname(dbname),
_title(title),
_cursor(position),
_filePath(filePath) {}
bool ScriptInfo::loadFromFile(const QString &filePath)
{
bool result = false;
QString filepath = QFileDialog::getOpenFileName(QApplication::activeWindow(), filePath, QString(), filterForScripts);
if (!filepath.isEmpty()) {
QString out;
if (loadFromFileText(filepath, out)) {
_script = out;
_filePath = filepath;
result = true;
}
}
return result;
}
bool ScriptInfo::loadFromFile()
{
return loadFromFile(_filePath);
}
bool ScriptInfo::saveToFileAs()
{
QString filepath = QFileDialog::getSaveFileName(QApplication::activeWindow(),
QObject::tr("Save As"), _filePath, filterForScripts);
if (saveToFileText(filepath, _script)) {
_filePath = filepath;
return true;
}
return false;
}
bool ScriptInfo::saveToFile()
{
return _filePath.isEmpty() ? saveToFileAs() : saveToFileText(_filePath, _script);
}
}
| 3,234
|
C++
|
.cpp
| 97
| 24.164948
| 125
| 0.578425
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,666
|
MongoUtils.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/MongoUtils.cpp
|
#include "robomongo/core/domain/MongoUtils.h"
#include <mongo/db/json.h>
using namespace std;
#include "mongo/util/md5.hpp"
namespace Robomongo
{
namespace MongoUtils
{
QString buildNiceSizeString(double sizeBytes)
{
if (sizeBytes < 1024 * 100) {
double kb = ((double) sizeBytes) / 1024;
return QString("%1 kb").arg(kb, 2, 'f', 2);
}
double mb = ((double) sizeBytes) / 1024 / 1024;
return QString("%1 mb").arg(mb, 2, 'f', 2);
}
std::string buildPasswordHash(const std::string &username, const std::string &password)
{
std::string sum = username + ":mongo:" + password;
const char * s = sum.c_str();
mongo::md5digest d;
md5_state_t st;
md5_init(&st);
md5_append( &st , (const md5_byte_t*)s , strlen( s ) );
md5_finish(&st, d);
return mongo::digestToString(d);
}
}
}
| 1,006
|
C++
|
.cpp
| 30
| 24.5
| 95
| 0.53759
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,667
|
Notifier.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/Notifier.cpp
|
#include "robomongo/core/domain/Notifier.h"
#include <thread>
#include <chrono>
#include <QAction>
#include <QClipboard>
#include <QApplication>
#include <QMenu>
#include "robomongo/core/domain/MongoShell.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/utils/BsonUtils.h"
#include "robomongo/core/settings/SettingsManager.h"
#include "robomongo/core/domain/MongoServer.h"
#include "robomongo/core/events/MongoEvents.h"
#include "robomongo/shell/db/ptimeutil.h"
#include "robomongo/gui/MainWindow.h"
#include "robomongo/gui/widgets/workarea/BsonTreeItem.h"
#include "robomongo/gui/dialogs/DocumentTextEditor.h"
#include "robomongo/gui/utils/DialogUtils.h"
#include "robomongo/gui/GuiRegistry.h"
#include "robomongo/core/EventBus.h"
namespace Robomongo
{
namespace detail
{
bool isSimpleType(Robomongo::BsonTreeItem const *item)
{
return BsonUtils::isSimpleType(item->type()) ||
BsonUtils::isUuidType(item->type(), item->binType());
}
bool isObjectIdType(Robomongo::BsonTreeItem *item)
{
return mongo::jstOID == item->type();
}
bool isMultiSelection(const QModelIndexList &indexes)
{
return indexes.count() > 1;
}
bool isDocumentType(BsonTreeItem const *item)
{
return BsonUtils::isDocument(item->type());
}
bool isArrayChild(BsonTreeItem const *item)
{
return BsonUtils::isArray(dynamic_cast<BsonTreeItem*>(item->parent())->type());
}
bool isDocumentRoot(BsonTreeItem const *item)
{
return ( item == item->superParent() );
}
/**
*
* @param QModelIndexList indexes
* @param bool returnSuperParents If TRUE, only indexes of super-parents will be in result list
* @return QModelIndexList
*/
QModelIndexList uniqueRows(QModelIndexList indexes, bool returnSuperParents)
{
QModelIndexList result;
for (QModelIndexList::const_iterator it = indexes.begin(); it != indexes.end(); ++it)
{
QModelIndex isUnique = *it;
Robomongo::BsonTreeItem *item = Robomongo::QtUtils::item<Robomongo::BsonTreeItem*>(isUnique);
if (item) {
for (QModelIndexList::const_iterator jt = result.begin(); jt != result.end(); ++jt)
{
Robomongo::BsonTreeItem *jItem = Robomongo::QtUtils::item<Robomongo::BsonTreeItem*>(*jt);
if (jItem && jItem->superParent() == item->superParent()) {
isUnique = QModelIndex();
break;
}
}
if (isUnique.isValid()) {
if (returnSuperParents) {
// Move index onto "super parent" element before pushing it into result set
QModelIndex parent = isUnique.parent();
while (parent != QModelIndex()) {
isUnique = parent;
parent = parent.parent();
}
}
result.append(isUnique);
}
}
}
return result;
}
}
Notifier::Notifier(INotifierObserver *const observer, MongoShell *shell, const MongoQueryInfo &queryInfo, QObject *parent) :
BaseClass(parent),
_observer(observer),
_shell(shell),
_queryInfo(queryInfo)
{
QWidget *wid = dynamic_cast<QWidget*>(_observer);
AppRegistry::instance().bus()->subscribe(this, InsertDocumentResponse::Type, _shell->server());
AppRegistry::instance().bus()->subscribe(this, RemoveDocumentResponse::Type, _shell->server());
_deleteDocumentAction = new QAction("Delete Document...", wid);
VERIFY(connect(_deleteDocumentAction, SIGNAL(triggered()), SLOT(onDeleteDocument())));
_deleteDocumentsAction = new QAction("Delete Documents...", wid);
VERIFY(connect(_deleteDocumentsAction, SIGNAL(triggered()), SLOT(onDeleteDocuments())));
_editDocumentAction = new QAction("Edit Document...", wid);
VERIFY(connect(_editDocumentAction, SIGNAL(triggered()), SLOT(onEditDocument())));
_viewDocumentAction = new QAction("View Document...", wid);
VERIFY(connect(_viewDocumentAction, SIGNAL(triggered()), SLOT(onViewDocument())));
_insertDocumentAction = new QAction("Insert Document...", wid);
VERIFY(connect(_insertDocumentAction, SIGNAL(triggered()), SLOT(onInsertDocument())));
_copyValueAction = new QAction("Copy Value", wid);
VERIFY(connect(_copyValueAction, SIGNAL(triggered()), SLOT(onCopyDocument())));
_copyValueNameAction = new QAction("Copy Name", wid);
VERIFY(connect(_copyValueNameAction, SIGNAL(triggered()), SLOT(onCopyNameDocument())));
_copyValuePathAction = new QAction("Copy Path", wid);
VERIFY(connect(_copyValuePathAction, SIGNAL(triggered()), SLOT(onCopyPathDocument())));
_copyTimestampAction = new QAction("Copy Timestamp from ObjectId", wid);
VERIFY(connect(_copyTimestampAction, SIGNAL(triggered()), SLOT(onCopyTimestamp())));
_copyJsonAction = new QAction("Copy JSON", wid);
VERIFY(connect(_copyJsonAction, SIGNAL(triggered()), SLOT(onCopyJson())));
}
void Notifier::initMenu(QMenu *const menu, BsonTreeItem *const item)
{
bool const isProjection = !_queryInfo._fields.isEmpty();
bool const isEditable = _queryInfo._info.isValid() && !isProjection;
bool const onItem = item ? true : false;
bool isSimple = false;
bool isDocument = false;
bool isObjectId = false;
bool isNotArrayChild = false;
bool isRoot = false;
if (item) {
isSimple = detail::isSimpleType(item);
isDocument = detail::isDocumentType(item);
isObjectId = detail::isObjectIdType(item);
isNotArrayChild = !detail::isArrayChild(item);
isRoot = detail::isDocumentRoot(item);
}
if (onItem && isEditable) menu->addAction(_editDocumentAction);
if (onItem) menu->addAction(_viewDocumentAction);
if (isEditable) menu->addAction(_insertDocumentAction);
if (onItem && (isSimple || isDocument)) menu->addSeparator();
if (onItem && isSimple) menu->addAction(_copyValueAction);
if (onItem && (isSimple || isDocument) && isNotArrayChild && !isRoot)
menu->addAction(_copyValueNameAction);
if (onItem && (isSimple || isDocument) && !isRoot)
menu->addAction(_copyValuePathAction);
if (onItem && isObjectId) menu->addAction(_copyTimestampAction);
if (onItem && isDocument) menu->addAction(_copyJsonAction);
if (onItem && isEditable) menu->addSeparator();
if (onItem && isEditable) menu->addAction(_deleteDocumentAction);
}
void Notifier::initMultiSelectionMenu(QMenu *const menu)
{
bool isEditable = _queryInfo._info.isValid();
if (isEditable) menu->addAction(_insertDocumentAction);
if (isEditable) menu->addAction(_deleteDocumentsAction);
}
void Notifier::deleteDocuments(std::vector<BsonTreeItem*> const& items, bool force)
{
bool isNeededRefresh = false;
int index = 0;
for (auto const * const documentItem : items) {
if (!documentItem)
break;
mongo::BSONObj obj = documentItem->superRoot();
mongo::BSONElement id = obj.getField("_id");
if (id.eoo()) {
QMessageBox::warning(dynamic_cast<QWidget*>(_observer), "Cannot delete",
"Selected document doesn't have _id field. \n"
"Maybe this is a system document that should be managed in a special way?");
break;
}
mongo::BSONObjBuilder builder;
builder.append(id);
mongo::BSONObj bsonQuery = builder.obj();
mongo::Query query(bsonQuery);
if (!force) {
// Ask user
int answer = utils::questionDialog(dynamic_cast<QWidget*>(_observer), "Delete",
"Document", "%1 %2 with id:<br><b>%3</b>?", QtUtils::toQString(id.toString(false)));
if (answer != QMessageBox::Yes)
break;
}
isNeededRefresh = true;
RemoveDocumentCount removeCount = items.size() == 1 ? RemoveDocumentCount::ONE :
RemoveDocumentCount::MULTI;
_shell->server()->removeDocuments(query, _queryInfo._info._ns, removeCount, index);
++index;
mainWindow()->showQueryWidgetProgressBar();
}
}
void Notifier::handle(InsertDocumentResponse *event)
{
if (event->isError()) { // Error
mainWindow()->hideQueryWidgetProgressBar();
if (_shell->server()->connectionRecord()->isReplicaSet()) {
// Insert document from tab results window (Notifier, OutputWindow widget)
if (EventError::SetPrimaryUnreachable == event->error().errorCode()) {
AppRegistry::instance().bus()->publish(
new ReplicaSetRefreshed(_shell, event->error(), event->error().replicaSetInfo()));
}
}
else // single server
QMessageBox::warning(NULL, "Database Error", QString::fromStdString(event->error().errorMessage()));
return;
}
// Success
std::this_thread::sleep_for(std::chrono::milliseconds(100));
_shell->query(0, _queryInfo);
}
void Notifier::handle(RemoveDocumentResponse *event)
{
if (event->isError()) {
if (!(event->removeCount == RemoveDocumentCount::MULTI && event->index > 0))
QMessageBox::warning(NULL, "Database Error", QString::fromStdString(event->error().errorMessage()));
}
else { // Success
std::this_thread::sleep_for(std::chrono::milliseconds(100));
_shell->query(0, _queryInfo);
}
}
void Notifier::onCopyNameDocument()
{
QModelIndex const& selectedInd = _observer->selectedIndex();
if (!selectedInd.isValid())
return;
BsonTreeItem const *documentItem = QtUtils::item<BsonTreeItem*>(selectedInd);
if (!documentItem)
return;
if (!(detail::isSimpleType(documentItem) || detail::isDocumentType(documentItem) ||
!detail::isArrayChild(documentItem) || !detail::isDocumentRoot(documentItem)))
return;
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(QString::fromStdString(documentItem->fieldName()));
}
void Notifier::onCopyPathDocument()
{
QModelIndex const& selectedInd = _observer->selectedIndex();
if (!selectedInd.isValid())
return;
BsonTreeItem const *documentItem = QtUtils::item<BsonTreeItem*>(selectedInd);
if (!documentItem)
return;
if (!(detail::isSimpleType(documentItem) || detail::isDocumentType(documentItem) ||
!detail::isDocumentRoot(documentItem)))
return;
QStringList namesList;
BsonTreeItem const *documentItemHelper = documentItem;
while (!detail::isDocumentRoot(documentItemHelper)) {
if (!detail::isArrayChild(documentItemHelper)) {
namesList.push_front(QString::fromStdString(documentItemHelper->fieldName()));
}
documentItemHelper = dynamic_cast<BsonTreeItem*>(documentItemHelper->parent());
}
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(namesList.join("."));
}
MainWindow* Notifier::mainWindow() const
{
MainWindow* mainWindow;
for (auto wid : QApplication::topLevelWidgets()) {
if ((mainWindow = qobject_cast<MainWindow*>(wid)))
break;
}
return mainWindow;
}
void Notifier::handleDeleteCommand()
{
if (_observer->selectedIndexes().count() > 1)
onDeleteDocuments();
else
onDeleteDocument();
}
void Notifier::onDeleteDocuments()
{
if (!_queryInfo._info.isValid())
return;
QModelIndexList selectedIndexes = _observer->selectedIndexes();
if (!detail::isMultiSelection(selectedIndexes))
return;
int const answer = QMessageBox::question(dynamic_cast<QWidget*>(_observer), "Delete",
QString("Do you want to delete %1 selected documents?").
arg(selectedIndexes.count()));
if (QMessageBox::Yes == answer) {
std::vector<BsonTreeItem*> items;
for (auto index : selectedIndexes)
items.push_back(QtUtils::item<BsonTreeItem*>(index));
deleteDocuments(items, true);
}
}
void Notifier::onDeleteDocument()
{
if (!_queryInfo._info.isValid())
return;
QModelIndex selectedIndex = _observer->selectedIndex();
if (!selectedIndex.isValid())
return;
BsonTreeItem *documentItem = QtUtils::item<BsonTreeItem*>(selectedIndex);
std::vector<BsonTreeItem*> vec;
vec.push_back(documentItem);
return deleteDocuments(vec, false);
}
void Notifier::onEditDocument()
{
if (!_queryInfo._info.isValid())
return;
QModelIndex selectedInd = _observer->selectedIndex();
if (!selectedInd.isValid())
return;
BsonTreeItem *documentItem = QtUtils::item<BsonTreeItem*>(selectedInd);
if (!documentItem)
return;
std::string str = BsonUtils::jsonString(documentItem->superRoot(), mongo::TenGen, 1,
AppRegistry::instance().settingsManager()->uuidEncoding(),
AppRegistry::instance().settingsManager()->timeZone());
const QString &json = QtUtils::toQString(str);
DocumentTextEditor editor(_queryInfo._info, json, false, dynamic_cast<QWidget*>(_observer));
editor.setWindowTitle("Edit Document");
int result = editor.exec();
if (result == QDialog::Accepted) {
_shell->server()->saveDocuments(editor.bsonObj(), _queryInfo._info._ns);
mainWindow()->showQueryWidgetProgressBar();
}
}
void Notifier::onViewDocument()
{
QModelIndex selectedIndex = _observer->selectedIndex();
if (!selectedIndex.isValid())
return;
BsonTreeItem *documentItem = QtUtils::item<BsonTreeItem*>(selectedIndex);
if (!documentItem)
return;
mongo::BSONObj obj = documentItem->superRoot();
std::string str = BsonUtils::jsonString(obj, mongo::TenGen, 1,
AppRegistry::instance().settingsManager()->uuidEncoding(),
AppRegistry::instance().settingsManager()->timeZone());
const QString &json = QtUtils::toQString(str);
DocumentTextEditor *editor = new DocumentTextEditor(_queryInfo._info,
json, true, dynamic_cast<QWidget*>(_observer));
editor->setWindowTitle("View Document");
editor->show();
}
void Notifier::onInsertDocument()
{
if (!_queryInfo._info.isValid())
return;
DocumentTextEditor editor(_queryInfo._info,
"{\n \n}", false, dynamic_cast<QWidget*>(_observer));
editor.setCursorPosition(1, 4);
editor.setWindowTitle("Insert Document");
int result = editor.exec();
if (result != QDialog::Accepted)
return;
DocumentTextEditor::ReturnType obj = editor.bsonObj();
for (DocumentTextEditor::ReturnType::const_iterator it = obj.begin(); it != obj.end(); ++it) {
_shell->server()->insertDocument(*it, _queryInfo._info._ns);
mainWindow()->showQueryWidgetProgressBar();
}
}
void Notifier::onCopyDocument()
{
QModelIndex selectedInd = _observer->selectedIndex();
if (!selectedInd.isValid())
return;
BsonTreeItem *documentItem = QtUtils::item<BsonTreeItem*>(selectedInd);
if (!documentItem)
return;
if (!detail::isSimpleType(documentItem))
return;
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(documentItem->value());
}
void Notifier::onCopyTimestamp()
{
QModelIndex selectedInd = _observer->selectedIndex();
if (!selectedInd.isValid())
return;
BsonTreeItem *documentItem = QtUtils::item<BsonTreeItem*>(selectedInd);
if (!documentItem)
return;
if (!detail::isObjectIdType(documentItem))
return;
QClipboard *clipboard = QApplication::clipboard();
// new Date(parseInt(this.valueOf().slice(0,8), 16)*1000);
QString hexTimestamp = documentItem->value().mid(10, 8);
bool ok;
long long milliTimestamp = (long long)hexTimestamp.toLongLong(&ok, 16)*1000;
bool isSupportedDate = (miutil::minDate < milliTimestamp) && (milliTimestamp < miutil::maxDate);
boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
boost::posix_time::time_duration diff = boost::posix_time::millisec(milliTimestamp);
boost::posix_time::ptime time = epoch + diff;
if (isSupportedDate)
{
std::string date = miutil::isotimeString(time, false, false);
clipboard->setText("ISODate(\""+QString::fromStdString(date)+"\")");
}
else {
clipboard->setText("Error extracting ISODate()");
}
}
void Notifier::onCopyJson()
{
QModelIndex selectedInd = _observer->selectedIndex();
if (!selectedInd.isValid())
return;
BsonTreeItem *documentItem = QtUtils::item<BsonTreeItem*>(selectedInd);
if (!documentItem)
return;
if (!detail::isDocumentType(documentItem))
return;
QClipboard *clipboard = QApplication::clipboard();
mongo::BSONObj obj = documentItem->root();
if (documentItem != documentItem->superParent()) {
obj = obj[documentItem->fieldName()].Obj();
}
bool isArray = BsonUtils::isArray(documentItem->type());
std::string str = BsonUtils::jsonString(obj, mongo::TenGen, 1,
AppRegistry::instance().settingsManager()->uuidEncoding(),
AppRegistry::instance().settingsManager()->timeZone(), isArray);
const QString &json = QtUtils::toQString(str);
clipboard->setText(json);
}
}
| 19,364
|
C++
|
.cpp
| 421
| 34.840855
| 128
| 0.601488
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,668
|
MongoCollectionInfo.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/MongoCollectionInfo.cpp
|
#include "MongoCollectionInfo.h"
#include "robomongo/core/utils/BsonUtils.h"
#include <mongo/client/dbclient_base.h>
namespace Robomongo
{
MongoCollectionInfo::MongoCollectionInfo(const std::string &ns) : _ns(ns) {}
/* MongoCollectionInfo::MongoCollectionInfo(mongo::BSONObj stats) : _ns(stats.getStringField("ns"))
{
// if "size" and "storageSize" are of type Int32 or Int64, they
// will be converted to double by "numberDouble()" function.
_sizeBytes = BsonUtils::getField<mongo::NumberDouble>(stats,"size");
_storageSizeBytes = BsonUtils::getField<mongo::NumberDouble>(stats,"storageSize");
// NumberLong because of mongodb can have very big collections
_count = BsonUtils::getField<mongo::NumberLong>(stats,"count");
}*/
}
| 795
|
C++
|
.cpp
| 16
| 44.6875
| 102
| 0.713548
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,669
|
MongoDocument.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/MongoDocument.cpp
|
#include "robomongo/core/domain/MongoDocument.h"
#include <mongo/client/dbclient_base.h>
#include "robomongo/core/settings/SettingsManager.h"
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/utils/BsonUtils.h"
namespace Robomongo
{
MongoDocument::MongoDocument()
{
}
MongoDocument::~MongoDocument()
{
}
/*
** Create MongoDocument from BsonObj. It will take owned version of BSONObj
*/
MongoDocument::MongoDocument(mongo::BSONObj bsonObj) :_bsonObj(bsonObj)
{
}
/*
** Create MongoDocument from BsonObj. It will take owned version of BSONObj
*/
MongoDocumentPtr MongoDocument::fromBsonObj(const mongo::BSONObj &bsonObj)
{
MongoDocument *doc = new MongoDocument(bsonObj);
return MongoDocumentPtr(doc);
}
/*
** Create list of MongoDocuments from QList<BsonObj>. It will take owned version of BSONObj
*/
std::vector<MongoDocumentPtr> MongoDocument::fromBsonObj(const std::vector<mongo::BSONObj> &bsonObjs)
{
std::vector<MongoDocumentPtr> list;
for (std::vector<mongo::BSONObj>::const_iterator it = bsonObjs.begin(); it != bsonObjs.end(); ++it) {
list.push_back(fromBsonObj(*it));
}
return list;
}
}
| 1,276
|
C++
|
.cpp
| 39
| 27.461538
| 109
| 0.689992
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,670
|
MongoServer.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/MongoServer.cpp
|
#include "robomongo/core/domain/MongoServer.h"
#include "robomongo/core/domain/MongoDatabase.h"
#include "robomongo/core/settings/ConnectionSettings.h"
#include "robomongo/core/settings/SshSettings.h"
#include "robomongo/core/settings/SettingsManager.h"
#include "robomongo/core/settings/ReplicaSetSettings.h"
#include "robomongo/core/mongodb/MongoWorker.h"
#include "robomongo/core/mongodb/SshTunnelWorker.h"
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/domain/App.h"
#include "robomongo/core/EventBus.h"
#include "robomongo/core/events/MongoEventsInfo.h"
#include "robomongo/core/utils/Logger.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/gui/MainWindow.h"
#include "robomongo/utils/common.h"
#include "robomongo/utils/StringOperations.h"
#include <QApplication>
namespace Robomongo {
R_REGISTER_EVENT(MongoServerLoadingDatabasesEvent)
MongoServer::MongoServer(int handle, ConnectionSettings *settings, ConnectionType connectionType)
: QObject(),
_version(0.0f),
_connectionType(connectionType),
_worker(nullptr),
_isConnected(false),
_connSettings(settings),
_handle(handle),
_bus(AppRegistry::instance().bus()),
_app(AppRegistry::instance().app()),
_replicaSetInfo(nullptr)
{}
bool MongoServer::isConnected() const {
return _isConnected;
}
ConnectionSettings *MongoServer::connectionRecord() const {
return _connSettings.get();
}
MongoServer::~MongoServer() {
clearDatabases();
if (_worker) {
_worker->stopAndDelete();
}
// MongoWorker "_worker" is not deleted here, because it is now owned by
// another thread (call to moveToThread() made in MongoWorker constructor).
// It will be deleted by this thread by means of "deleteLater()", which
// is also specified in MongoWorker constructor.
}
void MongoServer::tryConnect()
{
_bus->send(_worker, new EstablishConnectionRequest(this, _connectionType, _connSettings->uuid().toStdString()));
}
void MongoServer::tryRefresh()
{
_bus->send(_worker, new EstablishConnectionRequest(this, ConnectionRefresh, _connSettings->uuid().toStdString()));
}
void MongoServer::tryRefreshReplicaSetConnection()
{
_bus->send(_worker, new EstablishConnectionRequest(this, ConnectionRefresh, _connSettings->uuid().toStdString()));
}
void MongoServer::tryRefreshReplicaSetFolder(bool expanded, bool showLoading /*= true*/)
{
if (!_connSettings->isReplicaSet())
return;
if (showLoading)
_bus->publish(new ReplicaSetFolderLoading(this));
_bus->send(_worker, new RefreshReplicaSetFolderRequest(this, expanded));
}
QStringList MongoServer::getDatabasesNames() const
{
QStringList result;
for (QList<MongoDatabase *>::const_iterator it = _databases.begin(); it != _databases.end(); ++it) {
MongoDatabase *datab = *it;
result.append(QtUtils::toQString(datab->name()));
}
return result;
}
void MongoServer::addDatabase(MongoDatabase *database) {
_databases.append(database);
}
void MongoServer::createDatabase(const std::string &dbName)
{
_bus->send(_worker, new CreateDatabaseRequest(this, dbName));
}
MongoDatabase *MongoServer::findDatabaseByName(const std::string &dbName) const
{
for (QList<MongoDatabase *>::const_iterator it = _databases.begin(); it != _databases.end(); ++it) {
MongoDatabase *datab = *it;
if (datab->name() == dbName) {
return datab;
}
}
return NULL;
}
void MongoServer::dropDatabase(const std::string &dbName) {
_bus->send(_worker, new DropDatabaseRequest(this, dbName));
}
void MongoServer::insertDocuments(const std::vector<mongo::BSONObj> &objCont,
const MongoNamespace &ns) {
for (std::vector<mongo::BSONObj>::const_iterator it = objCont.begin(); it != objCont.end(); it++) {
insertDocument(*it, ns);
}
}
void MongoServer::insertDocument(const mongo::BSONObj &obj, const MongoNamespace &ns) {
_bus->send(_worker, new InsertDocumentRequest(this, obj, ns));
}
void MongoServer::saveDocuments(const std::vector<mongo::BSONObj> &objCont, const MongoNamespace &ns) {
for (std::vector<mongo::BSONObj>::const_iterator it = objCont.begin(); it != objCont.end(); it++) {
saveDocument(*it, ns);
}
}
void MongoServer::saveDocument(const mongo::BSONObj &obj, const MongoNamespace &ns) {
_bus->send(_worker, new InsertDocumentRequest(this, obj, ns, true));
}
void MongoServer::removeDocuments(mongo::Query query, const MongoNamespace &ns,
RemoveDocumentCount removeCount, int index)
{
_bus->send(_worker, new RemoveDocumentRequest(this, query, ns, removeCount, index));
}
void MongoServer::loadDatabases()
{
_bus->publish(new MongoServerLoadingDatabasesEvent(this));
if (_connSettings->isReplicaSet()) {
tryRefreshReplicaSetConnection();
}
else { // single server
_bus->send(_worker, new LoadDatabaseNamesRequest(this));
}
}
void MongoServer::clearDatabases()
{
qDeleteAll(_databases);
_databases.clear();
}
void MongoServer::handle(EstablishConnectionResponse *event)
{
_connectionType = event->connectionType;
// In any case, replica set info must be updated, there might be reachable secondary(ies).
// Also cached set name must be updated or cleared for failed connections.
updateReplicaSetSettings(event);
// --- Connection Failed
if (event->isError()) {
handleConnectionFailure(event);
return;
}
// --- Connections Successful
// Save various information after successful connection
const ConnectionInfo &info = event->info;
_version = info._version;
_storageEngineType = info._storageEngineType;
_isConnected = true;
// ConnectionRefresh is used just to update connection view (_version, _storageEngineType, _repPrimary etc..)
// So we return here after updating(refreshing) information related to connection view.
if (ConnectionRefresh == event->connectionType) {
if (_connSettings->isReplicaSet()) {
// If it is replica set connection, do not return yet.
LOG_MSG("Replica set refreshed. [" + _connSettings->connectionName() + ']',
mongo::logger::LogSeverity::Info());
}
else { // single server
LOG_MSG("Server refreshed.", mongo::logger::LogSeverity::Info());
return;
}
}
// Only for single servers
if (!_connSettings->isReplicaSet()) {
_bus->publish(new ConnectionEstablishedEvent(this, _connectionType, info));
// Do nothing if this is not a "primary" connection
if (ConnectionPrimary != _connectionType)
return;
}
if (ConnectionPrimary == _connectionType)
LOG_MSG("Establish connection successful. Connection: " + _connSettings->connectionName(),
mongo::logger::LogSeverity::Info());
clearDatabases();
for (auto const& dbname : info._databases) {
MongoDatabase *db = new MongoDatabase(this, dbname);
addDatabase(db); // todo: serverClones for replica sets should not do this
}
if (_connSettings->isReplicaSet()) {
_bus->publish(new ConnectionEstablishedEvent(this, event->connectionType, info));
// In order to do first connection much faster, time consuming refresh
// "repSetMonitor->startOrContinueRefresh(). refreshAll()" is being requested after
// successful connection.
if (ConnectionPrimary == event->connectionType)
_bus->send(_worker, new RefreshReplicaSetFolderRequest(this, false));
}
// Save connected db version if not saved before and if this is primary connection.
QString const versionStr = QString::fromStdString(info._dbVersionStr);
auto const& settingsManager = AppRegistry::instance().settingsManager();
if (ConnectionPrimary == _connectionType &&
!settingsManager->dbVersionsConnected().contains(versionStr)) {
settingsManager->addDbVersionConnected(versionStr);
settingsManager->save();
}
}
void MongoServer::handle(RefreshReplicaSetFolderResponse *event)
{
handleReplicaSetRefreshEvents(event->isError(), event->error(), event->replicaSet, event->expanded);
}
void MongoServer::handle(LoadDatabaseNamesResponse *event)
{
if (event->isError()) {
_bus->publish(new DatabaseListLoadedEvent(this, event->error()));
return;
}
clearDatabases();
for (auto const& dbname : event->databaseNames)
addDatabase(new MongoDatabase(this, dbname));
_bus->publish(new DatabaseListLoadedEvent(this, _databases));
LOG_MSG("Database list refreshed. Connection: " + _connSettings->connectionName(),
mongo::logger::LogSeverity::Info());
}
void MongoServer::handle(InsertDocumentResponse *event)
{
if (event->isError()) {
hideProgressBar();
if (_connSettings->isReplicaSet()) {
if (ConnectionPrimary == _connectionType) { // Insert document from explorer context menu
if (EventError::SetPrimaryUnreachable == event->error().errorCode()) {
auto refreshEvent = ReplicaSetRefreshed(this, event->error(), event->error().replicaSetInfo());
handle(&refreshEvent);
}
}
else { // Insert document from tab results window (Notifier, OutputWindow widget)
_bus->publish(new InsertDocumentResponse(this, event->error()));
}
}
genericEventErrorHandler(event, "Failed to insert document.", _bus, this);
}
else {
_bus->publish(new InsertDocumentResponse(this, event->error()));
LOG_MSG("Document inserted.", mongo::logger::LogSeverity::Info());
}
}
void MongoServer::handle(RemoveDocumentResponse *event)
{
if (event->removeCount == RemoveDocumentCount::MULTI && event->index > 0)
return;
std::string subStr;
switch (event->removeCount) {
case RemoveDocumentCount::ONE: subStr = "document."; break;
case RemoveDocumentCount::MULTI: subStr = "documents."; break;
case RemoveDocumentCount::ALL: subStr = "all documents."; break;
default: subStr = "(logic error)."; break;
}
if (event->isError()) {
hideProgressBar();
if (_connSettings->isReplicaSet() &&
EventError::SetPrimaryUnreachable == event->error().errorCode()) {
auto refreshEvent = ReplicaSetRefreshed(this, event->error(), event->error().replicaSetInfo());
handle(&refreshEvent);
}
genericEventErrorHandler(event, "Failed to remove " + subStr, _bus, this);
}
else { // success
_bus->publish(new RemoveDocumentResponse(this, event->error(), event->removeCount, event->index));
LOG_MSG("Removed " + subStr, mongo::logger::LogSeverity::Info());
}
}
void MongoServer::runWorkerThread()
{
_worker = new MongoWorker(_connSettings->clone(),
AppRegistry::instance().settingsManager()->loadMongoRcJs(),
AppRegistry::instance().settingsManager()->batchSize(),
AppRegistry::instance().settingsManager()->mongoTimeoutSec(),
AppRegistry::instance().settingsManager()->shellTimeoutSec());
}
void MongoServer::handle(CreateDatabaseResponse *event)
{
if (event->isError()) {
if (_connSettings->isReplicaSet() &&
EventError::SetPrimaryUnreachable == event->error().errorCode()) {
auto refreshEvent = ReplicaSetRefreshed(this, event->error(), event->error().replicaSetInfo());
handle(&refreshEvent);
}
genericEventErrorHandler(event, "Failed to create database \'" + event->database + "\'.", _bus, this);
}
else {
loadDatabases();
LOG_MSG("Database \'" + event->database + "\' created.", mongo::logger::LogSeverity::Info());
}
}
void MongoServer::handle(DropDatabaseResponse *event)
{
if (event->isError()) {
if (_connSettings->isReplicaSet() &&
EventError::SetPrimaryUnreachable == event->error().errorCode()) {
auto refreshEvent = ReplicaSetRefreshed(this, event->error(), event->error().replicaSetInfo());
handle(&refreshEvent);
}
genericEventErrorHandler(event, "Failed to drop database \'" + event->database + "\'.", _bus, this);
}
else {
loadDatabases();
LOG_MSG("Database \'" + event->database + "\' dropped.", mongo::logger::LogSeverity::Info());
}
}
void MongoServer::handle(ReplicaSetRefreshed *event)
{
handleReplicaSetRefreshEvents(event->isError(), event->error(), event->replicaSet, false);
}
void MongoServer::changeWorkerShellTimeout(int newTimeout)
{
_worker->changeTimeout(newTimeout);
}
void MongoServer::handleReplicaSetRefreshEvents(bool isError, EventError eventError,
ReplicaSet const& replicaSet, bool expanded)
{
if (isError) { // Primary is unreachable
_replicaSetInfo.reset(new ReplicaSet(replicaSet));
LOG_MSG("Replica set folder refreshed with error. " + eventError.errorMessage() +
". Connection: " + _connSettings->connectionName(), mongo::logger::LogSeverity::Error());
_bus->publish(new ReplicaSetFolderRefreshed(this, eventError, true));
return;
}
// Primary is reachable
// Update replica set settings and mongo server _replicaSetInfo
_replicaSetInfo.reset(new ReplicaSet(replicaSet));
_connSettings->setServerHost(_replicaSetInfo->primary.host());
_connSettings->setServerPort(_replicaSetInfo->primary.port());
_connSettings->replicaSetSettings()->setCachedSetName(
_connSettings->replicaSetSettings()->setNameUserEntered().empty() ? _replicaSetInfo->setName : "");
LOG_MSG("Replica set folder refreshed. Connection: " + _connSettings->connectionName(),
mongo::logger::LogSeverity::Info());
_bus->publish(new ReplicaSetFolderRefreshed(this, expanded));
}
void MongoServer::updateReplicaSetSettings(EstablishConnectionResponse* event)
{
if (!_connSettings->isReplicaSet())
return;
_replicaSetInfo.reset(new ReplicaSet(event->replicaSet));
_connSettings->setServerHost(_replicaSetInfo->primary.host());
_connSettings->setServerPort(_replicaSetInfo->primary.port());
_connSettings->replicaSetSettings()->setCachedSetName(
_connSettings->replicaSetSettings()->setNameUserEntered().empty() ? _replicaSetInfo->setName : "");
if (_connSettings->replicaSetSettings()->setNameUserEntered().empty()) {
// Cache replica set name for 2 times faster first connection
if (ConnectionPrimary == _connectionType) {
ConnectionSettings* originalConnSettings = AppRegistry::instance().settingsManager()
->getConnectionSettingsByUuid(event->info._uuid);
if (originalConnSettings) {
auto setName = event->isError() ? "" : _replicaSetInfo->setName;
originalConnSettings->replicaSetSettings()->setCachedSetName(setName);
AppRegistry::instance().settingsManager()->save();
LOG_MSG("Replica set name cached as \"" + setName + "\".", mongo::logger::LogSeverity::Info());
}
else
LOG_MSG("Failed to cache the replica set name.", mongo::logger::LogSeverity::Warning());
}
}
else { // User entered set name is not empty, clear cached set name just in case
ConnectionSettings* originalConnSettings = AppRegistry::instance().settingsManager()
->getConnectionSettingsByUuid(event->info._uuid);
if (originalConnSettings) {
originalConnSettings->replicaSetSettings()->setCachedSetName("");
AppRegistry::instance().settingsManager()->save();
LOG_MSG("Replica set's cached set name cleared. Using user entered set name.",
mongo::logger::LogSeverity::Info());
}
}
}
void MongoServer::handleConnectionFailure(EstablishConnectionResponse* event)
{
_isConnected = false;
std::stringstream ss("Unknown error");
auto eventErrorReason = event->errorReason;
if (_connSettings->isReplicaSet())
{
ss.clear();
std::string server = "";
if (_connSettings->replicaSetSettings()->members().size() > 0)
server = "[" + _connSettings->replicaSetSettings()->members().front() + "]";
if (event->error().errorCode() == EventError::ErrorCode::ServerHasDifferentMembers) {
ss << "Cannot connect to replica set \"" << _connSettings->connectionName() << "\"" << server
<< ". \n\nA primary with different host name [" << event->replicaSet.primary <<
"] found in server side. "
"Please double check if same host names and ports are used as in server's replica set"
" configuration. \nIf same set name is used for different replica sets, this configuration"
" is supported only on different instances of Robomongo. "
" Please open a new Robomongo instance for each replica set which has the same set name."
"\n\nReason:\n" << event->error().errorMessage();
}
else {
ss << "Cannot connect to replica set \"" << _connSettings->connectionName() << "\"" << server
<< ". \nSet's primary is unreachable.\n\nReason:\n" << event->error().errorMessage();
}
_bus->publish(new ConnectionFailedEvent(this, _handle, event->connectionType, ss.str(),
ConnectionFailedEvent::MongoConnection));
_app->fireConnectionFailedEvent(_handle, event->connectionType, ss.str(),
ConnectionFailedEvent::MongoConnection);
LOG_MSG("Establish connection failed. " + event->error().errorMessage() + ". Connection: "
+ _connSettings->connectionName(), mongo::logger::LogSeverity::Error());
}
else // single server
{
if (EstablishConnectionResponse::ErrorReason::MongoSslConnection == eventErrorReason)
{
auto reason = ConnectionFailedEvent::SslConnection;
ss.clear();
ss << "Cannot connect to the MongoDB at " << connectionRecord()->getFullAddress()
<< ".\n\nError:\n" << "TLS connection failure: " << event->error().errorMessage();
_app->fireConnectionFailedEvent(_handle, _connectionType, ss.str(), reason);
}
else
{
auto reason = (EstablishConnectionResponse::ErrorReason::MongoAuth == eventErrorReason) ?
ConnectionFailedEvent::MongoAuth : ConnectionFailedEvent::MongoConnection;
ss.clear();
ss << "Cannot connect to the MongoDB at " << connectionRecord()->getFullAddress()
<< ".\n\nError:\n" << event->error().errorMessage();
_app->fireConnectionFailedEvent(_handle, _connectionType, ss.str(), reason);
}
// When connection cannot be established, we should cleanup this instance of MongoServer if it wasn't
// shown in UI (i.e. it is not a Secondary connection that is used for shells tab)
if (_connectionType == ConnectionPrimary || _connectionType == ConnectionTest)
{
LOG_MSG("Establish connection failed. " + event->error().errorMessage() +
". Connection: " + _connSettings->connectionName(),
mongo::logger::LogSeverity::Error());
_app->closeServer(this);
}
}
}
void MongoServer::hideProgressBar() const
{
MainWindow* mainWindow = nullptr;
for (auto wid : QApplication::topLevelWidgets()) {
if ((mainWindow = qobject_cast<MainWindow*>(wid)))
break;
}
if(mainWindow)
mainWindow->hideQueryWidgetProgressBar();
}
} // namespace Robomongo
| 21,732
|
C++
|
.cpp
| 435
| 38.866667
| 122
| 0.61387
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,671
|
MongoDatabase.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/MongoDatabase.cpp
|
#include "robomongo/core/domain/MongoDatabase.h"
#include "robomongo/core/domain/MongoServer.h"
#include "robomongo/core/domain/MongoCollection.h"
#include "robomongo/core/mongodb/MongoWorker.h"
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/EventBus.h"
#include "robomongo/core/utils/Logger.h"
#include "robomongo/utils/common.h"
namespace Robomongo
{
R_REGISTER_EVENT(MongoDatabaseCollectionListLoadedEvent)
R_REGISTER_EVENT(MongoDatabaseUsersLoadedEvent)
R_REGISTER_EVENT(MongoDatabaseFunctionsLoadedEvent)
R_REGISTER_EVENT(MongoDatabaseUsersLoadingEvent)
R_REGISTER_EVENT(MongoDatabaseFunctionsLoadingEvent)
R_REGISTER_EVENT(MongoDatabaseCollectionsLoadingEvent)
const std::string MongoDatabase::StorageEngineType::WIRED_TIGER = "wiredTiger";
const std::string MongoDatabase::StorageEngineType::MMAPV1 = "mmapv1";
const float MongoDatabase::DBVersion::MONGODB_2_6 = 2.6f;
const float MongoDatabase::DBVersion::MONGODB_3_0 = 3.0f;
const float MongoDatabase::DBVersion::MONGODB_3_2 = 3.2f;
MongoDatabase::MongoDatabase(MongoServer *server, const std::string &name) :
QObject(),
_system(name == "admin" || name == "local"),
_server(server),
_bus(AppRegistry::instance().bus()),
_name(name) {}
MongoDatabase::~MongoDatabase()
{
clearCollections();
}
void MongoDatabase::loadCollections()
{
_bus->publish(new MongoDatabaseCollectionsLoadingEvent(this));
_bus->send(_server->worker(), new LoadCollectionNamesRequest(this, _name));
}
void MongoDatabase::loadUsers()
{
_bus->publish(new MongoDatabaseUsersLoadingEvent(this));
_bus->send(_server->worker(), new LoadUsersRequest(this, _name));
}
void MongoDatabase::loadFunctions()
{
_bus->publish(new MongoDatabaseFunctionsLoadingEvent(this));
_bus->send(_server->worker(), new LoadFunctionsRequest(this, _name));
}
void MongoDatabase::createCollection(const std::string &collection, long long size, bool capped, int maxDocNum, const mongo::BSONObj& extraOptions)
{
_bus->send(_server->worker(),
new CreateCollectionRequest(this, MongoNamespace(_name, collection), extraOptions, size, capped, maxDocNum));
}
void MongoDatabase::dropCollection(const std::string &collection)
{
_bus->send(_server->worker(), new DropCollectionRequest(this, MongoNamespace(_name, collection)));
}
void MongoDatabase::renameCollection(const std::string &collection, const std::string &newCollection)
{
_bus->send(_server->worker(), new RenameCollectionRequest(this, MongoNamespace(_name, collection),
newCollection));
}
void MongoDatabase::duplicateCollection(const std::string &collection, const std::string &newCollection)
{
_bus->send(_server->worker(), new DuplicateCollectionRequest(this, MongoNamespace(_name, collection), newCollection));
}
void MongoDatabase::copyCollection(MongoServer *server, const std::string &sourceDatabase, const std::string &collection)
{
_bus->send(_server->worker(), new CopyCollectionToDiffServerRequest(this, server->worker(), sourceDatabase, collection, _name));
}
void MongoDatabase::createUser(const MongoUser &user)
{
_bus->send(_server->worker(), new CreateUserRequest(this, _name, user));
}
void MongoDatabase::dropUser(std::string const& userName)
{
_bus->send(_server->worker(), new DropUserRequest(this, _name, userName));
}
void MongoDatabase::createFunction(const MongoFunction &fun)
{
_bus->send(_server->worker(), new CreateFunctionRequest(this, _name, _server->version(), fun));
}
void MongoDatabase::updateFunction(const std::string &name, const MongoFunction &fun)
{
_bus->send(_server->worker(), new CreateFunctionRequest(this, _name, _server->version(), fun, name));
}
void MongoDatabase::dropFunction(const std::string &name)
{
_bus->send(_server->worker(), new DropFunctionRequest(this, _name, _server->version(), name));
}
void MongoDatabase::handle(LoadCollectionNamesResponse *event)
{
if (event->isError()) {
_bus->publish(new MongoDatabaseCollectionListLoadedEvent(this, event->error()));
genericEventErrorHandler(event, "Failed to refresh 'Collections'.", _bus, this);
return;
}
clearCollections();
for (auto const& collectionInfo : event->collectionInfos())
addCollection(new MongoCollection(this, collectionInfo));
_bus->publish(new MongoDatabaseCollectionListLoadedEvent(this, _collections));
LOG_MSG("'Collections' refreshed.", mongo::logger::LogSeverity::Info());
}
void MongoDatabase::handle(CreateFunctionResponse *event)
{
if (event->isError()) {
handleIfReplicaSetUnreachable(event);
genericEventErrorHandler(event, "Failed to create function \'" + event->functionName + "\'.", _bus, this);
}
else {
loadFunctions();
LOG_MSG("Function \'" + event->functionName + "\' created.", mongo::logger::LogSeverity::Info());
}
}
void MongoDatabase::handle(CreateUserResponse *event)
{
if (event->isError()) {
handleIfReplicaSetUnreachable(event);
genericEventErrorHandler(event, "Failed to create user \'" + event->userName + "\'.", _bus, this);
}
else {
loadUsers();
LOG_MSG("User \'" + event->userName + "\' created.", mongo::logger::LogSeverity::Info());
}
}
void MongoDatabase::handle(LoadUsersResponse *event)
{
if (event->isError()) {
_bus->publish(new MongoDatabaseUsersLoadedEvent(this, event->error()));
if (_server->connectionRecord()->isReplicaSet()) // replica set
handleIfReplicaSetUnreachable(event);
genericEventErrorHandler(event, "Failed to refresh 'Users'.", _bus, this);
return;
}
_bus->publish(new MongoDatabaseUsersLoadedEvent(this, this, event->users()));
LOG_MSG("'Users' refreshed.", mongo::logger::LogSeverity::Info());
}
void MongoDatabase::handle(LoadFunctionsResponse *event)
{
if (event->isError()) {
_bus->publish(new MongoDatabaseFunctionsLoadedEvent(this, event->error()));
if (_server->connectionRecord()->isReplicaSet()) // replica set
handleIfReplicaSetUnreachable(event);
genericEventErrorHandler(event, "Failed to refresh 'Functions'.", _bus, this);
return;
}
_bus->publish(new MongoDatabaseFunctionsLoadedEvent(this, this, event->functions()));
LOG_MSG("'Functions' refreshed.", mongo::logger::LogSeverity::Info());
}
void MongoDatabase::clearCollections()
{
qDeleteAll(_collections);
_collections.clear();
}
void MongoDatabase::addCollection(MongoCollection *collection)
{
_collections.push_back(collection);
}
void MongoDatabase::handle(CreateCollectionResponse *event)
{
if (event->isError()) {
handleIfReplicaSetUnreachable(event);
genericEventErrorHandler(event, "Failed to create collection \'" + event->collection + "\'.", _bus, this);
}
else {
loadCollections();
LOG_MSG("Collection \'" + event->collection + "\' created.", mongo::logger::LogSeverity::Info());
}
}
void MongoDatabase::handle(DropCollectionResponse *event)
{
if (event->isError()) {
handleIfReplicaSetUnreachable(event);
genericEventErrorHandler(event, "Failed to drop collection \'" + event->collection + "\'.", _bus, this);
}
else {
loadCollections();
LOG_MSG("Collection \'" + event->collection + "\' dropped", mongo::logger::LogSeverity::Info());
}
}
void MongoDatabase::handle(DropFunctionResponse *event)
{
if (event->isError()) {
handleIfReplicaSetUnreachable(event);
genericEventErrorHandler(event, "Failed to remove function \'" + event->functionName + "\'.", _bus, this);
}
else {
loadFunctions();
LOG_MSG("Function \'" + event->functionName + "\' removed", mongo::logger::LogSeverity::Info());
}
}
void MongoDatabase::handle(DropUserResponse *event)
{
if (event->isError()) {
handleIfReplicaSetUnreachable(event);
genericEventErrorHandler(event, "Failed to drop user \'" + event->username + "\'.", _bus, this);
}
else {
loadUsers();
LOG_MSG("User \'" + event->username + "\' dropped", mongo::logger::LogSeverity::Info());
}
}
void MongoDatabase::handle(RenameCollectionResponse *event)
{
if (event->isError()) {
handleIfReplicaSetUnreachable(event);
genericEventErrorHandler(event, "Failed to rename collection.", _bus, this);
}
else {
loadCollections();
LOG_MSG("Collection \'" + event->oldCollection + "\' renamed to \'" +
event->newCollection +"\'." , mongo::logger::LogSeverity::Info());
}
}
void MongoDatabase::handle(DuplicateCollectionResponse *event)
{
if (event->isError()) {
handleIfReplicaSetUnreachable(event);
genericEventErrorHandler(event, "Failed to duplicate collection \'" + event->sourceCollection + "\'.",
_bus, this);
}
else {
loadCollections();
LOG_MSG("Collection \'" + event->sourceCollection + "\' duplicated as \'" +
event->duplicateCollection + "\'.", mongo::logger::LogSeverity::Info());
}
}
void MongoDatabase::handleIfReplicaSetUnreachable(Event *event)
{
if (!_server->connectionRecord()->isReplicaSet())
return;
if (EventError::SetPrimaryUnreachable == event->error().errorCode()) {
auto refreshEvent = ReplicaSetRefreshed(this, event->error(), event->error().replicaSetInfo());
_server->handle(&refreshEvent);
}
}
}
| 10,496
|
C++
|
.cpp
| 235
| 35.940426
| 151
| 0.637646
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,672
|
MongoCollection.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/MongoCollection.cpp
|
#include "robomongo/core/domain/MongoCollection.h"
#include "robomongo/core/domain/MongoUtils.h"
namespace Robomongo
{
MongoCollection::MongoCollection(MongoDatabase *database, const MongoCollectionInfo &info) :
_ns(info.ns()),
_database(database),
_info(info),
_system(false)
{
// System databases starts from system.*
std::string collectionName = _ns.collectionName();
std::string prefix = "system.";
// Checking whether `collectionName` starts from `system`
if (collectionName.compare(0, prefix.length(), prefix) == 0)
_system = true;
}
/* std::string MongoCollection::sizeString() const
{
return MongoUtils::buildNiceSizeString(_info.sizeBytes()).toStdString();
}
QString MongoCollection::storageSizeString() const
{
return MongoUtils::buildNiceSizeString(_info.storageSizeBytes());
}*/
}
| 932
|
C++
|
.cpp
| 26
| 29.615385
| 96
| 0.670732
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,673
|
MongoQueryInfo.cpp
|
Studio3T_robomongo/src/robomongo/core/domain/MongoQueryInfo.cpp
|
#include "robomongo/core/domain/MongoQueryInfo.h"
#include <mongo/client/dbclient_base.h>
namespace Robomongo
{
namespace detail
{
std::string prepareServerAddress(const std::string &address)
{
size_t pos = address.find_first_of("{");
if (pos != std::string::npos) {
return address.substr(0, pos);
}
return address;
}
}
CollectionInfo::CollectionInfo() {}
CollectionInfo::CollectionInfo(const std::string &server, const std::string &database, const std::string &collection)
:_serverAddress(server),
_ns(database, collection)
{}
bool CollectionInfo::isValid() const
{
return !_serverAddress.empty() && _ns.isValid();
}
MongoQueryInfo::MongoQueryInfo() {}
MongoQueryInfo::MongoQueryInfo(const CollectionInfo &info,
mongo::BSONObj query, mongo::BSONObj fields, int limit, int skip, int batchSize,
int options, bool special) :
_info(info),
_query(query),
_fields(fields),
_limit(limit),
_skip(skip),
_batchSize(batchSize),
_options(options),
_special(special)
{}
}
| 1,231
|
C++
|
.cpp
| 38
| 24.289474
| 121
| 0.602867
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,674
|
SettingsManager.cpp
|
Studio3T_robomongo/src/robomongo/core/settings/SettingsManager.cpp
|
#include "robomongo/core/settings/SettingsManager.h"
#include <QDir>
#include <QFile>
#include <QVariantList>
#include <QUuid>
#include <QJsonArray>
#include <QXmlStreamReader>
#include <QDirIterator>
#include <parser.h>
#include <serializer.h>
#include "robomongo/core/settings/ConnectionSettings.h"
#include "robomongo/core/settings/CredentialSettings.h"
#include "robomongo/core/settings/SshSettings.h"
#include "robomongo/core/settings/SslSettings.h"
#include "robomongo/core/utils/Logger.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/core/utils/StdUtils.h"
#include "robomongo/gui/AppStyle.h"
#include "robomongo/utils/common.h"
#include "robomongo/utils/qzip/qzipreader_p.h"
#include "robomongo/utils/RoboCrypt.h"
namespace Robomongo
{
// 3T config files
auto const Studio3T_PropertiesDat {
QString("%1/.3T/studio-3t/properties.dat").arg(QDir::homePath())
};
auto const DataMongodb_PropertiesDat {
QString("%1/.3T/data-man-mongodb/properties.dat").arg(QDir::homePath())
};
auto const MongoChefPro_PropertiesDat {
QString("%1/.3T/mongochef-pro/properties.dat").arg(QDir::homePath())
};
auto const MongoChefEnt_PropertiesDat {
QString("%1/.3T/mongochef-enterprise/properties.dat").arg(QDir::homePath())
};
const std::vector<std::pair<QString, QString>> S_3T_ZipFile_And_ConfigFile_List
{
{ Studio3T_PropertiesDat, "Studio3T.properties" },
{ DataMongodb_PropertiesDat, "3T.data-man-mongodb.properties" },
{ MongoChefPro_PropertiesDat, "3T.mongochef-pro.properties" },
{ MongoChefEnt_PropertiesDat, "3T.mongochef-enterprise.properties" }
};
// Extract zipFile and find the value of "anonymousID" field in propFile
QString extractAnonymousIDFromZip(QString const& zipFile, QString const& propfile);
// Extract "anonymousID" from a config file
QString extractAnonymousID(QString const& configFile);
/**
* @brief Version of schema
*/
const QString SchemaVersion = "2.0";
const auto CONFIG_FILE_0_8_5 {
QString("%1/.config/robomongo/robomongo.json").arg(QDir::homePath())
};
const auto CONFIG_FILE_1_0_RC1 {
QString("%1/.config/robomongo/1.0/robomongo.json").arg(QDir::homePath())
};
const auto CONFIG_FILE_1_1_0_BETA {
QString("%1/.3T/robomongo/1.1.0-Beta/robomongo.json").arg(QDir::homePath())
};
/**
* @brief Robomongo config. files of old versions
*/
// Important: In order to import connections from a version, config. file path must
// be defined and placed into the vector initializer list below in order.
std::vector<QString> const SettingsManager::_configFilesOfOldVersions
{
QString("%1/.3T/robo-3t/1.4.3/robo3t.json").arg(QDir::homePath()), // CONFIG_FILE_1_4_3
QString("%1/.3T/robo-3t/1.4.2/robo3t.json").arg(QDir::homePath()), // CONFIG_FILE_1_4_2
QString("%1/.3T/robo-3t/1.4.1/robo3t.json").arg(QDir::homePath()), // CONFIG_FILE_1_4_1
QString("%1/.3T/robo-3t/1.4.0/robo3t.json").arg(QDir::homePath()), // CONFIG_FILE_1_4_0
QString("%1/.3T/robo-3t/1.3.1/robo3t.json").arg(QDir::homePath()), // CONFIG_FILE_1_3_1
QString("%1/.3T/robo-3t/1.3.0/robo3t.json").arg(QDir::homePath()), // CONFIG_FILE_1_3_0_BETA
QString("%1/.3T/robo-3t/1.2.1/robo3t.json").arg(QDir::homePath()), // CONFIG_FILE_1_2_1
QString("%1/.3T/robo-3t/1.2.0/robo3t.json").arg(QDir::homePath()), // CONFIG_FILE_1_2_0_BETA
QString("%1/.3T/robo-3t/1.1.1/robo3t.json").arg(QDir::homePath()), // CONFIG_FILE_1_1_1
CONFIG_FILE_1_1_0_BETA, // CONFIG_FILE_1_1_0_BETA
QString("%1/.3T/robomongo/1.0.0/robomongo.json").arg(QDir::homePath()), // CONFIG_FILE_1_0_0
CONFIG_FILE_1_0_RC1, // CONFIG_FILE_1_0_RC1
QString("%1/.config/robomongo/0.9/robomongo.json").arg(QDir::homePath()), // CONFIG_FILE_0_9
CONFIG_FILE_0_8_5 // CONFIG_FILE_0_8_5
};
std::vector<ConnectionSettings*> SettingsManager::_connections;
/**
* Creates SettingsManager for config file in default location
* ~/.config/robomongo/robomongo.json
*/
SettingsManager::SettingsManager() :
_version(SchemaVersion),
_uuidEncoding(DefaultEncoding),
_timeZone(Utc),
_viewMode(Robomongo::Tree),
_autocompletionMode(AutocompleteAll),
_loadMongoRcJs(false),
_minimizeToTray(false),
_lineNumbers(false),
_disableConnectionShortcuts(false),
_batchSize(50),
_textFontFamily(""),
_textFontPointSize(-1),
_mongoTimeoutSec(10),
_shellTimeoutSec(15),
_imported(false)
{
if (!QDir().mkpath(ConfigDir))
LOG_MSG("ERROR: Could not create settings path: " + ConfigDir, mongo::logger::LogSeverity::Error());
RoboCrypt::initKey();
if (!load()) { // if load fails (probably due to non-existing config. file or directory)
save(); // create empty settings file
load(); // try loading again for the purpose of import from previous Robomongo versions
}
LOG_MSG("SettingsManager initialized in " + ConfigFilePath, mongo::logger::LogSeverity::Info(), false);
}
SettingsManager::~SettingsManager()
{
std::for_each(_connections.begin(), _connections.end(), stdutils::default_delete<ConnectionSettings *>());
}
/**
* Load settings from config file.
* @return true if success, false otherwise
*/
bool SettingsManager::load()
{
if (!QFile::exists(ConfigFilePath))
return false;
QFile f(ConfigFilePath);
if (!f.open(QIODevice::ReadOnly))
return false;
bool ok;
QJson::Parser parser;
QVariantMap map = parser.parse(f.readAll(), &ok).toMap();
if (!ok)
return false;
loadFromMap(map);
return true;
}
/**
* Saves all settings to config file.
* @return true if success, false otherwise
*/
bool SettingsManager::save()
{
QVariantMap const& map = convertToMap();
QFile f(ConfigFilePath);
if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
LOG_MSG("ERROR: Could not write settings to: " + ConfigFilePath, mongo::logger::LogSeverity::Error());
return false;
}
bool ok;
QJson::Serializer s;
s.setIndentMode(QJson::IndentFull);
s.serialize(map, &f, &ok);
LOG_MSG("Settings saved to: " + ConfigFilePath, mongo::logger::LogSeverity::Info());
return ok;
}
void SettingsManager::addCacheData(QString const& key, QVariant const& value)
{
_cacheData.insert(key, value);
}
QVariant SettingsManager::cacheData(QString const& key) const
{
return _cacheData.value(key);
}
/**
* Load settings from the map. Existings settings will be overwritten.
*/
void SettingsManager::loadFromMap(QVariantMap &map)
{
// 1. Load version
_version = map.value("version").toString();
// 2. Load UUID encoding
int encoding = map.value("uuidEncoding").toInt();
if (encoding > 3 || encoding < 0)
encoding = 0;
_uuidEncoding = (UUIDEncoding)encoding;
// 3. Load view mode
if (map.contains("viewMode")) {
int viewMode = map.value("viewMode").toInt();
if (viewMode > 2 || viewMode < 0)
viewMode = Custom; // Default View Mode
_viewMode = (ViewMode)viewMode;
}
else {
_viewMode = Custom; // Default View Mode
}
_autoExpand = map.contains("autoExpand") ? map.value("autoExpand").toBool() : true;
_autoExec = map.contains("autoExec") ? map.value("autoExec").toBool() : true;
_minimizeToTray = map.contains("minimizeToTray") ? map.value("minimizeToTray").toBool() : false;
_lineNumbers = map.contains("lineNumbers") ? map.value("lineNumbers").toBool() : false;
_imported = map.contains("imported") ? map.value("imported").toBool() : false;
_programExitedNormally = map.contains("programExitedNormally") ?
map.value("programExitedNormally").toBool() : true;
_disableHttpsFeatures = map.contains("disableHttpsFeatures") ?
map.value("disableHttpsFeatures").toBool() : false;
_debugMode = map.contains("debugMode") ? map.value("debugMode").toBool() : false;
// 4. Load TimeZone
int timeZone = map.value("timeZone").toInt();
if (timeZone > 1 || timeZone < 0)
timeZone = 0;
_timeZone = (SupportedTimes)timeZone;
_loadMongoRcJs = map.value("loadMongoRcJs").toBool();
_disableConnectionShortcuts = map.value("disableConnectionShortcuts").toBool();
if (map.contains("acceptedEulaVersions"))
_acceptedEulaVersions = map.value("acceptedEulaVersions").toStringList().toSet();
if (map.contains("dbVersionsConnected"))
_dbVersionsConnected = map.value("dbVersionsConnected").toStringList().toSet();
// Load anonymousID
_anonymousID = getOrCreateAnonymousID(map);
// Load AutocompletionMode
if (map.contains("autocompletionMode")) {
int autocompletionMode = map.value("autocompletionMode").toInt();
if (autocompletionMode < 0 || autocompletionMode > 2)
autocompletionMode = AutocompleteAll; // Default Mode
_autocompletionMode = (AutocompletionMode)autocompletionMode;
}
else {
_autocompletionMode = AutocompleteAll; // Default Mode
}
// Load Batch Size
_batchSize = map.value("batchSize").toInt();
if (_batchSize == 0)
_batchSize = 50;
if (map.contains("checkForUpdates"))
_checkForUpdates = map.value("checkForUpdates").toBool();
_currentStyle = map.value("style").toString();
if (_currentStyle.isEmpty()) {
_currentStyle = AppStyle::StyleName;
}
// Load font information
_textFontFamily = map.value("textFontFamily").toString();
_textFontPointSize = map.value("textFontPointSize").toInt();
if (map.contains("mongoTimeoutSec")) {
_mongoTimeoutSec = map.value("mongoTimeoutSec").toInt();
}
if (map.contains("shellTimeoutSec")) {
_shellTimeoutSec = map.value("shellTimeoutSec").toInt();
}
// 5. Load connections
_connections.clear();
QVariantList const& list = map.value("connections").toList();
for (auto const& conn : list) {
auto connSettings = new ConnectionSettings(false);
connSettings->fromVariant(conn.toMap());
addConnection(connSettings);
}
_toolbars = map.value("toolbars").toMap();
ToolbarSettingsContainerType::const_iterator it = _toolbars.find("connect");
if (_toolbars.end() == it)
_toolbars["connect"] = true;
it = _toolbars.find("open_save");
if (_toolbars.end() == it)
_toolbars["open_save"] = true;
it = _toolbars.find("exec");
if (_toolbars.end() == it)
_toolbars["exec"] = true;
it = _toolbars.find("explorer");
if (_toolbars.end() == it)
_toolbars["explorer"] = true;
it = _toolbars.find("logs");
if (_toolbars.end() == it)
_toolbars["logs"] = false;
_cacheData = map.value("cacheData").toMap();
// Load connection settings from previous versions of Robomongo
importFromOldVersion();
}
/**
* Save all settings to map.
*/
QVariantMap SettingsManager::convertToMap() const
{
QVariantMap map;
// 1. Save schema version
map.insert("version", SchemaVersion);
// 2. Save UUID encoding
map.insert("uuidEncoding", _uuidEncoding);
// 3. Save TimeZone encoding
map.insert("timeZone", _timeZone);
// 4. Save view mode
map.insert("viewMode", _viewMode);
map.insert("autoExpand", _autoExpand);
map.insert("lineNumbers", _lineNumbers);
// 5. Save Autocompletion mode
map.insert("autocompletionMode", _autocompletionMode);
// 6. Save loadInitJs
map.insert("loadMongoRcJs", _loadMongoRcJs);
// 7. Save disableConnectionShortcuts
map.insert("disableConnectionShortcuts", _disableConnectionShortcuts);
// 8. Save acceptedEulaVersions array
QJsonArray arr;
for (auto const& str : _acceptedEulaVersions)
arr.push_back(str);
map.insert("acceptedEulaVersions", arr.toVariantList());
// x. Save unique set of db versions connected
QJsonArray dbVersionsArr;
for (auto const& version : _dbVersionsConnected)
dbVersionsArr.push_back(version);
map.insert("dbVersionsConnected", dbVersionsArr.toVariantList());
// 9. Save batchSize
map.insert("batchSize", _batchSize);
map.insert("checkForUpdates", _checkForUpdates);
map.insert("mongoTimeoutSec", _mongoTimeoutSec);
map.insert("shellTimeoutSec", _shellTimeoutSec);
// 10. Save style
map.insert("style", _currentStyle);
// 11. Save font information
map.insert("textFontFamily", _textFontFamily);
map.insert("textFontPointSize", _textFontPointSize);
// 12. Save connections
QVariantList list;
for (auto const conn : _connections)
list.append(conn->toVariant().toMap());
map.insert("connections", list);
map.insert("autoExec", _autoExec);
map.insert("minimizeToTray", _minimizeToTray);
map.insert("toolbars", _toolbars);
map.insert("imported", _imported);
map.insert("anonymousID", _anonymousID);
map.insert("cacheData", _cacheData);
map.insert("programExitedNormally", _programExitedNormally);
map.insert("disableHttpsFeatures", _disableHttpsFeatures);
map.insert("debugMode", _debugMode);
return map;
}
QString SettingsManager::getOrCreateAnonymousID(QVariantMap const& map) const
{
QString anonymousID = "";
// If anonymousID has never been created or is empty, create a new one. Otherwise load the existing.
if (map.contains("anonymousID")) {
QUuid id = map.value("anonymousID").toString();
if (!id.isNull())
anonymousID = id.toString();
}
// Search and import "anonymousID" from other Studio 3T config files
for (auto const& zipFileAndConfigFile : S_3T_ZipFile_And_ConfigFile_List) {
if (!anonymousID.isEmpty())
break;
QUuid const& id = extractAnonymousIDFromZip(zipFileAndConfigFile.first, zipFileAndConfigFile.second);
if (!id.isNull())
anonymousID = id.toString();
}
// Search and import "anonymousID" from other Robo 3T old config files starting from latest
for (auto const& oldConfigFile : _configFilesOfOldVersions) {
if (!anonymousID.isEmpty())
break;
// Don't import from 1.1-Beta due to a problem where Beta might have redundantly created new UUID
if (oldConfigFile == CONFIG_FILE_1_1_0_BETA)
continue;
// Stop searching in 1_0_RC1 or older versions, "anonymousID" is introduced in version 1.0
if (oldConfigFile == CONFIG_FILE_1_0_RC1)
break;
anonymousID = extractAnonymousID(oldConfigFile);
}
// Search and import "anonymousID" from any other (ideally newer version) Robo 3T config files
if (anonymousID.isEmpty()) {
auto const dir1 = QString("%1/.3T/robo-3t").arg(QDir::homePath());
QDirIterator iter1 { dir1, QStringList() << "robo*.json", QDir::Files,
QDirIterator::Subdirectories };
while (iter1.hasNext()) {
anonymousID = extractAnonymousID(iter1.next());
if (!anonymousID.isEmpty())
break;
}
if (anonymousID.isEmpty()) {
auto const dir2 = QString("%1/.3T/robomongo").arg(QDir::homePath());
QDirIterator iter2 { dir2, QStringList() << "robo*.json", QDir::Files,
QDirIterator::Subdirectories };
while (iter2.hasNext()) {
anonymousID = extractAnonymousID(iter2.next());
if (!anonymousID.isEmpty())
break;
}
}
}
// Couldn't find/import any, create a new anonymousID
if (anonymousID.isEmpty())
anonymousID = QUuid::createUuid().toString();
anonymousID.remove('{');
anonymousID.remove('}');
return anonymousID;
}
/**
* Adds connection to the end of list and set it's uniqueID
*/
void SettingsManager::addConnection(ConnectionSettings *connection)
{
_connections.push_back(connection);
}
/**
* Removes connection by index
*/
void SettingsManager::removeConnection(ConnectionSettings *connection)
{
ConnectionSettingsContainerType::iterator it = std::find(_connections.begin(), _connections.end(), connection);
if (it != _connections.end()) {
_connections.erase(it);
delete connection;
}
}
ConnectionSettings* SettingsManager::getConnectionSettingsByUuid(QString const& uuid) const
{
for (auto const connSettings : _connections){
if (connSettings->uuid() == uuid)
return connSettings;
}
LOG_MSG("Failed to find connection settings object by UUID.", mongo::logger::LogSeverity::Warning());
return nullptr;
}
ConnectionSettings* SettingsManager::getConnectionSettingsByUuid(std::string const& uuid) const
{
return getConnectionSettingsByUuid(QString::fromStdString(uuid));
}
void SettingsManager::setCurrentStyle(const QString& style)
{
_currentStyle = style;
}
void SettingsManager::setTextFontFamily(const QString& fontFamily)
{
_textFontFamily = fontFamily;
}
void SettingsManager::setTextFontPointSize(int pointSize) {
_textFontPointSize = pointSize > 0 ? pointSize : -1;
}
void SettingsManager::reorderConnections(const ConnectionSettingsContainerType &connections)
{
_connections = connections;
}
void SettingsManager::setToolbarSettings(const QString toolbarName, const bool visible)
{
_toolbars[toolbarName] = visible;
}
void SettingsManager::importFromOldVersion()
{
if (_imported)
return;
// Import only from the latest version
for (auto const& configFile : _configFilesOfOldVersions) {
if (QFile::exists(configFile)) {
importFromFile(configFile);
setImported(true);
return;
}
}
}
bool SettingsManager::importConnectionsFrom_0_8_5()
{
// Load old configuration file (used till version 0.8.5)
if (!QFile::exists(CONFIG_FILE_0_8_5))
return false;
QFile oldConfigFile(CONFIG_FILE_0_8_5);
if (!oldConfigFile.open(QIODevice::ReadOnly))
return false;
bool ok;
QJson::Parser parser;
QVariantMap vmap = parser.parse(oldConfigFile.readAll(), &ok).toMap();
if (!ok)
return false;
QVariantList vconns = vmap.value("connections").toList();
for (QVariantList::iterator itconn = vconns.begin(); itconn != vconns.end(); ++itconn)
{
QVariantMap vconn = (*itconn).toMap();
auto conn = new ConnectionSettings(false);
conn->setImported(true);
conn->setConnectionName(QtUtils::toStdString(vconn.value("connectionName").toString()));
conn->setServerHost(QtUtils::toStdString(vconn.value("serverHost").toString().left(300)));
conn->setServerPort(vconn.value("serverPort").toInt());
conn->setDefaultDatabase(QtUtils::toStdString(vconn.value("defaultDatabase").toString()));
// SSH settings
if (vconn.contains("sshAuthMethod")) {
SshSettings *ssh = conn->sshSettings();
ssh->setHost(QtUtils::toStdString(vconn.value("sshHost").toString()));
ssh->setUserName(QtUtils::toStdString(vconn.value("sshUserName").toString()));
ssh->setPort(vconn.value("sshPort").toInt());
ssh->setUserPassword(QtUtils::toStdString(vconn.value("sshUserPassword").toString()));
ssh->setPublicKeyFile(QtUtils::toStdString(vconn.value("sshPublicKey").toString()));
ssh->setPrivateKeyFile(QtUtils::toStdString(vconn.value("sshPrivateKey").toString()));
ssh->setPassphrase(QtUtils::toStdString(vconn.value("sshPassphrase").toString()));
int const auth = vconn.value("sshAuthMethod").toInt();
ssh->setEnabled(auth == 1 || auth == 2);
ssh->setAuthMethod(auth == 2 ? "publickey" : "password");
}
// SSL settings
if (vconn.contains("sshEnabled")) {
SslSettings *ssl = conn->sslSettings();
ssl->enableSSL(vconn.value("enabled").toBool());
ssl->setPemKeyFile(QtUtils::toStdString(vconn.value("sslPemKeyFile").toString()));
}
// Credentials
QVariantList vcreds = vconn.value("credentials").toList();
for (QVariantList::const_iterator itcred = vcreds.begin(); itcred != vcreds.end(); ++itcred) {
QVariantMap vcred = (*itcred).toMap();
auto cred = new CredentialSettings();
cred->setUserName(vcred.value("userName").toString().toStdString());
cred->setUserPassword(vcred.value("userPassword").toString().toStdString());
cred->setDatabaseName(vcred.value("databaseName").toString().toStdString());
cred->setMechanism("MONGODB-CR");
cred->setUseManuallyVisibleDbs(vcred.value("useManuallyVisibleDbs").toBool());
cred->setManuallyVisibleDbs(vcred.value("manuallyVisibleDbs").toString().toStdString());
cred->setEnabled(vcred.value("enabled").toBool());
conn->addCredential(cred);
}
// Check that we didn't have similar connection
bool matched = false;
for (std::vector<ConnectionSettings*>::const_iterator it = _connections.begin(); it != _connections.end(); ++it) {
ConnectionSettings *econn = *it; // Existing connection
if (conn->serverPort() != econn->serverPort() ||
conn->serverHost() != econn->serverHost() ||
conn->defaultDatabase() != econn->defaultDatabase())
continue;
CredentialSettings *cred = conn->primaryCredential();
CredentialSettings *ecred = econn->primaryCredential();
if (cred->databaseName() != ecred->databaseName() ||
cred->userName() != ecred->userName() ||
cred->userPassword() != ecred->userPassword() ||
cred->enabled() != ecred->enabled())
continue;
SshSettings *ssh = conn->sshSettings();
SshSettings *essh = econn->sshSettings();
if (ssh->enabled() != essh->enabled() ||
ssh->port() != essh->port() ||
ssh->host() != essh->host() ||
ssh->privateKeyFile() != essh->privateKeyFile() ||
ssh->userPassword() != essh->userPassword() ||
ssh->userName() != essh->userName())
continue;
matched = true;
break;
}
// Import connection only if we didn't find similar one
if (!matched)
addConnection(conn);
}
return true;
}
bool SettingsManager::importFromFile(QString const& oldConfigFilePath)
{
if (oldConfigFilePath == CONFIG_FILE_0_8_5) {
importConnectionsFrom_0_8_5();
return true;
}
if (!QFile::exists(oldConfigFilePath))
return false;
QFile oldConfigFile(oldConfigFilePath);
if (!oldConfigFile.open(QIODevice::ReadOnly))
return false;
bool ok;
QJson::Parser parser;
QVariantMap vmap = parser.parse(oldConfigFile.readAll(), &ok).toMap();
if (!ok)
return false;
//// Import keys
_autoExpand = vmap.value("autoExpand").toBool();
_lineNumbers = vmap.value("lineNumbers").toBool();
_debugMode = vmap.value("debugMode").toBool();
_shellTimeoutSec = vmap.value("shellTimeoutSec").toInt();
//// Import connections
for (auto const& vcon : vmap.value("connections").toList()) {
QVariantMap const& vconn = vcon.toMap();
auto connSettings = new ConnectionSettings(false);
connSettings->fromVariant(vconn);
connSettings->setImported(true);
addConnection(connSettings);
}
return true;
}
int SettingsManager::importedConnectionsCount() {
return (std::count_if(_connections.cbegin(), _connections.cend(),
[](auto conn) { return conn->imported(); }
));
}
QString extractAnonymousIDFromZip(QString const& zipFile, QString const& propfile)
{
QZipReader zipReader(zipFile);
if (!zipReader.exists() || !zipReader.isReadable())
return QString("");
QXmlStreamReader reader(zipReader.fileData(propfile));
while (!reader.atEnd()) {
reader.readNext();
if (reader.text().toString() == "AnonymousID") {
reader.readNext();
reader.readNext();
reader.readNext();
reader.readNext();
return reader.text().toString();
}
}
return QString("");
}
QString extractAnonymousID(QString const& configFilePath)
{
if (!QFile::exists(configFilePath))
return QString("");
QFile oldConfigFile(configFilePath);
if (!oldConfigFile.open(QIODevice::ReadOnly))
return QString("");
bool ok = false;
QJson::Parser parser;
QVariantMap const& map = parser.parse(oldConfigFile.readAll(), &ok).toMap();
if (!ok)
return QString("");
QString anonymousID;
if (map.contains("anonymousID")) {
QUuid const& id = map.value("anonymousID").toString();
if (!id.isNull())
anonymousID = id.toString();
}
anonymousID.remove('{');
anonymousID.remove('}');
return anonymousID;
}
}
| 27,711
|
C++
|
.cpp
| 610
| 35.17377
| 126
| 0.603227
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,675
|
SslSettings.cpp
|
Studio3T_robomongo/src/robomongo/core/settings/SslSettings.cpp
|
#include "robomongo/core/settings/SslSettings.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/utils/RoboCrypt.h"
namespace Robomongo
{
SslSettings::SslSettings() :
_sslEnabled(false), _caFile(""), _pemKeyFile(""), _pemPassPhrase(""), _crlFile(""),
_allowInvalidHostnames(false), _allowInvalidCertificates(false), _usePemFile(false),
_useAdvancedOptions(false), _askPassphrase(false)
{}
SslSettings *SslSettings::clone() const
{
SslSettings *cloned = new SslSettings(*this);
return cloned;
}
QVariant SslSettings::toVariant() const
{
QVariantMap map;
map.insert("sslEnabled", sslEnabled());
map.insert("caFile", QtUtils::toQString(caFile()));
map.insert("usePemFile", usePemFile());
map.insert("pemKeyFile", QtUtils::toQString(pemKeyFile()));
map.insert("pemPassPhraseEncrypted", pemPassPhrase().empty() ? "" :
QtUtils::toQString(RoboCrypt::encrypt(pemPassPhrase())));
map.insert("useAdvancedOptions", useAdvancedOptions());
map.insert("crlFile", QtUtils::toQString(crlFile()));
map.insert("allowInvalidHostnames", allowInvalidHostnames());
map.insert("allowInvalidCertificates", allowInvalidCertificates());
map.insert("askPassphrase", askPassphrase());
return map;
}
void SslSettings::fromVariant(const QVariantMap &map)
{
enableSSL(map.value("sslEnabled").toBool());
setCaFile(QtUtils::toStdString(map.value("caFile").toString()));
setUsePemFile(map.value("usePemFile").toBool());
setPemKeyFile(QtUtils::toStdString(map.value("pemKeyFile").toString()));
// From version Robo 1.3 "pemPassPhraseEncrypted" is used instead of "pemPassPhrase" in config. file
if (map.contains("pemPassPhrase")) // Robo 1.2 and below
setPemPassPhrase((map.value("pemPassPhrase").toString().toStdString()));
else if (map.contains("pemPassPhraseEncrypted")) // From Robo 1.3
setPemPassPhrase(RoboCrypt::decrypt((map.value("pemPassPhraseEncrypted").toString().toStdString())));
setUseAdvancedOptions(map.value("useAdvancedOptions").toBool());
setCrlFile(QtUtils::toStdString(map.value("crlFile").toString()));
setAllowInvalidHostnames(map.value("allowInvalidHostnames").toBool());
setAllowInvalidCertificates(map.value("allowInvalidCertificates").toBool());
setAskPassphrase(map.value("askPassphrase").toBool());
}
}
| 2,578
|
C++
|
.cpp
| 49
| 44.163265
| 113
| 0.676084
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,676
|
ReplicaSetSettings.cpp
|
Studio3T_robomongo/src/robomongo/core/settings/ReplicaSetSettings.cpp
|
#include "robomongo/core/settings/ReplicaSetSettings.h"
#include "robomongo/core/utils/QtUtils.h"
namespace Robomongo
{
ReplicaSetSettings::ReplicaSetSettings()
: _cachedSetName(""), _members(), _readPreference(ReadPreference::PRIMARY)
{}
ReplicaSetSettings::ReplicaSetSettings(const mongo::MongoURI& uri)
: ReplicaSetSettings()
{
_cachedSetName = uri.getSetName();
for (auto const& server : uri.getServers()) {
_members.push_back(server.host() + ":" + std::to_string(server.port()));
}
}
ReplicaSetSettings *ReplicaSetSettings::clone() const
{
ReplicaSetSettings *cloned = new ReplicaSetSettings(*this);
return cloned;
}
QVariant ReplicaSetSettings::toVariant() const
{
QVariantMap map;
map.insert("setNameUserEntered", QString::fromStdString(_setNameUserEntered));
map.insert("cachedSetName", QString::fromStdString(_cachedSetName));
int idx = 0;
for (std::string const& str : _members) {
map.insert(QString::number(idx), QtUtils::toQString(str));
++idx;
}
map.insert("readPreference", static_cast<int>(readPreference()));
return map;
}
void ReplicaSetSettings::fromVariant(const QVariantMap &map)
{
setSetNameUserEntered(map.value("setNameUserEntered").toString().toStdString());
setCachedSetName(map.value("cachedSetName").toString().toStdString());
// Extract and set replica members
std::vector<std::string> vec;
auto itr = map.begin();
int idx = 0;
do
{
itr = map.find(QString::number(idx));
if (map.end() == itr) break;
vec.push_back(itr->toString().toStdString());
++idx;
} while (map.end() != itr);
setMembers(vec);
// Extract and set read reference
setReadPreference(static_cast<ReadPreference>(map.value("readPreference").toInt()));
}
void ReplicaSetSettings::setMembers(const std::vector<std::string>& members)
{
_members.clear();
for (auto const& member : members)
_members.push_back(member);
}
void ReplicaSetSettings::setMembers(const std::vector<std::pair<std::string, bool>>& membersAndHealts)
{
_members.clear();
for (auto const& memberAndHealth : membersAndHealts)
_members.push_back(memberAndHealth.first);
}
std::vector<mongo::HostAndPort> ReplicaSetSettings::membersToHostAndPort() const
{
std::vector<mongo::HostAndPort> membersHostAndPort;
for (auto const& member : _members)
membersHostAndPort.push_back(mongo::HostAndPort(member));
return membersHostAndPort;
}
}
| 2,813
|
C++
|
.cpp
| 72
| 30.805556
| 106
| 0.638071
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,677
|
CredentialSettings.cpp
|
Studio3T_robomongo/src/robomongo/core/settings/CredentialSettings.cpp
|
#include "robomongo/core/settings/CredentialSettings.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/utils/RoboCrypt.h"
namespace Robomongo
{
CredentialSettings::CredentialSettings() :
_userName(),
_userPassword(),
_databaseName(),
_mechanism(),
_enabled(false),
_useManuallyVisibleDbs(false),
_manuallyVisibleDbs()
{
}
CredentialSettings::CredentialSettings(const QVariantMap &map) :
_userName(QtUtils::toStdString(map.value("userName").toString())),
_databaseName(QtUtils::toStdString(map.value("databaseName").toString())),
_mechanism(QtUtils::toStdString(map.value("mechanism").toString())),
_useManuallyVisibleDbs(map.value("useManuallyVisibleDbs").toBool()),
_manuallyVisibleDbs(QtUtils::toStdString(map.value("manuallyVisibleDbs").toString())),
_enabled(map.value("enabled").toBool())
{
// From version Robo 1.3 "userPasswordEncrypted" is used instead of "userPassword" in config. file
if(map.contains("userPassword")) // Robo 1.2 and below
_userPassword = map.value("userPassword").toString().toStdString();
else if(map.contains("userPasswordEncrypted")) // From Robo 1.3
_userPassword = RoboCrypt::decrypt(map.value("userPasswordEncrypted").toString().toStdString());
}
/**
* @brief Clones credential settings.
*/
CredentialSettings *CredentialSettings::clone() const
{
CredentialSettings *cloned = new CredentialSettings(*this);
return cloned;
}
QVariant CredentialSettings::toVariant() const
{
QVariantMap map;
map.insert("userName", QtUtils::toQString(userName()));
map.insert("userPasswordEncrypted", userPassword().empty() ? "" :
QtUtils::toQString(RoboCrypt::encrypt(userPassword())));
map.insert("databaseName", QtUtils::toQString(databaseName()));
map.insert("mechanism", QtUtils::toQString(mechanism()));
map.insert("useManuallyVisibleDbs", _useManuallyVisibleDbs);
map.insert("manuallyVisibleDbs", QtUtils::toQString(_manuallyVisibleDbs));
map.insert("enabled", enabled());
return map;
}
}
| 2,276
|
C++
|
.cpp
| 51
| 36.764706
| 108
| 0.666367
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,678
|
SshSettings.cpp
|
Studio3T_robomongo/src/robomongo/core/settings/SshSettings.cpp
|
#include "robomongo/core/settings/SshSettings.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/utils/RoboCrypt.h"
namespace Robomongo
{
SshSettings::SshSettings() :
_port(22),
_authMethod("publickey"),
_enabled(false),
_askPassword(false),
_logLevel(1) {
}
SshSettings *SshSettings::clone() const {
SshSettings *cloned = new SshSettings(*this);
return cloned;
}
QVariant SshSettings::toVariant() const {
QVariantMap map;
map.insert("host", QtUtils::toQString(host()));
map.insert("port", port());
map.insert("userName", QtUtils::toQString(userName()));
map.insert("userPasswordEncrypted", userPassword().empty() ? "" :
QtUtils::toQString(RoboCrypt::encrypt(userPassword())));
map.insert("privateKeyFile", QtUtils::toQString(privateKeyFile()));
map.insert("publicKeyFile", QtUtils::toQString(publicKeyFile()));
map.insert("passphraseEncrypted", passphrase().empty() ? "" :
QtUtils::toQString(RoboCrypt::encrypt(passphrase())));
map.insert("method", QtUtils::toQString(authMethod()));
map.insert("enabled", enabled());
map.insert("askPassword", askPassword());
return map;
}
void SshSettings::fromVariant(const QVariantMap &map) {
setHost(QtUtils::toStdString(map.value("host").toString()));
setPort(map.value("port").toInt());
setUserName(QtUtils::toStdString(map.value("userName").toString()));
// From version Robo 1.3 "userPasswordEncrypted" is used instead of "userPassword" in config. file
if (map.contains("userPassword")) // Robo 1.2 and below
setUserPassword((map.value("userPassword").toString().toStdString()));
else if (map.contains("userPasswordEncrypted")) // From Robo 1.3
setUserPassword(RoboCrypt::decrypt((map.value("userPasswordEncrypted").toString().toStdString())));
setPrivateKeyFile(QtUtils::toStdString(map.value("privateKeyFile").toString()));
setPublicKeyFile(QtUtils::toStdString(map.value("publicKeyFile").toString()));
// From version Robo 1.3 "passphraseEncrypted" is used instead of "passphrase" in config. file
if (map.contains("passphrase")) // Robo 1.2 and below
setPassphrase((map.value("passphrase").toString().toStdString()));
else if (map.contains("passphraseEncrypted")) // From Robo 1.3
setPassphrase(RoboCrypt::decrypt((map.value("passphraseEncrypted").toString().toStdString())));
setAuthMethod(QtUtils::toStdString(map.value("method").toString()));
setEnabled(map.value("enabled").toBool());
setAskPassword(map.value("askPassword").toBool());
}
}
| 2,846
|
C++
|
.cpp
| 53
| 44.358491
| 111
| 0.647862
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,679
|
ConnectionSettings.cpp
|
Studio3T_robomongo/src/robomongo/core/settings/ConnectionSettings.cpp
|
#include "robomongo/core/settings/ConnectionSettings.h"
#include <stdio.h>
#include <QUuid>
#include "robomongo/core/settings/CredentialSettings.h"
#include "robomongo/core/settings/ReplicaSetSettings.h"
#include "robomongo/core/settings/SshSettings.h"
#include "robomongo/core/settings/SslSettings.h"
#include "robomongo/core/utils/QtUtils.h"
#include <boost/algorithm/string.hpp>
namespace
{
const unsigned port = 27017;
const char *defaultServerHost = "localhost";
const char *defaultNameConnection = "New Connection";
const int maxLength = 300;
}
namespace Robomongo
{
/**
* Creates ConnectionSettings with default values
*/
ConnectionSettings::ConnectionSettings(bool isClone) : QObject(),
_connectionName(defaultNameConnection),
_host(defaultServerHost),
_port(port),
_imported(false),
_sshSettings(new SshSettings()),
_sslSettings(new SslSettings()),
_isReplicaSet(false),
_replicaSetSettings(new ReplicaSetSettings()),
_clone(isClone)
{ }
ConnectionSettings::ConnectionSettings(const mongo::MongoURI& uri, bool isClone)
: _connectionName(defaultNameConnection),
_host(defaultServerHost),
_port(port),
_imported(false),
_sshSettings(new SshSettings()),
_sslSettings(new SslSettings()),
_isReplicaSet((uri.type() == mongo::ConnectionString::ConnectionType::SET)),
_replicaSetSettings(new ReplicaSetSettings(uri)),
_clone(isClone)
{
// Disabling unfinished feature : Export / Import to / from MongoURI
/*
if (!uri.getServers().empty()) {
_host = uri.getServers().front().host();
_port = uri.getServers().front().port();
}
auto str = std::string(uri.getOptions().getStringField("ssl"));
auto sslEnabled = ("true" == str);
if (sslEnabled) {
_sslSettings->enableSSL(true);
_sslSettings->setAllowInvalidCertificates(true);
}
auto credential = new CredentialSettings();
credential->setUserName(uri.getUser());
credential->setUserPassword(uri.getPassword());
credential->setDatabaseName(uri.getDatabase());
if (!credential->userName().empty() && !credential->userPassword().empty()) { // todo:
credential->setEnabled(true);
}
addCredential(credential);
*/
}
void ConnectionSettings::fromVariant(const QVariantMap &map) {
setConnectionName(QtUtils::toStdString(map.value("connectionName").toString()));
setServerHost(QtUtils::toStdString(map.value("serverHost").toString().left(maxLength)));
setServerPort(map.value("serverPort").toInt());
setDefaultDatabase(QtUtils::toStdString(map.value("defaultDatabase").toString()));
setReplicaSet(map.value("isReplicaSet").toBool());
QVariantList list = map.value("credentials").toList();
for (QVariantList::const_iterator it = list.begin(); it != list.end(); ++it) {
QVariant var = *it;
CredentialSettings *credential = new CredentialSettings(var.toMap());
addCredential(credential);
}
if (map.contains("ssh")) {
_sshSettings->fromVariant(map.value("ssh").toMap());
}
if (map.contains("ssl")) {
_sslSettings->fromVariant(map.value("ssl").toMap());
}
if (isReplicaSet()) {
_replicaSetSettings->fromVariant(map.value("replicaSet").toMap());
}
// If UUID has never been created or is empty, create a new one. Otherwise load the existing.
if (!map.contains("uuid") || map.value("uuid").toString().isEmpty())
_uuid = QUuid::createUuid().toString();
else
_uuid = map.value("uuid").toString();
//#ifdef MONGO_SSL
// ,SSLInfo(map.value("sslEnabled").toBool(),QtUtils::toStdString(map.value("sslPemKeyFile").toString()))
//#endif
}
/**
* Cleanup used resources
*/
ConnectionSettings::~ConnectionSettings()
{
clearCredentials();
}
/**
* Creates completely new ConnectionSettings by cloning this record.
*/
ConnectionSettings *ConnectionSettings::clone() const
{
auto settings = new ConnectionSettings(true);
settings->setUuid(_uuid);
settings->apply(this);
return settings;
}
/**
* Discards current state and applies state from 'source' ConnectionSettings.
*/
void ConnectionSettings::apply(const ConnectionSettings *source)
{
setConnectionName(source->connectionName());
setServerHost(source->serverHost());
setServerPort(source->serverPort());
setDefaultDatabase(source->defaultDatabase());
setImported(source->imported());
setReplicaSet(source->isReplicaSet());
clearCredentials();
QList<CredentialSettings *> cred = source->credentials();
for (QList<CredentialSettings *>::iterator it = cred.begin(); it != cred.end(); ++it) {
addCredential((*it)->clone());
}
_sshSettings.reset(source->sshSettings()->clone());
_sslSettings.reset(source->sslSettings()->clone());
_replicaSetSettings.reset(source->_replicaSetSettings->clone());
//#ifdef MONGO_SSL
// setSslInfo(source->sslInfo());
//#endif
}
/**
* @brief Converts to QVariantMap
*/
QVariant ConnectionSettings::toVariant() const
{
QVariantMap map;
map.insert("connectionName", QtUtils::toQString(connectionName()));
map.insert("serverHost", QtUtils::toQString(serverHost()));
map.insert("serverPort", serverPort());
map.insert("defaultDatabase", QtUtils::toQString(defaultDatabase()));
map.insert("isReplicaSet", isReplicaSet());
if (isReplicaSet())
map.insert("replicaSet", _replicaSetSettings->toVariant());
#ifdef MONGO_SSL
SSLInfo infl = _info.sslInfo();
map.insert("sslEnabled", infl._sslSupport);
map.insert("sslPemKeyFile", QtUtils::toQString(infl._sslPEMKeyFile));
#endif
QVariantList list;
for (auto const& cred : _credentials)
list.append(cred->toVariant());
map.insert("credentials", list);
map.insert("ssh", _sshSettings->toVariant());
map.insert("ssl", _sslSettings->toVariant());
map.insert("uuid", _uuid);
return map;
}
CredentialSettings *ConnectionSettings::findCredential(const std::string &databaseName) const
{
CredentialSettings *result = nullptr;
for (QList<CredentialSettings *>::const_iterator it = _credentials.begin(); it != _credentials.end(); ++it) {
CredentialSettings *cred = *it;
if (cred->databaseName() == databaseName) {
result = cred;
break;
}
}
return result;
}
/**
* @brief Adds credential to this connection
*/
void ConnectionSettings::addCredential(CredentialSettings *credential)
{
if (!findCredential(credential->databaseName()))
_credentials.append(credential);
}
/**
* @brief Checks whether this connection has primary credential
* which is also enabled.
*/
bool ConnectionSettings::hasEnabledPrimaryCredential() const
{
if (_credentials.count() == 0)
return false;
return primaryCredential()->enabled();
}
/**
* @brief Returns primary credential
*/
CredentialSettings *ConnectionSettings::primaryCredential() const
{
if (_credentials.count() == 0) {
_credentials.append(new CredentialSettings());
}
return _credentials.at(0);
}
/**
* @brief Clears and releases memory occupied by credentials
*/
void ConnectionSettings::clearCredentials()
{
qDeleteAll(_credentials);
_credentials.clear();
}
std::string ConnectionSettings::getFullAddress() const
{
return hostAndPort().toString();
}
mongo::HostAndPort ConnectionSettings::hostAndPort() const
{
// If it doesn't look like IPv6 address,
// treat it like IPv4 or literal hostname
if (_host.find(':') == std::string::npos) {
return mongo::HostAndPort(_host, _port);
}
// The following code assumes, that it is IPv6 address
// If address contains square brackets ("["), remove them:
std::string hostCopy = _host;
if (_host.find('[') != std::string::npos) {
boost::erase_all(hostCopy, "[");
boost::erase_all(hostCopy, "]");
}
return mongo::HostAndPort(hostCopy, _port);
}
}
| 8,850
|
C++
|
.cpp
| 231
| 30.428571
| 118
| 0.630854
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,680
|
ScriptEngine.cpp
|
Studio3T_robomongo/src/robomongo/core/engine/ScriptEngine.cpp
|
#include "robomongo/core/engine/ScriptEngine.h"
#include <QVector> // unable to put this include below. doesn't compile on GCC 4.7.2 and Qt 4.8
#include <QDir>
#include <QStringList>
#include <QRegExp>
#include <QTextStream>
#include <QFile>
#include <QElapsedTimer>
// v0.9
//#include <third_party/js-1.7/jsapi.h>
//#include <third_party/js-1.7/jsparse.h>
//#include <third_party/js-1.7/jsscan.h>
//#include <third_party/js-1.7/jsstr.h>
#include <mongo/util/assert_util.h>
#include <mongo/util/exit_code.h>
#include <mongo/scripting/engine.h>
// v0.9
//#include <mongo/scripting/engine_spidermonkey.h>
#include <mongo/scripting/mozjs/engine.h>
#include <mongo/shell/shell_utils.h>
#include <mongo/base/string_data.h>
#include <mongo/client/dbclient_base.h>
#include <pcrecpp.h>
#include "robomongo/core/events/MongoEvents.h"
#include "robomongo/core/settings/ConnectionSettings.h"
#include "robomongo/core/settings/CredentialSettings.h"
#include "robomongo/core/domain/MongoDocument.h"
#include "robomongo/core/utils/Logger.h"
#include "robomongo/core/utils/QtUtils.h"
namespace
{
std::vector<std::string> split(const std::string &s, char seperator)
{
std::vector<std::string> output;
std::string::size_type prev_pos = 0, pos = 0;
while ((pos = s.find(seperator, pos)) != std::string::npos) {
std::string substring(s.substr(prev_pos, pos-prev_pos));
output.push_back(substring);
prev_pos = ++pos;
}
output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word
return output;
}
}
namespace mongo {
extern bool isShell;
void logProcessDetailsForLogRotate() {}
}
namespace Robomongo
{
ScriptEngine::ScriptEngine(ConnectionSettings *connection, int timeoutSec) :
_connection(connection),
_scope(nullptr),
_engine(NULL),
_timeoutSec(timeoutSec),
_initialized(false),
_mutex(QMutex::Recursive) { }
ScriptEngine::~ScriptEngine()
{
}
void ScriptEngine::init(bool isLoadMongoRcJs, const std::string& serverAddr, const std::string& dbName)
{
QMutexLocker lock(&_mutex);
std::string connectDatabase = dbName.empty() ? "test" : dbName;
if (_connection->hasEnabledPrimaryCredential())
connectDatabase = _connection->primaryCredential()->databaseName();
std::stringstream ss;
auto hostAndPort = serverAddr.empty() ? _connection->hostAndPort().toString() : serverAddr;
ss << "db = connect('" << hostAndPort << "/" << connectDatabase;
// v0.9
// ss << "db = connect('" << _connection->serverHost() << ":" << _connection->serverPort() << _connection->sslInfo() << _connection->sshInfo() << "/" << connectDatabase;
if (!_connection->hasEnabledPrimaryCredential())
ss << "')";
else
ss << "', '"
<< _connection->primaryCredential()->userName() << "', '"
<< _connection->primaryCredential()->userPassword() << "')";
{
mongo::shell_utils::dbConnect = ss.str();
// v0.9
// mongo::isShell = true;
mongo::ScriptEngine::setConnectCallback( mongo::shell_utils::onConnect );
mongo::ScriptEngine::setup();
mongo::getGlobalScriptEngine()->setScopeInitCallback(mongo::shell_utils::initScope);
mongo::getGlobalScriptEngine()->enableJIT(true);
_scope.reset(mongo::getGlobalScriptEngine()->newScope());
_engine = mongo::getGlobalScriptEngine();
// Load '.mongorc.js' from user's home directory
if (isLoadMongoRcJs) {
QString mongorcPath = QString("%1/.mongorc.js").arg(QDir::homePath());
if (QFile::exists(mongorcPath)) {
_scope->execFile(QtUtils::toStdString(mongorcPath), false, false);
}
}
// Load '.robomongorc.js'
QString robomongorcPath = QString("%1/.robomongorc.js").arg(QDir::homePath());
if (QFile::exists(robomongorcPath)) {
_scope->execFile(QtUtils::toStdString(robomongorcPath), false, false);
}
_failedScope = false;
}
// Esprima ECMAScript parser: http://esprima.org/
std::string esprima = loadFile(":/robomongo/scripts/esprima.js", true);
_scope->exec(esprima, "(esprima)", false, true, true);
// UUID helpers
std::string uuidhelpers = loadFile(":/robomongo/scripts/uuidhelpers.js", true);
_scope->exec(uuidhelpers, "(uuidhelpers)", false, true, true);
// Enable verbose shell reporting
_scope->exec("_verboseShell = true;", "(verboseShell)", false, false, false);
// Save original autocomplete function so it can be restored if overwritten by user preference
_scope->exec("DB.autocompleteOriginal = DB.autocomplete;", "(saveOriginalAutocomplete)", false, false, false);
// Cache result of original "DB.autocomplete"
// Cache invalidated by the invalidateDbCollectionsCache() method.
std::string const cacheAutocompletion =
"__robomongoAutocompletionCache = null;"
"DB.autocompleteCached = function(obj) { "
" if (__robomongoAutocompletionCache == null) {"
" __robomongoAutocompletionCache = DB.autocompleteOriginal(obj);"
" }"
" return __robomongoAutocompletionCache;"
"}";
_scope->exec(cacheAutocompletion, "", false, false, false);
// Capture aggregate parameters: pipeline, options
std::string const aggregateInterceptor =
"__robomongoAggregateUsed = false;"
"__robomongoAggregate = DBCollection.prototype.aggregate;"
"__robomongoAggregatePipeline = null;"
"__robomongoAggregateOptions = null;"
"DBCollection.prototype.aggregate = function(pipeline, options) { "
" __robomongoAggregateUsed = true;"
" __robomongoAggregatePipeline = pipeline;"
" __robomongoAggregateOptions = options;"
" return __robomongoAggregate.call(this, pipeline, options);"
"}";
_scope->exec(aggregateInterceptor, "", false, false, false);
_initialized = true;
}
MongoShellExecResult ScriptEngine::exec(const std::string &originalScript, const std::string &dbName,
AggrInfo aggrInfo /* = AggrInfo() */)
{
QMutexLocker lock(&_mutex);
if (!_scope) {
_failedScope = true;
return MongoShellExecResult(true, "Connection error. Uninitialized mongo scope.");
}
// robomongo shell timeout
bool timeoutReached = false;
/*
* Replace all commands ('show dbs', 'use db' etc.) with call
* to shellHelper('show', 'dbs') and so on.
*/
std::string stdstr(originalScript);
pcrecpp::RE re("^(show|use|set) (\\w+)$",
pcrecpp::RE_Options(PCRE_CASELESS|PCRE_MULTILINE|PCRE_NEWLINE_ANYCRLF));
re.GlobalReplace("shellHelper('\\1', '\\2');", &stdstr);
/*
* Statementize (i.e. extract all JavaScript statements from script) and
* execute each statement one by one
*/
std::vector<std::string> statements;
std::string error;
bool result = statementize(stdstr, statements, error);
if (!result && statements.size() == 0)
statements.push_back("print(__robomongoResult.error)");
std::vector<MongoShellResult> results;
use(dbName);
for (auto const& statement : statements) {
// clear global objects
__objects.clear();
__type = "";
__finished = false;
__logs.str("");
if (true /* ! wascmd */) {
try {
bool failed = false;
QElapsedTimer timer;
timer.start();
if ( _scope->exec( statement , "(shell)" , false , true , false, _timeoutSec * 1000) ) {
_scope->exec( "__robomongoLastRes = __lastres__; shellPrintHelper( __lastres__ );",
"(shell2)" , true , true , false, _timeoutSec * 1000);
}
else // failed to run script
failed = true;
qint64 elapsed = timer.elapsed(); // milliseconds
if (elapsed > _timeoutSec * 1000)
timeoutReached = true;
std::string logs = __logs.str();
std::string answer = logs.c_str();
std::string type = __type.c_str();
if (failed && !timeoutReached)
return MongoShellExecResult(true, answer);
std::vector<MongoDocumentPtr> docs = MongoDocument::fromBsonObj(__objects);
if (!answer.empty() || docs.size() > 0)
results.push_back(
prepareResult(type, answer, docs, elapsed, statement, aggrInfo)
);
}
catch (const std::exception &e) {
std::cout << "error:" << e.what() << std::endl;
}
}
}
return prepareExecResult(results, timeoutReached);
}
void ScriptEngine::interrupt()
{
// This operation crash Robomongo
// static_cast<mongo::mozjs::MozJSImplScope*>(_scope)->kill();
// v0.9
//mongo::Scope::_interruptFlag = true;
}
void ScriptEngine::use(const std::string &dbName)
{
QMutexLocker lock(&_mutex);
if (!dbName.empty()) {
std::stringstream ss;
// Switch to database
ss << "shellHelper.use('" << dbName << "');" << std::endl;
// Always allow to read from slave
ss << "rs.slaveOk();" << std::endl;
_scope->exec(ss.str(), "(usedb)", false, true, false);
}
}
void ScriptEngine::setBatchSize(int batchSize)
{
QMutexLocker lock(&_mutex);
char buff[64] = {0};
sprintf(buff, "DBQuery.shellBatchSize = %d", batchSize);
_scope->exec(buff, "(shellBatchSize)", false, true, true);
}
void ScriptEngine::ping()
{
if (!_scope)
return;
QMutexLocker lock(&_mutex);
_scope->exec("if (db) { db.runCommand({ping:1}); }", "(ping)", false, false, false, 3000);
}
QStringList ScriptEngine::complete(const std::string &prefix, const AutocompletionMode mode)
{
//if ( prefix.find( '"' ) != string::npos )
// return;
try {
if (mode == AutocompleteAll)
_scope->exec("DB.autocomplete = DB.autocompleteCached;", "", false, false, false);
else if (mode == AutocompleteNoCollectionNames)
_scope->exec("DB.autocomplete = function(obj){return [];}", "", false, false, false);
QStringList results;
mongo::BSONObj args = BSON( "0" << prefix );
_scope->invokeSafe( "function callShellAutocomplete(x) {shellAutocomplete(x)}", &args, 0, 1000 );
mongo::BSONObjBuilder b;
_scope->append( b , "" , "__autocomplete__" );
mongo::BSONObj res = b.obj();
mongo::BSONObj arr = res.firstElement().Obj();
mongo::BSONObjIterator i( arr );
while ( i.more() ) {
mongo::BSONElement e = i.next();
results.append(QtUtils::toQString(e.String()));
}
return results;
}
catch ( ... ) {
return QStringList();
}
return QStringList();
}
MongoShellResult ScriptEngine::prepareResult(const std::string &type, const std::string &output,
const std::vector<MongoDocumentPtr> &objects, qint64 elapsedms,
const std::string &statement, AggrInfo aggrInfo /*= AggrInfo()*/)
{
const char *script =
"__robomongoQuery = false; \n"
"__robomongoIsAggregate = false; \n"
"__robomongoDbName = '[invalid database]'; \n"
"__robomongoServerAddress = '[invalid connection]'; \n"
"__robomongoCollectionName = '[invalid collection]'; \n"
"if (typeof __robomongoLastRes == 'object' && __robomongoLastRes != null \n"
" && __robomongoLastRes instanceof DBQuery) { \n"
" __robomongoQuery = true; \n"
" __robomongoDbName = __robomongoLastRes._db.getName();\n "
" __robomongoServerAddress = __robomongoLastRes._mongo.host; \n"
" __robomongoCollectionName = __robomongoLastRes._collection._shortName; \n"
" __robomongoQuery = __robomongoLastRes._query; \n"
" __robomongoFields = __robomongoLastRes._fields; \n"
" __robomongoLimit = __robomongoLastRes._limit; \n"
" __robomongoSkip = __robomongoLastRes._skip; \n"
" __robomongoBatchSize = __robomongoLastRes._batchSize; \n"
" __robomongoOptions = __robomongoLastRes._options; \n"
" __robomongoSpecial = __robomongoLastRes._special; \n"
"} \n"
"else if (typeof __robomongoLastRes == 'object' && __robomongoLastRes != null \n"
" && __robomongoLastRes instanceof DBCommandCursor \n"
" && __robomongoAggregateUsed) { \n"
" __robomongoAggregateUsed = false; \n"
" __robomongoIsAggregate = true; \n"
" __robomongoDbName = __robomongoLastRes._db.getName();\n "
" __robomongoServerAddress = __robomongoLastRes._db._mongo.host; \n"
" __robomongoCollectionName = __robomongoLastRes._collName; \n"
"} \n"
;
_scope->exec(script, "(getresultinfo)", false, false, false);
bool const isQuery = _scope->getBoolean("__robomongoQuery");
bool const isAggregate = _scope->getBoolean("__robomongoIsAggregate");
if (isQuery) {
std::string serverAddress = getString("__robomongoServerAddress");
std::string dbName = getString("__robomongoDbName");
std::string collectionName = getString("__robomongoCollectionName");
mongo::BSONObj query = _scope->getObject("__robomongoQuery");
mongo::BSONObj fields = _scope->getObject("__robomongoFields");
int limit = _scope->getNumberInt("__robomongoLimit");
int skip = _scope->getNumberInt("__robomongoSkip");
int batchSize = _scope->getNumberInt("__robomongoBatchSize");
int options = _scope->getNumberInt("__robomongoOptions");
bool special = _scope->getBoolean("__robomongoSpecial");
MongoQueryInfo const info{ CollectionInfo(serverAddress, dbName, collectionName),
query, fields, limit, skip, batchSize, options, special };
return MongoShellResult(type, output, objects, info, statement, elapsedms);
}
else if (isAggregate) {
std::string const serverAddress = getString("__robomongoServerAddress");
std::string const dbName = getString("__robomongoDbName");
std::string const collectionName = getString("__robomongoCollectionName");
mongo::BSONObj const pipeline = _scope->getObject("__robomongoAggregatePipeline");
mongo::BSONObj const options = _scope->getObject("__robomongoAggregateOptions");
// This query can be paging of an original aggr. query, we store the original/unpaged
// pipeline object here.
mongo::BSONObj const origPipeline = aggrInfo.isValid ? aggrInfo.pipeline : pipeline;
int const skip = aggrInfo.isValid ? aggrInfo.skip : 0;
int const batchSize = aggrInfo.isValid ? aggrInfo.batchSize : 50;
int const resultIndex = aggrInfo.isValid ? aggrInfo.resultIndex : -1;
AggrInfo const newAggrInfo { collectionName, skip, batchSize, origPipeline, options, resultIndex };
return MongoShellResult(type, output, objects, MongoQueryInfo(), statement, elapsedms, newAggrInfo);
}
return MongoShellResult(type, output, objects, MongoQueryInfo(), statement, elapsedms);
}
MongoShellExecResult ScriptEngine::prepareExecResult(const std::vector<MongoShellResult> &results,
bool timeoutReached /* = false */)
{
const char *script =
"__robomongoServerAddress = '[invalid connection]'; \n"
"__robomongoServerIsValid = false; \n"
"__robomongoDbName = '[invalid database]'; \n"
"__robomongoDbIsValid = false; \n"
"if (typeof db == 'object' && db != null && db instanceof DB) { \n"
" __robomongoServerAddress = db.getMongo().host; \n"
" __robomongoServerIsValid = true; \n"
" __robomongoDbName = db.getName();\n "
" __robomongoDbIsValid = true; \n "
"} \n";
_scope->exec(script, "(getdbname)", false, false, false);
std::string serverName = getString("__robomongoServerAddress");
bool serverIsValid = _scope->getBoolean("__robomongoServerIsValid");
std::string dbName = getString("__robomongoDbName");
bool dbIsValid = _scope->getBoolean("__robomongoDbIsValid");
return MongoShellExecResult(results, serverName, serverIsValid, dbName, dbIsValid, timeoutReached);
}
std::string ScriptEngine::getString(const char *fieldName)
{
return _scope->getString(fieldName);
}
bool ScriptEngine::statementize(
const std::string &script, std::vector<std::string> &outVec, std::string &outError)
{
_scope->setString("__robomongoEsprima", script.c_str());
mongo::StringData const data {
"var __robomongoResult = {};"
"try {"
"__robomongoResult.result = esprima.parse(__robomongoEsprima, { range: true, loc : true });"
"} catch(e) {"
"__robomongoResult.error = e.name + ': ' + e.message;"
"}"
"__robomongoResult;"
};
if(!_scope->exec(data, "(esprima2)", false, true, false)) {
sendLog(this, LogEvent::RBM_ERROR, "ScriptEngine: Scope failed. Resetting scope.");
_scope->reset();
sendLog(this, LogEvent::RBM_INFO, "ScriptEngine: Scope reset complete.");
_scope->exec(data, "(esprima2)", false, true, false);
}
mongo::BSONObj const obj = _scope->getObject("__lastres__");
if (obj.hasField("error")) {
outError = obj.getField("error");
return false;
}
for (auto const& bsonElem : obj.getField("result").Obj().getField("body").Array())
{
mongo::BSONObj const item = bsonElem.Obj();
std::vector<mongo::BSONElement> const range = item.getField("range").Array();
auto const from = static_cast<int>(range.at(0).number());
auto const till = static_cast<int>(range.at(1).number());
QString const qScript = QtUtils::toQString(script);
std::string statement = qScript.mid(from, till - from).toStdString();
outVec.push_back(statement);
}
return true;
}
void ScriptEngine::invalidateDbCollectionsCache() {
if (!_initialized)
return;
_scope->exec("__robomongoAutocompletionCache = null;", "", false, false, false);
}
std::string ScriptEngine::loadFile(const QString &path, bool throwOnError) {
QFile file(path);
if (!file.open(QIODevice::ReadOnly)) {
if (throwOnError)
throw std::runtime_error("Unable to load file");
return "";
}
QTextStream in(&file);
QString content = in.readAll();
return QtUtils::toStdString(content);
}
}
| 20,410
|
C++
|
.cpp
| 412
| 38.179612
| 176
| 0.579445
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,681
|
RoboCrypt.cpp
|
Studio3T_robomongo/src/robomongo/utils/RoboCrypt.cpp
|
#include "RoboCrypt.h"
#include "robomongo/core/utils/Logger.h"
#include <cmath>
#include <iostream>
#include <random>
#include <QDir>
#include <QFileInfo>
#include <QIODevice>
#include <QString>
#include <QTextStream>
namespace Robomongo {
long long RoboCrypt::_KEY = 0;
std::vector<RoboCrypt::LogAndSeverity> RoboCrypt::_roboCryptLogs;
void RoboCrypt::initKey()
{
using MongoSeverity = mongo::logger::LogSeverity;
auto addToRoboCryptLogs = [](std::string msg, MongoSeverity severity) {
_roboCryptLogs.push_back({ msg, severity });
};
const auto KEY_FILE = QString("%1/.3T/robo-3t/robo3t.key").arg(QDir::homePath()).toStdString();
QString fileContent;
QFileInfo const fileInfo{ QString::fromStdString(KEY_FILE) };
if (fileInfo.exists() && fileInfo.isFile()) { // a) Read existing key from file
QFile keyFile{ QString::fromStdString(KEY_FILE) };
if (!keyFile.open(QIODevice::ReadOnly))
addToRoboCryptLogs("RoboCrypt: Failed to open key file: " + KEY_FILE, MongoSeverity::Error());
QTextStream in{ &keyFile };
fileContent = in.readAll();
if(fileContent.isEmpty())
addToRoboCryptLogs("RoboCrypt: Key file is empty: " + KEY_FILE, MongoSeverity::Error());
_KEY = fileContent.toLongLong();
}
else { // b) Generate a new key and save it into file
addToRoboCryptLogs("RoboCrypt: No key found, generating a new key and saving it into file",
MongoSeverity::Warning());
// Generate a new key
std::random_device randomDevice;
std::mt19937_64 engine{ randomDevice() };
std::uniform_int_distribution<long long int> dist{ std::llround(std::pow(2,61)),
std::llround(std::pow(2,62)) };
_KEY = dist(engine);
// Save the key into file
QFile file{ QString::fromStdString(KEY_FILE) };
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
addToRoboCryptLogs("RoboCrypt: Failed to save the key into file: " + KEY_FILE, MongoSeverity::Error());
QTextStream out(&file);
out << QString::number(_KEY);
}
}
}
| 2,395
|
C++
|
.cpp
| 50
| 36.76
| 119
| 0.600347
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,682
|
common.cpp
|
Studio3T_robomongo/src/robomongo/utils/common.cpp
|
#include "robomongo/utils/common.h"
#include <QFileInfo>
#include <QSettings>
#include "robomongo/core/events/MongoEvents.h"
#include "robomongo/core/utils/Logger.h"
#include "robomongo/core/EventBus.h"
#include "robomongo/utils/StringOperations.h"
namespace Robomongo
{
void genericEventErrorHandler(Event *event, const std::string &userFriendlyMessage, EventBus* bus,
QObject* sender)
{
if (!event->isError())
return;
std::string errMsg = captilizeFirstChar(event->error().errorMessage());
LOG_MSG(userFriendlyMessage + " " + errMsg, mongo::logger::LogSeverity::Error());
if (bus && sender)
bus->publish(new OperationFailedEvent(sender, errMsg, userFriendlyMessage));
else
LOG_MSG("Failed to publish OperationFailedEvent.", mongo::logger::LogSeverity::Error());
}
bool fileExists(const QString &filePath)
{
QFileInfo fileInfo(filePath);
return fileInfo.exists() && fileInfo.isFile();
}
template<typename T>
bool vectorContains(std::vector<T> const& vec, T const& value) {
return find(vec.cbegin(), vec.cend(), value) != vec.cend();
}
QVariant getSetting(QString const& key) {
return QSettings("3T", "Robomongo").value(key).toSize();
}
void saveSetting(QString const& key, QVariant const& value) {
QSettings("3T", "Robomongo").setValue(key, value);
}
} // end of name space Robomongo
| 1,500
|
C++
|
.cpp
| 37
| 33.783784
| 103
| 0.664143
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,683
|
RoboCrypt_test.cpp
|
Studio3T_robomongo/src/robomongo/utils/RoboCrypt_test.cpp
|
#include "gtest/gtest.h"
#include "robomongo/utils/RoboCrypt.h"
#include <string>
/* Example Test:
*
* TEST( [Test_Case_Name], [Test_Name] )
* TEST( [Test_Case_Name], [UnitOfWorkName_ScenarioUnderTest_ExpectedBehavior] )
* TEST( StringParserTests, NumberLeftOf_StringWithoutNumber_ReturnsFalse) {
// ...
}
*/
TEST(RoboCrypt_CoreTests, encrypt_decrypt)
{
auto const pwds = {
"Tyu_aBq",
"_?asdfghjkl;'piop[.,/",
".?/`_@~!#$%^^&&*)_)_+=-",
"<>?/.,;':][p{}|\""
};
for (auto const& pwd : pwds) {
const std::string encryptedPwd = Robomongo::RoboCrypt::encrypt(pwd);
const std::string decryptedPwd = Robomongo::RoboCrypt::decrypt(encryptedPwd);
EXPECT_EQ(pwd, decryptedPwd);
}
}
| 767
|
C++
|
.cpp
| 25
| 25.88
| 85
| 0.610811
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,685
|
StringOperations.cpp
|
Studio3T_robomongo/src/robomongo/utils/StringOperations.cpp
|
#include "robomongo/utils/StringOperations.h"
namespace Robomongo
{
std::string captilizeFirstChar(std::string str)
{
if (!str.empty())
str[0] = static_cast<char>(toupper(str[0]));
return str;
}
} // end of name space Robomongo
| 272
|
C++
|
.cpp
| 10
| 22
| 56
| 0.638462
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,686
|
StringOperations_test.cpp
|
Studio3T_robomongo/src/robomongo/utils/StringOperations_test.cpp
|
#include "gtest/gtest.h"
#include "robomongo/utils/StringOperations.h"
#include <string>
/* Example Test:
*
* TEST( [Test_Case_Name], [Test_Name] )
* TEST( [Test_Case_Name], [UnitOfWorkName_ScenarioUnderTest_ExpectedBehavior] )
* TEST( StringParserTests, NumberLeftOf_StringWithoutNumber_ReturnsFalse) {
// ...
}
*/
TEST(StringOperationsTests, captilizeFirstChar)
{
// EXPECT_EQ("Abcc", Robomongo::captilizeFirstChar("abc")); // Simulating failing test
EXPECT_EQ("Abc", Robomongo::captilizeFirstChar("abc")); // Simulating passing test
}
| 559
|
C++
|
.cpp
| 16
| 32.625
| 90
| 0.737523
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,688
|
ptimeutil.cpp
|
Studio3T_robomongo/src/robomongo/shell/db/ptimeutil.cpp
|
/*
wdb - weather and water data storage
Copyright (C) 2007 met.no
Contact information:
Norwegian Meteorological Institute
Box 43 Blindern
0313 OSLO
NORWAY
E-mail: wdb@met.no
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA
*/
#include "ptimeutil.h"
#include <ctype.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
//#include <trimstr.h>
#include <sstream>
namespace
{
int getInt( const std::string &timebuf, std::string::size_type &index, int numberOfChar, bool &isSuccessfull )
{
int nextN=0;
char buf[10]={0};
isSuccessfull = numberOfChar < 9;
assert(isSuccessfull);
while ( nextN < numberOfChar && isSuccessfull) {
isSuccessfull = index < timebuf.length() && isdigit( timebuf[index] );
assert(isSuccessfull);
buf[nextN]=timebuf[index];
nextN++;
index++;
}
return atoi( buf );
}
}
namespace miutil
{
const long long minDate = -9218988800000; // "1677-11-10T17:46:40.001Z"
const long long maxDate = 9218988800000; // "2262-02-20T06:13:19.999Z"
std::string rfc1123date( const boost::posix_time::ptime &pt )
{
const char *day = NULL;
const char *mon = NULL;
if( pt.is_special() )
return std::string();
boost::gregorian::date d( pt.date() );
boost::posix_time::time_duration t( pt.time_of_day() );
switch( d.day_of_week() ) {
using namespace boost::date_time;
case Sunday: day="Sun"; break;
case Monday: day="Mon"; break;
case Tuesday: day="Tue"; break;
case Wednesday: day="Wed"; break;
case Thursday: day="Thu"; break;
case Friday: day="Fri"; break;
case Saturday: day="Sat"; break;
}
switch( d.month() ){
using namespace boost::date_time;
case Jan: mon="Jan"; break;
case Feb: mon="Feb"; break;
case Mar: mon="Mar"; break;
case Apr: mon="Apr"; break;
case May: mon="May"; break;
case Jun: mon="Jun"; break;
case Jul: mon="Jul"; break;
case Aug: mon="Aug"; break;
case Sep: mon="Sep"; break;
case Oct: mon="Oct"; break;
case Nov: mon="Nov"; break;
case Dec: mon="Dec"; break;
}
if( !day || !mon )
return std::string();
unsigned short year = d.year();
char buf[64] = {0};
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat"
#elif defined(__GNUG__) // gcc
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat"
#endif
sprintf( buf, "%s, %02d %s %04d %02d:%02d:%02d GMT", day, d.day().as_number(), mon, year, t.hours(), t.minutes(), t.seconds() );
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUG__) // gcc
#pragma GCC diagnostic pop
#endif
return buf;
}
boost::posix_time::ptime rfc1123date( const std::string &rfc1123 )
{
return rfc1123date( rfc1123.c_str() );
}
boost::posix_time::ptime rfc1123date( const char *rfc1123 )
{
char gmt[4];
char sday[4];
char smon[4];
int day, mon, year, h, m, s;
int weekDay;
if( !rfc1123 )
return boost::posix_time::ptime( boost::date_time::not_a_date_time );
if ( sscanf( rfc1123, "%3s, %02d %3s %04d %02d:%02d:%02d %3s", sday, &day, smon, &year,
&h, &m, &s, gmt) !=8 )
return boost::posix_time::ptime( boost::date_time::not_a_date_time );
if( strcmp(gmt, "GMT")!=0 )
return boost::posix_time::ptime( boost::date_time::not_a_date_time );
if ( strcmp(smon, "Jan")==0 )
mon=1;
else if ( strcmp(smon, "Feb")==0 )
mon=2;
else if ( strcmp(smon, "Mar")==0 )
mon=3;
else if ( strcmp(smon, "Apr")==0 )
mon=4;
else if ( strcmp(smon, "May")==0 )
mon=5;
else if ( strcmp(smon, "Jun")==0 )
mon=6;
else if ( strcmp(smon, "Jul")==0 )
mon=7;
else if ( strcmp(smon, "Aug")==0 )
mon=8;
else if ( strcmp(smon, "Sep")==0 )
mon=9;
else if ( strcmp(smon, "Oct")==0 )
mon=10;
else if ( strcmp(smon, "Nov")==0 )
mon=11;
else if ( strcmp(smon, "Dec")==0 )
mon=12;
else
return boost::posix_time::ptime( boost::date_time::not_a_date_time );
//The day chack is a consistent check that could be dropped.
if ( strcmp(sday, "Sun")==0 )
weekDay=0;
else if ( strcmp(sday, "Mon")==0 )
weekDay=1;
else if ( strcmp(sday, "Tue")==0 )
weekDay=2;
else if ( strcmp(sday, "Wed")==0 )
weekDay=3;
else if ( strcmp(sday, "Thu")==0 )
weekDay=4;
else if ( strcmp(sday, "Fri")==0 )
weekDay=5;
else if ( strcmp(sday, "Sat")==0 )
weekDay=6;
else
return boost::posix_time::ptime( boost::date_time::not_a_date_time );
if( day<0 || day>31 || h<0 || h>23 || m<0 || m>59 || s<0 || s>60 )
return boost::posix_time::ptime( boost::date_time::not_a_date_time );
boost::posix_time::ptime date( boost::gregorian::date(year, mon, day) ,
boost::posix_time::time_duration( h, m, s ) );
//This is a consistent check. We could skip this test.
if( weekDay != date.date().day_of_week() )
return boost::posix_time::ptime( boost::date_time::not_a_date_time );
return date;
}
std::string isotimeString(const boost::posix_time::ptime &pt, bool useTseparator, bool isLocalFormat)
{
if( pt.is_special() )
return "";
char buf[64]={0};
char sep=' ';
if( useTseparator )
sep = 'T';
boost::gregorian::date d( pt.date() );
boost::posix_time::time_duration t( pt.time_of_day() );
if( !isLocalFormat ){
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat"
#elif defined(__GNUG__) // gcc
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat"
#endif
sprintf( buf, "%04d-%02d-%02d%c%02d:%02d:%02d.%03dZ",
static_cast<int>(d.year()), d.month().as_number(), d.day().as_number(), sep,
t.hours(), t.minutes(), t.seconds(), (static_cast<int>(t.total_milliseconds()))%1000 );
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUG__) // gcc
#pragma GCC diagnostic pop
#endif
}
else{
boost::posix_time::ptime timeP(d, t);
time_t rawtime;
time ( &rawtime );
struct tm *ptm = std::gmtime ( &rawtime );
int utcD = ptm->tm_mday;
int utcH = ptm->tm_hour;
int utcM = ptm->tm_min;
struct tm *timeinfo = std::localtime (&rawtime);
int diffH = timeinfo->tm_hour - utcH;
// Time zone calculation
if (timeinfo->tm_mday < utcD && diffH > 0)
diffH -= 24;
else if (timeinfo->tm_mday > utcD && diffH < 0)
diffH += 24;
int diffM = timeinfo->tm_min - utcM;
boost::posix_time::time_duration diffT = boost::posix_time::time_duration(diffH, diffM, 0);
timeP += diffT;
d = timeP.date();
t = timeP.time_of_day();
char utc_buff[8]={0};
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat"
#elif defined(__GNUG__) // gcc
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat"
#endif
sprintf(utc_buff, (diffT.hours() >= 0) ? "+%02d:%02d" : "%03d:%02d", diffT.hours(), abs(diffM));
sprintf(buf, "%04d-%02d-%02d%c%02d:%02d:%02d.%03d",
static_cast<int>(d.year()), d.month().as_number(), d.day().as_number(), sep,
t.hours(), t.minutes(), t.seconds(), (static_cast<int>(t.total_milliseconds()))%1000);
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUG__) // gcc
#pragma GCC diagnostic pop
#endif
strcat(buf, utc_buff);
}
return buf;
}
boost::posix_time::ptime ptimeFromIsoString( const std::string &isoTime)
{
bool isSuccessfull=false;
return ptimeFromIsoString(isoTime, isSuccessfull);
}
boost::posix_time::ptime ptimeFromIsoString( const std::string &isoTime, bool &isSuccessfull)
{
struct DEF {
int number;
unsigned char numberOfChars;
const char *nextSep;
};
DEF def[] = {
{0, 4, "-"}, //year
{0, 2, "-"}, //Month
{0, 2, "T "},//day
{0, 2, ":"}, //hour
{0, 2, ":"}, //minute
{0, 2, ".Z"}, //second
{0, 3, "+-Z"}, //msecond
{0, 0, 0} //terminator
};
isSuccessfull = true;
if( isoTime == "infinity" )
return boost::posix_time::ptime( boost::posix_time::pos_infin );
else if( isoTime == "-infinity" )
return boost::posix_time::ptime( boost::posix_time::neg_infin );
else if( isoTime == "epoch" )
return boost::posix_time::ptime( boost::gregorian::date( 1970, 1, 1 ),
boost::posix_time::time_duration( 0, 0, 0) );
else if( isoTime == "now" )
return boost::posix_time::second_clock::universal_time();
else if( isoTime == "today" ) {
boost::posix_time::ptime now( boost::posix_time::second_clock::universal_time() );
return boost::posix_time::ptime( now.date(), boost::posix_time::time_duration( 0, 0, 0) );
} else if( isoTime == "tomorrow" ) {
boost::posix_time::ptime now( boost::posix_time::second_clock::universal_time() );
now += boost::posix_time::hours(24);
return boost::posix_time::ptime( now.date(), boost::posix_time::time_duration( 0, 0, 0) );
} else if( isoTime == "yesterday" ) {
boost::posix_time::ptime now( boost::posix_time::second_clock::universal_time() );
now -= boost::posix_time::hours(24);
return boost::posix_time::ptime( now.date(), boost::posix_time::time_duration( 0, 0, 0) );
}
std::string::size_type iIsoTime = isoTime.find_first_not_of( " ", 0 ); //Skip whitespace in front
isSuccessfull = iIsoTime != std::string::npos;
assert( isSuccessfull );
if( ! isdigit( (int)isoTime[iIsoTime] ) ) {
//We try to decode it as an rfc1123date.
boost::posix_time::ptime pt = rfc1123date( isoTime.c_str() );
isSuccessfull = !pt.is_special();
assert( isSuccessfull );
return pt;
}
//Decode the YYYY-MM-DDThh:mm:ss part
//Remeber -, T and : is optional.
for( unsigned short defIndex=0; def[defIndex].nextSep && iIsoTime < isoTime.length() && isSuccessfull; ++defIndex ) {
def[defIndex].number = getInt( isoTime, iIsoTime, def[defIndex].numberOfChars, isSuccessfull);
iIsoTime = isoTime.find_first_of( def[defIndex].nextSep, iIsoTime );
if(defIndex!=6)
++iIsoTime;
}
if(!isSuccessfull){
return boost::posix_time::ptime();
}
int hourOffset=0;
int minuteOffset=0;
//Decode the UTC offset part of
//YYYY-MM-DDThh:mm:ssSHHMM part
//The UTC offset part is SHHMM
//Where S is the sign. + or -.
// HH the hour offset, mandatory if we have an UTC offset part.
// MM the minute offset, otional.
if( iIsoTime < isoTime.length() ) {
//We have a possible UTC offset.
//The format is SHHMM, where S is the sign.
char ch = isoTime[iIsoTime];
if( ch == '+' || ch == '-' || isdigit( ch ) ) {
int sign=1;
if( ! isdigit( ch ) ) {
if( ch=='-' )
sign=-1;
isSuccessfull = isdigit( isoTime[++iIsoTime] )!=0;
assert( isSuccessfull );
}
hourOffset = getInt( isoTime, iIsoTime, 2, isSuccessfull);
hourOffset*=sign;
if( iIsoTime < isoTime.length() && isdigit( isoTime[++iIsoTime] ) ) {
minuteOffset = getInt( isoTime, iIsoTime, 2, isSuccessfull);
}
}
}
try{
boost::gregorian::date date(def[0].number, def[1].number, def[2].number);
boost::posix_time::time_duration td(def[3].number, def[4].number, def[5].number, def[6].number*1000);
boost::posix_time::ptime pt(date, td);
td = boost::posix_time::time_duration(hourOffset, minuteOffset, 0);
return pt - td;
}
catch(const std::out_of_range &)
{
isSuccessfull = false;
return boost::posix_time::ptime();
}
}
}
| 14,219
|
C++
|
.cpp
| 347
| 30.936599
| 136
| 0.543866
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,690
|
main_mongo.cpp
|
Studio3T_robomongo/src/robomongo/app/main_mongo.cpp
|
#include <QApplication>
#include <QDesktopWidget>
#include <QDebug>
#include <locale.h>
#include <mongo/bson/bsonobjbuilder.h>
#include <robomongo/core/utils/BsonUtils.h>
using namespace Robomongo;
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
mongo::BSONObjBuilder m;
m.append("test", 56);
const mongo::BSONObj &obj = m.obj();
std::string str = BsonUtils::jsonString(obj, mongo::TenGen, 1, DefaultEncoding, Utc);
qDebug() << "Hello!";
qDebug() << QString::fromStdString(str);
return app.exec();
}
| 561
|
C++
|
.cpp
| 18
| 27.722222
| 89
| 0.706215
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,691
|
main.cpp
|
Studio3T_robomongo/src/robomongo/app/main.cpp
|
#include <QApplication>
#include <QDesktopWidget>
#include <locale.h>
// Header "mongo/util/net/sock" is needed for mongo::enableIPv6()
// Header "mongo/platform/basic" is required by "sock.h" under Windows
#include <mongo/platform/basic.h>
#include <mongo/util/net/socket_utils.h>
#include <mongo/base/initializer.h>
#include <mongo/util/net/ssl_options.h>
#include <mongo/db/service_context.h>
#include <mongo/transport/transport_layer_asio.h>
#include <mongo/shell/shell_options.h>
#include <mongo/db/storage/storage_engine_init.h>
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/settings/SettingsManager.h"
#include "robomongo/core/utils/Logger.h"
#include "robomongo/gui/MainWindow.h"
#include "robomongo/gui/AppStyle.h"
#include "robomongo/gui/dialogs/EulaDialog.h"
#include "robomongo/ssh/ssh.h"
#include "robomongo/utils/RoboCrypt.h"
int main(int argc, char *argv[], char** envp)
{
if (rbm_ssh_init())
return 1;
// Please check, do we really need envp for other OSes?
#ifdef Q_OS_WIN
envp = NULL;
#endif
// Support for IPv6 is disabled by default. Enable it.
mongo::enableIPv6(true);
// Perform SSL-enabled mongo initialization
mongo::sslGlobalParams.sslMode.store(mongo::SSLParams::SSLMode_allowSSL);
// Cross Platform High DPI support - Qt 5.7
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
// Initialization routine for MongoDB shell
mongo::runGlobalInitializersOrDie(argc, argv, envp);
mongo::setGlobalServiceContext(mongo::ServiceContext::make());
// Todo from mongo repo: This should use a TransportLayerManager or TransportLayerFactory
auto serviceContext = mongo::getGlobalServiceContext();
mongo::transport::TransportLayerASIO::Options opts;
// When true, it breaks connection to localhost, github #1757
opts.enableIPv6 = mongo::shellGlobalParams.enableIPv6;
opts.mode = mongo::transport::TransportLayerASIO::Options::kEgress;
serviceContext->setTransportLayer(
std::make_unique<mongo::transport::TransportLayerASIO>(opts, nullptr)
);
auto tlPtr = serviceContext->getTransportLayer();
uassertStatusOK(tlPtr->setup());
uassertStatusOK(tlPtr->start());
// Initialize Qt application
QApplication app(argc, argv);
// On Unix/Linux Qt is configured to use the system locale settings by default.
// This can cause a conflict when using POSIX functions, for instance, when
// converting between data types such as floats and strings, since the notation
// may differ between locales. To get around this problem, call the POSIX
// function setlocale(LC_NUMERIC, "C") right after initializing QApplication or
// QCoreApplication to reset the locale that is used for number formatting to "C"-locale.
// (http://doc.qt.io/qt-5/qcoreapplication.html#locale-settings)
setlocale(LC_NUMERIC, "C");
#ifdef Q_OS_MAC
app.setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif
// EULA License Agreement
auto const& settings { Robomongo::AppRegistry::instance().settingsManager() };
if (!settings->acceptedEulaVersions().contains(PROJECT_VERSION)) {
bool const showFormPage { settings->programExitedNormally() && !settings->disableHttpsFeatures() };
Robomongo::EulaDialog eulaDialog(showFormPage);
settings->setProgramExitedNormally(false);
settings->save();
int const result = eulaDialog.exec();
settings->setProgramExitedNormally(true);
settings->save();
if (QDialog::Rejected == result) {
rbm_ssh_cleanup();
return 1;
}
// EULA accepted
settings->addAcceptedEulaVersion(PROJECT_VERSION);
settings->save();
}
// Init GUI style
Robomongo::AppStyleUtils::initStyle();
// To be set true at normal program exit
settings->setProgramExitedNormally(false);
settings->save();
// Application main window
Robomongo::MainWindow mainWindow;
mainWindow.show();
for(auto const& msgAndSeverity : Robomongo::RoboCrypt::roboCryptLogs())
Robomongo::LOG_MSG(msgAndSeverity.first, msgAndSeverity.second);
int rc = app.exec();
rbm_ssh_cleanup();
return rc;
}
| 4,244
|
C++
|
.cpp
| 95
| 39.589474
| 107
| 0.724673
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,692
|
main_test.cpp
|
Studio3T_robomongo/src/robomongo/app/main_test.cpp
|
#undef NDEBUG
#include <sstream>
#include <iostream>
#include <assert.h>
#include <limits>
#include <mongo/util/exit_code.h>
#include <mongo/util/net/hostandport.h>
namespace mongo {
extern bool isShell;
void logProcessDetailsForLogRotate() {}
void exitCleanly(ExitCode code) {}
}
void testHostAndPort() {
mongo::HostAndPort hp = mongo::HostAndPort("127.0.0.1", 20017);
assert(hp.toString() == "127.0.0.1:20017");
hp = mongo::HostAndPort("2a03:b0c0:3:d0::f3:1001", 20017);
assert(hp.toString() == "[2a03:b0c0:3:d0::f3:1001]:20017");
// toString() will wrap IPv6 address in brackets even if they
// are already exist. This is true at least for MongoDB 3.2
hp = mongo::HostAndPort("[2a03:b0c0:3:d0::f3:1001]", 20017);
assert(hp.toString() == "[[2a03:b0c0:3:d0::f3:1001]]:20017");
hp = mongo::HostAndPort("[2a03:b0c0:3:d0::f3:1001", 20017);
assert(hp.toString() == "[[2a03:b0c0:3:d0::f3:1001]:20017");
}
void precisionAssert(const std::string &text, double d) {
std::stringstream s;
s.precision(std::numeric_limits<double>::digits10);
s << d;
if (d == (long long)d)
s << ".0";
std::cout << "Checking " << text << " - ";
assert(text == s.str());
std::cout << "Correct. " << std::endl;
}
void testPrecision() {
precisionAssert("-9.987654321", -9.987654321);
precisionAssert("-1.0", -1.0);
precisionAssert("-0.0", -0.0);
precisionAssert("0.0", 0.0);
precisionAssert("9.0", 9.0);
precisionAssert("9.8", 9.8);
precisionAssert("9.9", 9.9);
precisionAssert("9.98", 9.98);
precisionAssert("9.987", 9.987);
precisionAssert("9.9876", 9.9876);
precisionAssert("9.98765", 9.98765);
precisionAssert("9.987654", 9.987654);
precisionAssert("9.9876543", 9.9876543);
precisionAssert("9.98765432", 9.98765432);
precisionAssert("9.987654321", 9.987654321);
precisionAssert("9.987654321", 9.9876543210);
precisionAssert("9.98765432109", 9.98765432109);
precisionAssert("9.987654321098", 9.987654321098);
precisionAssert("9.9876543210987", 9.9876543210987);
precisionAssert("9.98765432109876", 9.98765432109876);
precisionAssert("9.98765432109876", 9.987654321098765);
precisionAssert("9.98765432109877", 9.9876543210987654);
precisionAssert("3.1415", 3.1415);
precisionAssert("1.1", 1.1);
precisionAssert("9.7", 9.7);
}
int main(int argc, char *argv[], char** envp)
{
testHostAndPort();
testPrecision();
return 0;
}
| 2,502
|
C++
|
.cpp
| 67
| 33.223881
| 67
| 0.665705
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,693
|
GuiRegistry.cpp
|
Studio3T_robomongo/src/robomongo/gui/GuiRegistry.cpp
|
#include "robomongo/gui/GuiRegistry.h"
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/settings/SettingsManager.h"
#include <QApplication>
#include <QStyle>
#include <QIcon>
namespace Robomongo
{
/**
* @brief This is a private constructor, because GuiRegistry is a singleton
*/
GuiRegistry::GuiRegistry()
{
}
/**
* @brief Functions that provide access to various icons
*/
void GuiRegistry::setAlternatingColor(QAbstractItemView *view)
{
#if defined(Q_OS_MAC)
view->setAlternatingRowColors(true);
QPalette p = view->palette();
// p.setColor(QPalette::AlternateBase, QColor(243, 246, 250));
p.setColor(QPalette::AlternateBase, QColor(245, 245, 245));
p.setColor(QPalette::Active, QPalette::Highlight, QColor(16, 108, 214));
view->setPalette(p);
#endif
}
const QIcon &GuiRegistry::serverIcon() const
{
static const QIcon serverIc = QIcon(":/robomongo/icons/server_16x16.png");
return serverIc;
}
const QIcon &GuiRegistry::serverImportedIcon() const
{
static const QIcon importedIcon = QIcon(":/robomongo/icons/server_imported_16x16.png");
return importedIcon;
}
const QIcon &GuiRegistry::serverPrimaryIcon() const
{
static const QIcon icon(":/robomongo/icons/server_primary_16x16.png");
return icon;
}
const QIcon &GuiRegistry::serverSecondaryIcon() const
{
static const QIcon icon(":/robomongo/icons/server_secondary_16x16.png");
return icon;
}
const QIcon &GuiRegistry::replicaSetIcon() const
{
static const QIcon replicaSetIc(":/robomongo/icons/replica_set_16x16.png");
return replicaSetIc;
}
const QIcon &GuiRegistry::replicaSetOfflineIcon() const
{
static const QIcon icon(":/robomongo/icons/replica_set_offline_16x16.png");
return icon;
}
const QIcon &GuiRegistry::openIcon() const
{
static const QIcon openIc = qApp->style()->standardIcon(QStyle::SP_DialogOpenButton);
//static const QIcon openIc = QIcon(":/robomongo/icons/open_32x32.png");
return openIc;
}
const QIcon &GuiRegistry::saveIcon() const
{
static const QIcon saveIc = qApp->style()->standardIcon(QStyle::SP_DialogSaveButton);
// static const QIcon saveIc = QIcon(":/robomongo/icons/save_32x32.png");
return saveIc;
}
const QIcon &GuiRegistry::databaseIcon() const
{
static const QIcon databaseIc = QIcon(":/robomongo/icons/database_16x16.png");
return databaseIc;
}
const QIcon &GuiRegistry::collectionIcon() const
{
static const QIcon collectionIc = QIcon(":/robomongo/icons/collection_16x16.png");
return collectionIc;
}
const QIcon &GuiRegistry::indexIcon() const
{
static const QIcon collectionIc = QIcon(":/robomongo/icons/index_16x16.png");
return collectionIc;
}
const QIcon &GuiRegistry::userIcon() const
{
static const QIcon userIc = QIcon(":/robomongo/icons/user_16x16.png");
return userIc;
}
const QIcon &GuiRegistry::functionIcon() const
{
static const QIcon functionIc = QIcon(":/robomongo/icons/function_16x16.png");
return functionIc;
}
const QIcon &GuiRegistry::maximizeIcon() const
{
static const QIcon maximizeIc(":/robomongo/icons/maximize.png");
return maximizeIc;
}
const QIcon &GuiRegistry::minimizeIcon() const
{
static const QIcon minimizeIc(":/robomongo/icons/minimize.png");
return minimizeIc;
}
const QIcon &GuiRegistry::undockIcon() const
{
static const QIcon undockIc(":/robomongo/icons/undock.png");
return undockIc;
}
const QIcon &GuiRegistry::dockIcon() const
{
static const QIcon dockIc(":/robomongo/icons/dock.png");
return dockIc;
}
const QIcon &GuiRegistry::textIcon() const
{
static const QIcon textIc = QIcon(":/robomongo/icons/text_16x16.png");
return textIc;
}
const QIcon &GuiRegistry::textHighlightedIcon() const
{
static const QIcon textHighlightedIc = QIcon(":/robomongo/icons/text_highlighted_16x16.png");
return textHighlightedIc;
}
const QIcon &GuiRegistry::treeIcon() const
{
static const QIcon treeIc = QIcon(":/robomongo/icons/tree_16x16.png");
return treeIc;
}
const QIcon &GuiRegistry::treeHighlightedIcon() const
{
static const QIcon treeHighlightedIc = QIcon(":/robomongo/icons/tree_highlighted_16x16.png");
return treeHighlightedIc;
}
const QIcon &GuiRegistry::tableIcon() const
{
static const QIcon treeIc = QIcon(":/robomongo/icons/table_16x16.png");
return treeIc;
}
const QIcon &GuiRegistry::tableHighlightedIcon() const
{
static const QIcon treeHighlightedIc = QIcon(":/robomongo/icons/table_highlighted_16x16.png");
return treeHighlightedIc;
}
const QIcon &GuiRegistry::customIcon() const
{
static const QIcon customIc = QIcon(":/robomongo/icons/custom_16x16.png");
return customIc;
}
const QIcon &GuiRegistry::customHighlightedIcon() const
{
static const QIcon customHighlightedIc = QIcon(":/robomongo/icons/custom_highlighted_16x16.png");
return customHighlightedIc;
}
const QIcon &GuiRegistry::rotateIcon() const
{
static const QIcon rotateIc = QIcon(":/robomongo/icons/rotate_16x16.png");
return rotateIc;
}
const QIcon &GuiRegistry::visualIcon() const
{
static const QIcon visualIc = QIcon(":/robomongo/icons/visual_16x16.png");
return visualIc;
}
const QIcon &GuiRegistry::circleIcon() const
{
static const QIcon circleIc = QIcon(":/robomongo/icons/bson_unsupported_16x16.png");
return circleIc;
}
const QIcon &GuiRegistry::bsonArrayIcon() const
{
static const QIcon bsonArrayIc = QIcon(":/robomongo/icons/bson_array_16x16.png");
return bsonArrayIc;
}
const QIcon &GuiRegistry::bsonObjectIcon() const
{
static const QIcon bsonObjectIc = QIcon(":/robomongo/icons/bson_object_16x16.png");
return bsonObjectIc;
}
const QIcon &GuiRegistry::bsonStringIcon() const
{
static const QIcon bsonStringIc = QIcon(":/robomongo/icons/bson_string_16x16.png");
return bsonStringIc;
}
const QIcon &GuiRegistry::folderIcon() const
{
static const QIcon folderIc = qApp->style()->standardIcon(QStyle::SP_DirClosedIcon);
return folderIc;
}
const QIcon &GuiRegistry::bsonIntegerIcon() const
{
static const QIcon bsonIntegerIc = QIcon(":/robomongo/icons/bson_integer_16x16.png");
return bsonIntegerIc;
}
const QIcon &GuiRegistry::bsonDoubleIcon() const
{
static const QIcon bsonDoubleIc = QIcon(":/robomongo/icons/bson_double_16x16.png");
return bsonDoubleIc;
}
const QIcon &GuiRegistry::bsonNumberDecimalIcon() const
{
static const QIcon icon(":/robomongo/icons/bson_decimal128_16x16.png");
return icon;
}
const QIcon &GuiRegistry::bsonDateTimeIcon() const
{
static const QIcon bsonDateTimeIc = QIcon(":/robomongo/icons/bson_datetime_16x16.png");
return bsonDateTimeIc;
}
const QIcon &GuiRegistry::bsonBinaryIcon() const
{
static const QIcon bsonBinaryIc = QIcon(":/robomongo/icons/bson_binary_16x16.png");
return bsonBinaryIc;
}
const QIcon &GuiRegistry::bsonNullIcon() const
{
static const QIcon bsonNullIc = QIcon(":/robomongo/icons/bson_null_16x16.png");
return bsonNullIc;
}
const QIcon &GuiRegistry::bsonBooleanIcon() const
{
static const QIcon bsonBooleanIc = QIcon(":/robomongo/icons/bson_bool_16x16.png");
return bsonBooleanIc;
}
const QIcon &GuiRegistry::noMarkIcon() const
{
static const QIcon noMarkIc = QIcon(":/robomongo/icons/no_mark_24x24.png");
return noMarkIc;
}
const QIcon &GuiRegistry::yesMarkIcon() const
{
static const QIcon yesMarkIc = QIcon(":/robomongo/icons/yes_mark_24x24.png");
return yesMarkIc;
}
const QIcon &GuiRegistry::skipMarkIcon() const
{
static const QIcon skipMarkIc = QIcon(":/robomongo/icons/skip_mark_24x24.png");
return skipMarkIc;
}
const QIcon &GuiRegistry::questionMarkIcon() const
{
static const QIcon questionMarkIc = QIcon(":/robomongo/icons/question_mark_24x24.png");
return questionMarkIc;
}
const QIcon &GuiRegistry::timeIcon() const
{
static const QIcon timeIc = QIcon(":/robomongo/icons/time_16x16.png");
return timeIc;
}
const QIcon &GuiRegistry::keyIcon() const
{
static const QIcon keyIc = QIcon(":/robomongo/icons/key_16x16.png");
return keyIc;
}
const QIcon &GuiRegistry::showIcon() const
{
static const QIcon icon = QIcon(":/robomongo/icons/show_64x64.png");
return icon;
}
const QIcon &GuiRegistry::hideIcon() const
{
static const QIcon icon = QIcon(":/robomongo/icons/hide_64x64.png");
return icon;
}
const QIcon &GuiRegistry::plusIcon() const
{
static const QIcon icon {":/robomongo/icons/plus_sign.png"};
return icon;
}
const QIcon &GuiRegistry::minusIcon() const
{
static const QIcon icon {":/robomongo/icons/minus_sign.png"};
return icon;
}
const QBrush &GuiRegistry::typeBrush() const
{
static const QBrush typeBrush = QBrush(QColor(150, 150, 150));
return typeBrush;
}
const QIcon &GuiRegistry::leftIcon() const
{
static const QIcon leftIc = QIcon(":/robomongo/icons/left_16x16.png");
return leftIc;
}
const QIcon &GuiRegistry::rightIcon() const
{
static const QIcon rightIc = QIcon(":/robomongo/icons/right_16x16.png");
return rightIc;
}
const QIcon &GuiRegistry::mongodbIcon() const
{
static const QIcon mongodbIc = QIcon(":/robomongo/icons/mongodb_16x16.png");
return mongodbIc;
}
const QIcon &GuiRegistry::mongodbIconForMAC() const
{
static const QIcon mongodbIc = QIcon(":/robomongo/icons/mongodb_icon_for_MAC.png");
return mongodbIc;
}
const QIcon &GuiRegistry::connectIcon() const
{
static const QIcon connectIc = QIcon(":/robomongo/icons/connect_24x24.png");
return connectIc;
}
const QIcon &GuiRegistry::executeIcon() const
{
static const QIcon executeIc = QIcon(":/robomongo/icons/execute_24x24.png");
return executeIc;
}
const QIcon &GuiRegistry::stopIcon() const
{
static const QIcon stopIc = QIcon(":/robomongo/icons/stop_24x24.png");
return stopIc;
}
const QIcon &GuiRegistry::exportIcon() const
{
static const QIcon exportIc = QIcon(":/robomongo/icons/export_64x64.png");
return exportIc;
}
const QIcon &GuiRegistry::importIcon() const
{
static const QIcon importIc = QIcon(":/robomongo/icons/import_64x64.png");
return importIc;
}
const QIcon &GuiRegistry::deleteIcon() const
{
static const QIcon icon(":/robomongo/icons/delete.png");
return icon;
}
const QIcon &GuiRegistry::deleteIconRed() const
{
static const QIcon icon(":/robomongo/icons/delete_red_color.png");
return icon;
}
const QIcon &GuiRegistry::deleteIconMouseHovered() const
{
static const QIcon icon(":/robomongo/icons/delete_mouse_hovered.png");
return icon;
}
const QIcon &GuiRegistry::mainWindowIcon() const
{
static const QIcon mainWindowIc = QIcon(":/robomongo/icons/logo-256x256.png");
return mainWindowIc;
}
const QIcon& GuiRegistry::welcomeTabIcon() const
{
static const QIcon icon(":/robomongo/icons/welcome_tab_icon.png");
return icon;
}
const QFont &GuiRegistry::font() const
{
QString family = AppRegistry::instance().settingsManager()->textFontFamily();
if (family.isEmpty()) {
#if defined(Q_OS_MAC)
family = "Monaco";
#elif defined(Q_OS_UNIX)
family = "Monospace";
#elif defined(Q_OS_WIN)
family = "Courier";
#endif
}
int pointSize = AppRegistry::instance().settingsManager()->textFontPointSize();
if (pointSize < 1) {
#if defined(Q_OS_MAC)
pointSize = 12;
#elif defined(Q_OS_UNIX)
pointSize = -1;
#elif defined(Q_OS_WIN)
pointSize = 10;
#endif
}
static QFont textFont = QFont(family, pointSize);
#if defined(Q_OS_UNIX)
textFont.setFixedPitch(true);
#endif
return textFont;
}
}
| 13,001
|
C++
|
.cpp
| 379
| 27.701847
| 105
| 0.661856
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,694
|
MainWindow.cpp
|
Studio3T_robomongo/src/robomongo/gui/MainWindow.cpp
|
#include "robomongo/gui/MainWindow.h"
#include <QApplication>
#include <QToolButton>
#include <QMessageBox>
#include <QWidgetAction>
#include <QMenuBar>
#include <QMenu>
#include <QKeyEvent>
#include <QToolBar>
#include <QToolTip>
#include <QDockWidget>
#include <QDesktopWidget>
#include <QTimer>
#include <QPushButton>
#include <QLabel>
#include <QStatusBar>
#include <QHBoxLayout>
#include <QSettings>
#include <QSystemTrayIcon>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QTextDocument>
#include <mongo/logger/log_severity.h>
#include "robomongo/core/settings/SettingsManager.h"
#include "robomongo/core/settings/SshSettings.h"
#include "robomongo/core/domain/MongoServer.h"
#include "robomongo/core/domain/App.h"
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/EventBus.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/core/utils/Logger.h"
#include "robomongo/gui/widgets/LogWidget.h"
#include "robomongo/gui/widgets/explorer/ExplorerWidget.h"
#include "robomongo/gui/widgets/explorer/ExplorerCollectionTreeItem.h"
#include "robomongo/gui/widgets/explorer/ExplorerTreeWidget.h"
#include "robomongo/gui/widgets/workarea/WorkAreaTabWidget.h"
#include "robomongo/gui/widgets/workarea/QueryWidget.h"
#include "robomongo/gui/widgets/workarea/QueryWidget.h"
#include "robomongo/gui/widgets/workarea/WelcomeTab.h"
#include "robomongo/gui/dialogs/ConnectionsDialog.h"
#include "robomongo/gui/dialogs/AboutDialog.h"
#include "robomongo/gui/dialogs/PreferencesDialog.h"
#include "robomongo/gui/dialogs/ExportDialog.h"
#include "robomongo/gui/dialogs/ChangeShellTimeoutDialog.h"
#include "robomongo/gui/GuiRegistry.h"
#include "robomongo/gui/AppStyle.h"
namespace
{
void setToolBarIconSize(QToolBar *toolBar)
{
#if defined(Q_OS_MAC)
const int size = 20;
#else
const int size = 24;
#endif
toolBar->setIconSize(QSize(size, size));
}
void saveViewMode(Robomongo::ViewMode mode)
{
Robomongo::AppRegistry::instance().settingsManager()->setViewMode(mode);
Robomongo::AppRegistry::instance().settingsManager()->save();
}
void saveAutoExpand(bool isExpand)
{
Robomongo::AppRegistry::instance().settingsManager()->setAutoExpand(isExpand);
Robomongo::AppRegistry::instance().settingsManager()->save();
}
void saveAutoExec(bool isAutoExec)
{
Robomongo::AppRegistry::instance().settingsManager()->setAutoExec(isAutoExec);
Robomongo::AppRegistry::instance().settingsManager()->save();
}
void saveMinimizeToTraySettings(bool isMinimizingToTray)
{
Robomongo::AppRegistry::instance().settingsManager()->setMinimizeToTray(isMinimizingToTray);
Robomongo::AppRegistry::instance().settingsManager()->save();
}
void saveLineNumbers(bool showLineNumbers)
{
Robomongo::AppRegistry::instance().settingsManager()->setLineNumbers(showLineNumbers);
Robomongo::AppRegistry::instance().settingsManager()->save();
}
}
/* End of anonymous namespace */
namespace Robomongo
{
/* -------------------------------- ConnectionMenu ---------------------------- */
class ConnectionMenu : public QMenu
{
public:
ConnectionMenu(QWidget *parent) : QMenu(parent) {}
protected:
virtual void keyPressEvent(QKeyEvent *event) override
{
if (event->key() == Qt::Key_F12) {
hide();
}
else {
QMenu::keyPressEvent(event);
}
}
};
/* -------------------------------- MainWindow --------------------------------- */
// In milliseconds
constexpr int ONE_HOUR = 3'600'000; // (3'600'000 msec = 60 * 60 * 1000 msec)
constexpr int THIRTY_SECONDS = 30'000;
constexpr int ONE_SECOND = 1'000;
MainWindow::MainWindow()
: BaseClass(),
_logDock(nullptr), _workArea(nullptr), _explorer(nullptr), _app(AppRegistry::instance().app()),
_connectionsMenu(nullptr), _connectButton(nullptr), _viewMenu(nullptr), _toolbarsMenu(nullptr),
_connectAction(nullptr), _openAction(nullptr), _saveAction(nullptr), _saveAsAction(nullptr),
_executeAction(nullptr), _stopAction(nullptr), _orientationAction(nullptr), _execToolBar(nullptr),
#if defined(Q_OS_WIN)
_trayIcon(nullptr),
#endif
_allowExit(false)
{
QColor background = palette().window().color();
QString controlKey = "Ctrl";
#if defined(Q_OS_MAC)
QString explorerColor = "#EFEFEF"; // was #CED6DF"
controlKey = QChar(0x2318); // "Command" key aka Cauliflower
setUnifiedTitleAndToolBarOnMac(true);
#elif defined(Q_OS_LINUX)
QString explorerColor = background.darker(103).name();
#else
QString explorerColor = background.lighter(103).name();
#endif
qApp->setStyleSheet(QString(
"QWidget#queryWidget { background-color:#E7E5E4; margin: 0px; padding:0px; } \n"
"Robomongo--ExplorerTreeWidget#explorerTree { padding: 1px 0px 0px 0px; background-color: %1; border: 0px; } \n"
"QMainWindow::separator { background: #E7E5E4; width: 1px; } \n"
"QMessageBox { messagebox-text-interaction-flags: 5; }" // Make QMessageBox text selectable
).arg(explorerColor));
_openAction = new QAction(GuiRegistry::instance().openIcon(), tr("&Open..."), this);
_openAction->setToolTip(QString("Load script from the file to the currently opened shell <b>(%1 + O)</b>").arg(controlKey));
_openAction->setShortcuts(QKeySequence::Open);
VERIFY(connect(_openAction, SIGNAL(triggered()), this, SLOT(open())));
_saveAction = new QAction(GuiRegistry::instance().saveIcon(), tr("&Save"), this);
_saveAction->setShortcuts(QKeySequence::Save);
_saveAction->setToolTip(QString("Save script of the currently opened shell to the file <b>(%1 + S)</b>").arg(controlKey));
VERIFY(connect(_saveAction, SIGNAL(triggered()), this, SLOT(save())));
_saveAsAction = new QAction(tr("Save &As..."), this);
_saveAsAction->setShortcuts(QKeySequence::SaveAs);
VERIFY(connect(_saveAsAction, SIGNAL(triggered()), this, SLOT(saveAs())));
// Exit action
QAction *exitAction = new QAction("&Exit", this);
exitAction->setShortcuts(QKeySequence::Quit);
VERIFY(connect(exitAction, SIGNAL(triggered()), this, SLOT(exit())));
// Connect action
_connectAction = new QAction("&Connect...", this);
_connectAction->setShortcuts(QKeySequence::New);
_connectAction->setIcon(GuiRegistry::instance().connectIcon());
_connectAction->setIconText("Connect");
_connectAction->setToolTip(QString("Connect to local or remote MongoDB instance <b>(%1 + N)</b>").arg(controlKey));
VERIFY(connect(_connectAction, SIGNAL(triggered()), this, SLOT(manageConnections())));
_connectionsMenu = new ConnectionMenu(this);
VERIFY(connect(_connectionsMenu, SIGNAL(triggered(QAction*)), this, SLOT(connectToServer(QAction*))));
updateConnectionsMenu();
_connectButton = new QToolButton();
_connectButton->setText("&Connect...");
_connectButton->setIcon(GuiRegistry::instance().connectIcon());
_connectButton->setFocusPolicy(Qt::NoFocus);
_connectButton->setToolTip(QString("Connect to local or remote MongoDB instance <b>(%1 + N)</b>").arg(controlKey));
_connectButton->setToolButtonStyle(Qt::ToolButtonIconOnly);
#if !defined(Q_OS_MAC)
_connectButton->setMenu(_connectionsMenu);
_connectButton->setPopupMode(QToolButton::MenuButtonPopup);
#endif
VERIFY(connect(_connectButton, SIGNAL(clicked()), this, SLOT(manageConnections())));
QWidgetAction *connectButtonAction = new QWidgetAction(this);
connectButtonAction->setDefaultWidget(_connectButton);
// Tray icon
#if defined(Q_OS_WIN)
_trayIcon = new QSystemTrayIcon(GuiRegistry::instance().mainWindowIcon());
VERIFY(connect(_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayActivated(QSystemTrayIcon::ActivationReason))));
auto trayMinimizeAction = new QAction("Minimize to Tray", _trayIcon);
VERIFY(connect(trayMinimizeAction, SIGNAL(triggered()), this, SLOT(toggleMinimize())));
auto trayExitAction = new QAction("Exit", _trayIcon);
VERIFY(connect(trayExitAction, SIGNAL(triggered()), this, SLOT(exit())));
auto contextMenu = new QMenu();
contextMenu->addAction(trayMinimizeAction);
contextMenu->addSeparator();
contextMenu->addAction(trayExitAction);
_trayIcon->setContextMenu(contextMenu);
#endif
// Orientation action
_orientationAction = new QAction("&Rotate", this);
_orientationAction->setShortcut(Qt::Key_F10);
_orientationAction->setIcon(GuiRegistry::instance().rotateIcon());
_orientationAction->setToolTip("Toggle orientation of results view <b>(F10)</b>");
VERIFY(connect(_orientationAction, SIGNAL(triggered()), this, SLOT(toggleOrientation())));
// read view mode setting
ViewMode viewMode = AppRegistry::instance().settingsManager()->viewMode();
// Text mode action
auto textModeAction = new QAction("&Text Mode", this);
textModeAction->setShortcut(Qt::Key_F4);
textModeAction->setIcon(GuiRegistry::instance().textHighlightedIcon());
textModeAction->setToolTip("Show current tab in text mode, and make this mode default for all subsequent queries <b>(F4)</b>");
textModeAction->setCheckable(true);
textModeAction->setChecked(viewMode == Text);
VERIFY(connect(textModeAction, SIGNAL(triggered()), this, SLOT(enterTextMode())));
// Tree mode action
QAction *treeModeAction = new QAction("&Tree Mode", this);
treeModeAction->setShortcut(Qt::Key_F2);
treeModeAction->setIcon(GuiRegistry::instance().treeHighlightedIcon());
treeModeAction->setToolTip("Show current tab in tree mode, and make this mode default for all subsequent queries <b>(F3)</b>");
treeModeAction->setCheckable(true);
treeModeAction->setChecked(viewMode == Tree);
VERIFY(connect(treeModeAction, SIGNAL(triggered()), this, SLOT(enterTreeMode())));
// Tree mode action
QAction *tableModeAction = new QAction("T&able Mode", this);
tableModeAction->setShortcut(Qt::Key_F3);
tableModeAction->setIcon(GuiRegistry::instance().tableHighlightedIcon());
tableModeAction->setToolTip("Show current tab in table mode, and make this mode default for all subsequent queries <b>(F3)</b>");
tableModeAction->setCheckable(true);
tableModeAction->setChecked(viewMode == Table);
VERIFY(connect(tableModeAction, SIGNAL(triggered()), this, SLOT(enterTableMode())));
// Custom mode action
QAction *customModeAction = new QAction("&Custom Mode", this);
//customModeAction->setShortcut(Qt::Key_F2);
customModeAction->setIcon(GuiRegistry::instance().customHighlightedIcon());
customModeAction->setToolTip("Show current tab in custom mode if possible, and make this mode default for all subsequent queries <b>(F2)</b>");
customModeAction->setCheckable(true);
customModeAction->setChecked(viewMode == Custom);
VERIFY(connect(customModeAction, SIGNAL(triggered()), this, SLOT(enterCustomMode())));
// Execute action
_executeAction = new QAction(this);
_executeAction->setData("Execute");
_executeAction->setIcon(GuiRegistry::instance().executeIcon());
_executeAction->setShortcut(Qt::Key_F5);
_executeAction->setToolTip(QString("Execute query for current tab. If you have some selection in query text - only selection will be executed <b>(F5 </b> or <b>%1 + Enter)</b>").arg(controlKey));
VERIFY(connect(_executeAction, SIGNAL(triggered()), SLOT(executeScript())));
// Stop action
_stopAction = new QAction(this);
_stopAction->setData("Stop");
_stopAction->setIcon(GuiRegistry::instance().stopIcon());
_stopAction->setShortcut(Qt::Key_F6);
_stopAction->setToolTip("Stop execution of currently running script. <b>(F6)</b>");
_stopAction->setDisabled(true);
VERIFY(connect(_stopAction, SIGNAL(triggered()), SLOT(stopScript())));
// Refresh action
QAction *refreshAction = new QAction("Refresh", this);
refreshAction->setIcon(qApp->style()->standardIcon(QStyle::SP_BrowserReload));
VERIFY(connect(refreshAction, SIGNAL(triggered()), this, SLOT(refreshConnections())));
/*** File menu ***/
QMenu *fileMenu = menuBar()->addMenu("File");
fileMenu->addAction(_connectAction);
fileMenu->addSeparator();
fileMenu->addAction(_openAction);
fileMenu->addAction(_saveAction);
fileMenu->addAction(_saveAsAction);
fileMenu->addSeparator();
fileMenu->addAction(exitAction);
/*** View menu ***/
_viewMenu = menuBar()->addMenu("View");
// adds option to toggle Explorer and Logs panels
createDatabaseExplorer();
_toolbarsMenu = _viewMenu->addMenu(tr("Toolbars"));
// adds Themes submenu
createStylesMenu();
/*** Options menu ***/
QMenu *optionsMenu = menuBar()->addMenu("Options");
// View Mode
QMenu *defaultViewModeMenu = optionsMenu->addMenu("Default View Mode");
defaultViewModeMenu->addAction(customModeAction);
defaultViewModeMenu->addAction(treeModeAction);
defaultViewModeMenu->addAction(tableModeAction);
defaultViewModeMenu->addAction(textModeAction);
optionsMenu->addSeparator();
QActionGroup *modeGroup = new QActionGroup(this);
modeGroup->addAction(textModeAction);
modeGroup->addAction(treeModeAction);
modeGroup->addAction(tableModeAction);
modeGroup->addAction(customModeAction);
// Time Zone
QAction *utcTime = new QAction(convertTimesToString(Utc), this);
utcTime->setCheckable(true);
utcTime->setChecked(AppRegistry::instance().settingsManager()->timeZone() == Utc);
VERIFY(connect(utcTime, SIGNAL(triggered()), this, SLOT(setUtcTimeZone())));
QAction *localTime = new QAction(convertTimesToString(LocalTime), this);
localTime->setCheckable(true);
localTime->setChecked(AppRegistry::instance().settingsManager()->timeZone() == LocalTime);
VERIFY(connect(localTime, SIGNAL(triggered()), this, SLOT(setLocalTimeZone())));
QMenu *timeMenu = optionsMenu->addMenu("Display Dates In...");
timeMenu->addAction(utcTime);
timeMenu->addAction(localTime);
QActionGroup *timeZoneGroup = new QActionGroup(this);
timeZoneGroup->addAction(utcTime);
timeZoneGroup->addAction(localTime);
// UUID encoding
QAction *defaultEncodingAction = new QAction("Do not decode (show as is)", this);
defaultEncodingAction->setCheckable(true);
defaultEncodingAction->setChecked(AppRegistry::instance().settingsManager()->uuidEncoding() == DefaultEncoding);
VERIFY(connect(defaultEncodingAction, SIGNAL(triggered()), this, SLOT(setDefaultUuidEncoding())));
QAction *javaLegacyEncodingAction = new QAction("Use Java Encoding", this);
javaLegacyEncodingAction->setCheckable(true);
javaLegacyEncodingAction->setChecked(AppRegistry::instance().settingsManager()->uuidEncoding() == JavaLegacy);
VERIFY(connect(javaLegacyEncodingAction, SIGNAL(triggered()), this, SLOT(setJavaUuidEncoding())));
QAction *csharpLegacyEncodingAction = new QAction("Use .NET Encoding", this);
csharpLegacyEncodingAction->setCheckable(true);
csharpLegacyEncodingAction->setChecked(AppRegistry::instance().settingsManager()->uuidEncoding() == CSharpLegacy);
VERIFY(connect(csharpLegacyEncodingAction, SIGNAL(triggered()), this, SLOT(setCSharpUuidEncoding())));
QAction *pythonEncodingAction = new QAction("Use Python Encoding", this);
pythonEncodingAction->setCheckable(true);
pythonEncodingAction->setChecked(AppRegistry::instance().settingsManager()->uuidEncoding() == PythonLegacy);
VERIFY(connect(pythonEncodingAction, SIGNAL(triggered()), this, SLOT(setPythonUuidEncoding())));
QMenu *uuidMenu = optionsMenu->addMenu("Legacy UUID Encoding");
uuidMenu->addAction(defaultEncodingAction);
uuidMenu->addAction(javaLegacyEncodingAction);
uuidMenu->addAction(csharpLegacyEncodingAction);
uuidMenu->addAction(pythonEncodingAction);
// Read Autocompletion Mode
AutocompletionMode autocompletionMode = AppRegistry::instance().settingsManager()->autocompletionMode();
// Autocompletion
QAction *autocompletionAllAction = new QAction("All", this);
autocompletionAllAction->setCheckable(true);
autocompletionAllAction->setChecked(autocompletionMode == AutocompleteAll);
VERIFY(connect(autocompletionAllAction, SIGNAL(triggered()), this, SLOT(setShellAutocompletionAll())));
QAction *autocompletionNoCollectionNamesAction = new QAction("All (Except Collection Names)", this);
autocompletionNoCollectionNamesAction->setCheckable(true);
autocompletionNoCollectionNamesAction->setChecked(autocompletionMode == AutocompleteNoCollectionNames);
VERIFY(connect(autocompletionNoCollectionNamesAction, SIGNAL(triggered()), this, SLOT(setShellAutocompletionNoCollectionNames())));
QAction *autocompletionNoneAction = new QAction("None", this);
autocompletionNoneAction->setCheckable(true);
autocompletionNoneAction->setChecked(autocompletionMode == AutocompleteNone);
VERIFY(connect(autocompletionNoneAction, SIGNAL(triggered()), this, SLOT(setShellAutocompletionNone())));
QMenu *autocompletionMenu = optionsMenu->addMenu("Autocompletion Mode");
autocompletionMenu->addAction(autocompletionAllAction);
autocompletionMenu->addAction(autocompletionNoCollectionNamesAction);
autocompletionMenu->addAction(autocompletionNoneAction);
QActionGroup *autocompletionGroup = new QActionGroup(this);
autocompletionGroup->addAction(autocompletionAllAction);
autocompletionGroup->addAction(autocompletionNoCollectionNamesAction);
autocompletionGroup->addAction(autocompletionNoneAction);
QAction *loadMongoRcJs = new QAction("Load .mongorc.js", this);
loadMongoRcJs->setCheckable(true);
loadMongoRcJs->setChecked(AppRegistry::instance().settingsManager()->loadMongoRcJs());
VERIFY(connect(loadMongoRcJs, SIGNAL(triggered()), this, SLOT(setLoadMongoRcJs())));
optionsMenu->addSeparator();
optionsMenu->addAction(loadMongoRcJs);
optionsMenu->addSeparator();
QAction *autoExpand = new QAction("Auto Expand First Document", this);
autoExpand->setCheckable(true);
autoExpand->setChecked(AppRegistry::instance().settingsManager()->autoExpand());
VERIFY(connect(autoExpand, SIGNAL(triggered()), this, SLOT(toggleAutoExpand())));
optionsMenu->addAction(autoExpand);
QAction *showLineNumbers = new QAction("Show Line Numbers By Default", this);
showLineNumbers->setCheckable(true);
showLineNumbers->setChecked(AppRegistry::instance().settingsManager()->lineNumbers());
VERIFY(connect(showLineNumbers, SIGNAL(triggered()), this, SLOT(toggleLineNumbers())));
optionsMenu->addAction(showLineNumbers);
QAction *disabelConnectionShortcuts = new QAction("Disable Connection Shortcuts", this);
disabelConnectionShortcuts->setCheckable(true);
disabelConnectionShortcuts->setChecked(AppRegistry::instance().settingsManager()->disableConnectionShortcuts());
VERIFY(connect(disabelConnectionShortcuts, SIGNAL(triggered()), this, SLOT(setDisableConnectionShortcuts())));
optionsMenu->addAction(disabelConnectionShortcuts);
QAction *autoExec = new QAction(tr("Automatically execute code in new tab"), this);
autoExec->setCheckable(true);
autoExec->setChecked(AppRegistry::instance().settingsManager()->autoExec());
VERIFY(connect(autoExec, SIGNAL(triggered()), this, SLOT(toggleAutoExec())));
optionsMenu->addAction(autoExec);
#if defined(Q_OS_WIN)
QAction *minimizeTray = new QAction("Close button should minimize to system tray");
minimizeTray->setCheckable(true);
minimizeTray->setChecked(AppRegistry::instance().settingsManager()->minimizeToTray());
VERIFY(connect(minimizeTray, SIGNAL(triggered()), this, SLOT(toggleMinimizeToTray())));
optionsMenu->addAction(minimizeTray);
#endif
auto checkUpdates = new QAction(tr("Check For Updates"), this);
checkUpdates->setCheckable(true);
checkUpdates->setChecked(AppRegistry::instance().settingsManager()->checkForUpdates());
VERIFY(connect(checkUpdates, SIGNAL(triggered()), this, SLOT(toggleCheckUpdates())));
optionsMenu->addAction(checkUpdates);
auto changeShellTimeout = new QAction(tr("Change Shell Timeout..."), this);
VERIFY(connect(changeShellTimeout, SIGNAL(triggered()), this, SLOT(openShellTimeoutDialog())));
optionsMenu->addAction(changeShellTimeout);
QAction *preferencesAction = new QAction("Preferences", this);
VERIFY(connect(preferencesAction, SIGNAL(triggered()), this, SLOT(openPreferences())));
preferencesAction->setVisible(false);
optionsMenu->addAction(preferencesAction);
QActionGroup *uuidEncodingGroup = new QActionGroup(this);
uuidEncodingGroup->addAction(defaultEncodingAction);
uuidEncodingGroup->addAction(javaLegacyEncodingAction);
uuidEncodingGroup->addAction(csharpLegacyEncodingAction);
uuidEncodingGroup->addAction(pythonEncodingAction);
/*** Window menu ***/
// Full screen action
QAction *fullScreenAction = new QAction("&Full Screen", this);
#if !defined(Q_OS_MAC)
fullScreenAction->setShortcut(Qt::Key_F11);
#else
fullScreenAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_F11));
#endif
fullScreenAction->setVisible(true);
VERIFY(connect(fullScreenAction, SIGNAL(triggered()), this, SLOT(toggleFullScreen2())));
// Minimize window
QAction *minimizeAction = new QAction("&Minimize", this);
minimizeAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_M));
minimizeAction->setVisible(true);
VERIFY(connect(minimizeAction, SIGNAL(triggered()), this, SLOT(showMinimized())));
// Next tab
QAction *nexttabAction = new QAction("Select Next Tab", this);
nexttabAction->setShortcuts(QKeySequence::NextChild);
nexttabAction->setVisible(true);
VERIFY(connect(nexttabAction, SIGNAL(triggered()), this, SLOT(selectNextTab())));
// Previous tab
QAction *prevtabAction = new QAction("Select Previous Tab", this);
prevtabAction->setShortcuts(QKeySequence::PreviousChild);
prevtabAction->setVisible(true);
VERIFY(connect(prevtabAction, SIGNAL(triggered()), this, SLOT(selectPrevTab())));
// Reload action (currently a re-execute, as does not "reload" files per issue #447)
QAction *reloadAction = new QAction("Re-execute Query in Current Tab", this);
reloadAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R));
reloadAction->setVisible(true);
VERIFY(connect(reloadAction, SIGNAL(triggered()), SLOT(executeScript())));
// Duplicate tab action
QAction *duplicateAction = new QAction("Duplicate Query in New Tab", this);
duplicateAction->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_T);
duplicateAction->setVisible(true);
VERIFY(connect(duplicateAction, SIGNAL(triggered()), SLOT(duplicateTab())));
// Window menu
QMenu *windowMenu = menuBar()->addMenu("Window");
//minimize
windowMenu->addAction(fullScreenAction);
windowMenu->addAction(minimizeAction);
windowMenu->addSeparator();
windowMenu->addAction(nexttabAction);
windowMenu->addAction(prevtabAction);
windowMenu->addSeparator();
windowMenu->addAction(reloadAction);
windowMenu->addAction(duplicateAction);
windowMenu->addSeparator();
auto const& settings { AppRegistry::instance().settingsManager() };
if (!settings->disableHttpsFeatures()) {
// Open welcome tab action
auto openWelcomeTabAction = new QAction("Open/Refresh Welcome Tab", this);
openWelcomeTabAction->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_W);
openWelcomeTabAction->setVisible(true);
VERIFY(connect(openWelcomeTabAction, SIGNAL(triggered()), SLOT(openWelcomeTab())));
windowMenu->addAction(openWelcomeTabAction);
}
auto toolbarsSettings = AppRegistry::instance().settingsManager()->toolbars();
/*** About menu ***/
QAction *aboutRobomongoAction = new QAction("&About Robo 3T...", this);
VERIFY(connect(aboutRobomongoAction, SIGNAL(triggered()), this, SLOT(aboutRobomongo())));
// Options menu
QMenu *helpMenu = menuBar()->addMenu("Help");
helpMenu->addAction(aboutRobomongoAction);
// Toolbar
QToolBar *connectToolBar = new QToolBar(tr("Connections Toolbar"), this);
connectToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
connectToolBar->addAction(connectButtonAction);
connectToolBar->setShortcutEnabled(1, true);
connectToolBar->setMovable(false);
connectToolBar->setVisible(true /*toolbarsSettings["connect"].toBool()*/);
_toolbarsMenu->addAction(connectToolBar->toggleViewAction());
VERIFY(connect(connectToolBar->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onConnectToolbarVisibilityChanged(bool))));
setToolBarIconSize(connectToolBar);
addToolBar(connectToolBar);
QToolBar *openSaveToolBar = new QToolBar(tr("Open/Save Toolbar"), this);
openSaveToolBar->addAction(_openAction);
openSaveToolBar->addAction(_saveAction);
openSaveToolBar->setMovable(false);
openSaveToolBar->setVisible(true /*toolbarsSettings["open_save"].toBool()*/);
_toolbarsMenu->addAction(openSaveToolBar->toggleViewAction());
VERIFY(connect(openSaveToolBar->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onOpenSaveToolbarVisibilityChanged(bool))));
setToolBarIconSize(openSaveToolBar);
addToolBar(openSaveToolBar);
_execToolBar = new QToolBar(tr("Execution Toolbar"), this);
_execToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
_execToolBar->addAction(_executeAction);
_execToolBar->addAction(_stopAction);
_execToolBar->addAction(_orientationAction);
_execToolBar->setShortcutEnabled(1, true);
_execToolBar->setMovable(false);
_execToolBar->setVisible(true /*toolbarsSettings["exec"].toBool()*/);
setToolBarIconSize(_execToolBar);
addToolBar(_execToolBar);
_updateLabel = new QLabel;
_updateLabel->setWordWrap(true);
_updateLabel->setOpenExternalLinks(true);
_updateLabel->setTextFormat(Qt::TextFormat::RichText);
_updateLabel->setIndent(_updateLabel->fontMetrics().width("T"));
_closeButton = new QPushButton;
_closeButton->setIcon(QIcon(":/robomongo/icons/close_hover_16x16.png"));
_closeButton->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Minimum);
_closeButton->setMouseTracking(true);
_closeButton->setAttribute(Qt::WA_Hover);
_closeButton->installEventFilter(this);
VERIFY(connect(_closeButton, SIGNAL(clicked()), this, SLOT(on_closeButton_clicked())));
auto updateBarLay = new QHBoxLayout;
updateBarLay->addWidget(_updateLabel);
updateBarLay->addWidget(_closeButton, Qt::AlignRight);
updateBarLay->setSpacing(0);
updateBarLay->setMargin(0);
auto updateBarWid = new QWidget;
updateBarWid->setLayout(updateBarLay);
_updateBar = new QToolBar("Updates Toolbar");
_updateBar->addWidget(updateBarWid);
_updateBar->setStyleSheet("background-color: #b3e0ff; border: none;"); // blue
addToolBarBreak();
addToolBar(_updateBar);
_updateBar->setHidden(true);
_updateBar->setMovable(false);
_toolbarsMenu->addAction(_execToolBar->toggleViewAction());
VERIFY(connect(_execToolBar->toggleViewAction(), SIGNAL(triggered(bool)),
this, SLOT(onExecToolbarVisibilityChanged(bool))));
createTabs();
createStatusBar();
setWindowTitle("Robo 3T - " + QString(PROJECT_VERSION_SHORT));
setWindowIcon(GuiRegistry::instance().mainWindowIcon());
QTimer::singleShot(0, this, SLOT(manageConnections()));
updateMenus();
_updateMenusAtStart = false;
AppRegistry::instance().bus()->subscribe(this, ConnectionFailedEvent::Type);
AppRegistry::instance().bus()->subscribe(this, ScriptExecutedEvent::Type);
AppRegistry::instance().bus()->subscribe(this, ScriptExecutingEvent::Type);
AppRegistry::instance().bus()->subscribe(this, QueryWidgetUpdatedEvent::Type);
AppRegistry::instance().bus()->subscribe(this, OperationFailedEvent::Type);
restoreWindowSettings();
// Catch application windows focus changes
VERIFY(connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(on_focusChanged())));
_networkAccessManager = new QNetworkAccessManager;
VERIFY(connect(_networkAccessManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(on_networkReply(QNetworkReply*))));
if (!settings->disableHttpsFeatures() && settings->checkForUpdates()) {
// First check for updates THIRTY_SECONDS after program start
QTimer::singleShot(THIRTY_SECONDS, this, SLOT(checkUpdates()));
// Then, check for updates every 1 hour
auto const timer { new QTimer(this) };
VERIFY(connect(timer, SIGNAL(timeout()), this, SLOT(checkUpdates())));
timer->start(ONE_HOUR);
}
setUnifiedTitleAndToolBarOnMac(false); // https://bugreports.qt.io/browse/QTBUG-68946
}
void MainWindow::createStylesMenu()
{
_viewMenu->addSeparator();
QMenu *styles = _viewMenu->addMenu("Theme");
QStringList supportedStyles = AppStyleUtils::getSupportedStyles();
QActionGroup *styleGroup = new QActionGroup(this);
VERIFY(connect(styleGroup, SIGNAL(triggered(QAction *)), this, SLOT(changeStyle(QAction *))));
const QString ¤tStyle = AppRegistry::instance().settingsManager()->currentStyle();
for (QStringList::const_iterator it = supportedStyles.begin(); it != supportedStyles.end(); ++it) {
const QString &style = *it;
QAction *styleAction = new QAction(style, this);
styleAction->setCheckable(true);
styleAction->setChecked(style == currentStyle);
styleGroup->addAction(styleAction);
styles->addAction(styleAction);
}
}
void MainWindow::createStatusBar()
{
QColor windowColor = palette().window().color();
QColor buttonBgColor = windowColor.lighter(105);
QColor buttonBorderBgColor = windowColor.darker(112);
QColor buttonPressedColor = windowColor.darker(102);
QToolButton *log = new QToolButton(this);
log->setText("Logs");
log->setCheckable(true);
log->setDefaultAction(_logDock->toggleViewAction());
log->setStyleSheet(QString(
"QToolButton {"
" background-color: %1;"
" border-style: outset;"
" border-width: 1px;"
" border-radius: 4px;"
" border-color: %2;"
" padding: 1px 10px 1px 10px;"
"} \n"
""
"QToolButton:checked, QToolButton:pressed {"
" background-color: %3;"
" border-style: inset;"
"}")
.arg(buttonBgColor.name())
.arg(buttonBorderBgColor.name())
.arg(buttonPressedColor.name()));
statusBar()->insertWidget(0, log);
statusBar()->setStyleSheet("QStatusBar::item { border: 0px solid black };");
}
void MainWindow::changeStyle(QAction *ac)
{
const QString &text = ac->text();
AppStyleUtils::applyStyle(text);
AppRegistry::instance().settingsManager()->setCurrentStyle(text);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::exit()
{
_allowExit = true;
close();
}
void MainWindow::restoreWindowSettings()
{
QSettings settings("3T", "Robomongo");
// Restore settings if registery key exists, otherwise resize as app started for the first time.
if (settings.contains("MainWindow/geometry"))
{
restoreGeometry(settings.value("MainWindow/geometry").toByteArray());
}
else
{
// Resize main window. We are trying to keep it "almost" maximized.
QRect screenGeometry = QApplication::desktop()->availableGeometry();
int horizontalMargin = static_cast<int>(screenGeometry.width() * 0.1);
int verticalMargin = static_cast<int>(screenGeometry.height() * 0.1);
int _width = screenGeometry.width() - horizontalMargin;
int _height = screenGeometry.height() - verticalMargin;
resize(QSize(_width, _height));
// Center main window
int x = (screenGeometry.width() - width()) / 2;
int y = (screenGeometry.height() - height()) / 2;
move(x, y);
}
}
void MainWindow::saveWindowSettings() const
{
QSettings settings("3T", "Robomongo");
settings.setValue("MainWindow/geometry", saveGeometry());
}
void MainWindow::adjustUpdatesBarHeight()
{
if (!AppRegistry::instance().settingsManager()->checkForUpdates() || !_updateBar->isVisible())
return;
QTextDocument doc;
doc.setHtml(_updateLabel->text());
int const strWidth = _updateLabel->fontMetrics().width(doc.toPlainText());
int const lineHeight = _updateLabel->fontMetrics().height();
int const widthForUpdateStr = width() - _closeButton->width();
if (0 == widthForUpdateStr)
return;
#ifdef __APPLE__
_updateLabel->setFixedHeight((strWidth / widthForUpdateStr + 1) * lineHeight * 1.3);
#else
_updateLabel->setFixedHeight((strWidth / widthForUpdateStr + 1) * lineHeight);
#endif
}
void MainWindow::open()
{
QueryWidget *wid = _workArea->currentQueryWidget();
if (wid) {
wid->openFile();
}
else { // todo: currently this case not handled properly, since "Open" button is
// disabled when no tabs exist
auto connectionsCopy = AppRegistry::instance().settingsManager()->connections();
if (connectionsCopy.size() == 1) {
ScriptInfo inf = ScriptInfo(QString());
if (inf.loadFromFile()) {
// todo: for now do not open new shell
_app->openShell(nullptr, connectionsCopy.at(0), inf);
}
}
}
}
void MainWindow::save()
{
QueryWidget *wid = _workArea->currentQueryWidget();
if (wid) {
wid->saveToFile();
}
}
void MainWindow::saveAs()
{
QueryWidget *wid = _workArea->currentQueryWidget();
if (wid) {
wid->savebToFileAs();
}
}
void MainWindow::updateConnectionsMenu()
{
_connectionsMenu->clear();
int number = 1;
// Populate list with connections
SettingsManager::ConnectionSettingsContainerType connections = AppRegistry::instance().settingsManager()->connections();
for (SettingsManager::ConnectionSettingsContainerType::const_iterator it = connections.begin(); it != connections.end(); ++it) {
ConnectionSettings *connection = *it;
QAction *action = new QAction(QtUtils::toQString(connection->getReadableName()), this);
action->setData(QVariant::fromValue(connection));
if (number <= 9 && !AppRegistry::instance().settingsManager()->disableConnectionShortcuts()) {
action->setShortcut(QKeySequence(QString("Alt+").append(QString::number(number))));
}
_connectionsMenu->addAction(action);
++number;
}
if (AppRegistry::instance().settingsManager()->connections().size() > 0)
_connectionsMenu->addSeparator();
// Connect action
QAction *connectAction = new QAction("&Manage Connections...", this);
connectAction->setIcon(GuiRegistry::instance().connectIcon());
connectAction->setToolTip("Connect to MongoDB");
VERIFY(connect(connectAction, SIGNAL(triggered()), this, SLOT(manageConnections())));
_connectionsMenu->addAction(connectAction);
}
WelcomeTab* MainWindow::getWelcomeTab()
{
return _workArea->getWelcomeTab();
}
void MainWindow::showQueryWidgetProgressBar() const
{
if (QueryWidget *widget = _workArea->currentQueryWidget())
widget->showProgress();
}
void MainWindow::hideQueryWidgetProgressBar() const
{
if (QueryWidget *widget = _workArea->currentQueryWidget())
widget->hideProgress();
}
void MainWindow::manageConnections()
{
#if defined(Q_OS_WIN)
_trayIcon->hide(); // hide the tray icon so the main window can't be hidden behind the connections dialog
#endif
static bool checkForImported = true;
ConnectionsDialog dialog(AppRegistry::instance().settingsManager(), checkForImported, this);
int result = dialog.exec();
checkForImported = false;
// save settings and update connection menu
AppRegistry::instance().settingsManager()->save();
updateConnectionsMenu();
if (result == QDialog::Accepted) {
ConnectionSettings *selected = dialog.selectedConnection();
selected->sshSettings()->setLogLevel(1);
if (QGuiApplication::queryKeyboardModifiers().testFlag(Qt::ShiftModifier)) {
// Enable debug level of logging for SSH
if (selected->sshSettings()->enabled()) {
selected->sshSettings()->setLogLevel(100);
}
// Show log pannel
toggleLogs(true);
}
try {
_app->openServer(selected, ConnectionPrimary);
} catch(const std::exception &) {
QString message = QString("Cannot connect to MongoDB (%1)").arg(QtUtils::toQString(selected->getFullAddress()));
QMessageBox::information(this, "Error", message);
}
}
#if defined(Q_OS_WIN)
_trayIcon->show(); // show the tray icon once the connections dialog is gone
#endif
// on linux focus is lost - we need to activate main window back
activateWindow();
}
void MainWindow::toggleOrientation()
{
QueryWidget *widget = _workArea->currentQueryWidget();
if (!widget)
return;
widget->toggleOrientation();
}
void MainWindow::enterTextMode()
{
saveViewMode(Text);
QueryWidget *widget = _workArea->currentQueryWidget();
if (!widget)
return;
widget->enterTextMode();
}
void MainWindow::enterTreeMode()
{
saveViewMode(Tree);
QueryWidget *widget = _workArea->currentQueryWidget();
if (!widget)
return;
widget->enterTreeMode();
}
void MainWindow::enterTableMode()
{
saveViewMode(Table);
QueryWidget *widget = _workArea->currentQueryWidget();
if (!widget)
return;
widget->enterTableMode();
}
void MainWindow::enterCustomMode()
{
saveViewMode(Custom);
QueryWidget *widget = _workArea->currentQueryWidget();
if (!widget)
return;
widget->enterCustomMode();
}
void MainWindow::toggleAutoExpand()
{
QAction *send = qobject_cast<QAction*>(sender());
saveAutoExpand(send->isChecked());
}
void MainWindow::toggleAutoExec()
{
QAction *send = qobject_cast<QAction*>(sender());
saveAutoExec(send->isChecked());
}
void MainWindow::toggleCheckUpdates()
{
auto action = qobject_cast<QAction*>(sender());
AppRegistry::instance().settingsManager()->setCheckForUpdates(action->isChecked());
AppRegistry::instance().settingsManager()->save();
QTimer::singleShot(ONE_SECOND, this, SLOT(checkUpdates()));
}
void MainWindow::openShellTimeoutDialog()
{
changeShellTimeoutDialog();
}
void MainWindow::toggleLineNumbers()
{
QAction *send = qobject_cast<QAction*>(sender());
saveLineNumbers(send->isChecked());
}
void MainWindow::executeScript()
{
QueryWidget *widget = _workArea->currentQueryWidget();
if (!widget)
return;
widget->execute();
}
void MainWindow::stopScript()
{
QueryWidget *widget = _workArea->currentQueryWidget();
if (!widget)
return;
widget->stop();
}
void MainWindow::toggleFullScreen2()
{
if (windowState() == Qt::WindowFullScreen)
showNormal();
else
showFullScreen();
}
void MainWindow::selectNextTab()
{
_workArea->nextTab();
}
void MainWindow::selectPrevTab()
{
_workArea->previousTab();
}
void MainWindow::duplicateTab()
{
QueryWidget *widget = _workArea->currentQueryWidget();
if (!widget)
return;
widget->duplicate();
}
void MainWindow::refreshConnections()
{
QToolTip::showText(QPoint(0, 0),
QString("Refresh not working yet... : <br/> <b>Ctrl+D</b> : push Button"));
}
void MainWindow::aboutRobomongo()
{
AboutDialog dlg(this);
dlg.exec();
}
void MainWindow::openPreferences()
{
PreferencesDialog dlg(this);
dlg.exec();
}
void MainWindow::openWelcomeTab()
{
_workArea->openWelcomeTab();
}
void MainWindow::setDefaultUuidEncoding()
{
AppRegistry::instance().settingsManager()->setUuidEncoding(DefaultEncoding);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::setJavaUuidEncoding()
{
AppRegistry::instance().settingsManager()->setUuidEncoding(JavaLegacy);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::setCSharpUuidEncoding()
{
AppRegistry::instance().settingsManager()->setUuidEncoding(CSharpLegacy);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::setPythonUuidEncoding()
{
AppRegistry::instance().settingsManager()->setUuidEncoding(PythonLegacy);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::setShellAutocompletionAll()
{
AppRegistry::instance().settingsManager()->setAutocompletionMode(AutocompleteAll);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::setShellAutocompletionNoCollectionNames()
{
AppRegistry::instance().settingsManager()->setAutocompletionMode(AutocompleteNoCollectionNames);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::setShellAutocompletionNone()
{
AppRegistry::instance().settingsManager()->setAutocompletionMode(AutocompleteNone);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::setUtcTimeZone()
{
AppRegistry::instance().settingsManager()->setTimeZone(Utc);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::setLocalTimeZone()
{
AppRegistry::instance().settingsManager()->setTimeZone(LocalTime);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::setDisableConnectionShortcuts()
{
QAction *send = qobject_cast<QAction*>(sender());
AppRegistry::instance().settingsManager()->setDisableConnectionShortcuts(send->isChecked());
AppRegistry::instance().settingsManager()->save();
updateConnectionsMenu();
}
void MainWindow::setLoadMongoRcJs()
{
QAction *send = qobject_cast<QAction*>(sender());
AppRegistry::instance().settingsManager()->setLoadMongoRcJs(send->isChecked());
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::toggleLogs(bool show)
{
_logDock->setVisible(show);
}
void MainWindow::connectToServer(QAction *connectionAction)
{
QVariant data = connectionAction->data();
ConnectionSettings *ptr = data.value<ConnectionSettings *>();
try {
_app->openServer(ptr, ConnectionPrimary);
}
catch(const std::exception &) {
QString message = QString("Cannot connect to the MongoDB at %1.")
.arg(QtUtils::toQString(ptr->getFullAddress()));
QMessageBox::information(this, "Error", message);
}
}
void MainWindow::handle(ConnectionFailedEvent *event)
{
// Handle only Primary connections
if (event->connectionType != ConnectionPrimary)
return;
// Very temporary solution to prevent multiple connection error messages
// from both SshTunnelWorker and MongoWorker
static int lastServerHandle = -1;
if (event->serverHandle <= lastServerHandle)
return;
lastServerHandle = event->serverHandle;
QMessageBox::critical(this, "Error", QtUtils::toQString(event->message));
}
void MainWindow::handle(ScriptExecutingEvent *)
{
_stopAction->setDisabled(false);
_executeAction->setDisabled(true);
}
void MainWindow::handle(ScriptExecutedEvent *)
{
_stopAction->setDisabled(true);
_executeAction->setDisabled(false);
}
void MainWindow::handle(OperationFailedEvent *event)
{
std::stringstream ss;
ss << event->userFriendlyErrorMessage << std::endl << std::endl
<< "Error:" << std::endl << event->technicalErrorMessage;
QMessageBox::critical(NULL, "Operation failed", QtUtils::toQString(ss.str()));
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_F12) {
_connectButton->showMenu();
return;
}
BaseClass::keyPressEvent(event);
}
void MainWindow::closeEvent(QCloseEvent *event)
{
AppRegistry::instance().settingsManager()->setProgramExitedNormally(true);
AppRegistry::instance().settingsManager()->save();
saveWindowSettings();
#if defined(Q_OS_WIN)
if (AppRegistry::instance().settingsManager()->minimizeToTray() && !_allowExit) {
event->ignore();
hide(); // hide the window because it can be reopened with the tray icon
}
else {
if (_trayIcon->isVisible())
_trayIcon->hide();
QMainWindow::closeEvent(event);
}
#else
QMainWindow::closeEvent(event);
#endif
}
void MainWindow::hideEvent(QHideEvent *event)
{
#if defined(Q_OS_WIN)
if (_trayIcon->contextMenu()->actions().size() > 0 && isHidden()) {
_trayIcon->contextMenu()->actions().at(0)->setText("Show Robo 3T");
}
#endif
}
void MainWindow::showEvent(QShowEvent *event)
{
#if defined(Q_OS_WIN)
if (_trayIcon->contextMenu()->actions().size() > 0) {
_trayIcon->contextMenu()->actions().at(0)->setText("Minimize to Tray");
}
#endif
}
bool MainWindow::eventFilter(QObject *target, QEvent *event)
{
auto closeUpdatesBarButton = qobject_cast<QPushButton*>(target);
if (!closeUpdatesBarButton)
return false;
if (event->type() == QEvent::HoverEnter) {
closeUpdatesBarButton->setIcon(QIcon(":/robomongo/icons/close_hover_16x16_original.png"));
return true;
}
else if (event->type() == QEvent::HoverLeave) {
closeUpdatesBarButton->setIcon(QIcon(":/robomongo/icons/close_hover_16x16.png"));
return true;
}
return QWidget::eventFilter(target, event);
}
void MainWindow::resizeEvent(QResizeEvent* event)
{
QMainWindow::resizeEvent(event);
adjustUpdatesBarHeight();
}
void MainWindow::handle(QueryWidgetUpdatedEvent *event)
{
_orientationAction->setEnabled(event->numOfResults() > 1);
}
void MainWindow::createDatabaseExplorer()
{
_explorer = new ExplorerWidget(this);
AppRegistry::instance().bus()->subscribe(_explorer, ConnectingEvent::Type);
AppRegistry::instance().bus()->subscribe(_explorer, ConnectionFailedEvent::Type);
AppRegistry::instance().bus()->subscribe(_explorer, ConnectionEstablishedEvent::Type);
QDockWidget *explorerDock = new QDockWidget(tr("Database Explorer"));
explorerDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
explorerDock->setWidget(_explorer);
explorerDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable);
QWidget *titleWidget = new QWidget(this); // this lines simply remove
explorerDock->setTitleBarWidget(titleWidget); // title bar widget.
explorerDock->setVisible(true);
// Prior to v0.9 it was:
// explorerDock->setVisible(AppRegistry::instance().settingsManager()->toolbars()["explorer"].toBool());
QAction *actionExp = explorerDock->toggleViewAction();
// Adjust any parameter you want.
actionExp->setText(QString("&Explorer"));
actionExp->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_E));
actionExp->setStatusTip(QString("Press to show/hide Database Explorer panel."));
actionExp->setChecked(explorerDock->isVisible());
VERIFY(connect(actionExp, SIGNAL(triggered(bool)), this, SLOT(onExplorerVisibilityChanged(bool))));
// Install action in the menu.
_viewMenu->addAction(actionExp);
addDockWidget(Qt::LeftDockWidgetArea, explorerDock);
LogWidget *log = new LogWidget(this);
VERIFY(connect(&Logger::instance(), SIGNAL(printed(const QString&, mongo::logger::LogSeverity)),
log, SLOT(addMessage(const QString&, mongo::logger::LogSeverity))));
_logDock = new QDockWidget(tr("Logs"));
_logDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea | Qt::TopDockWidgetArea);
_logDock->setWidget(log);
_logDock->setFeatures(QDockWidget::DockWidgetClosable);
_logDock->setVisible(false);
QAction *action = _logDock->toggleViewAction();
action->setText(QString("&Logs"));
action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
//action->setStatusTip(QString("Press to show/hide Logs panel.")); //commented for now because this message hides Logs button in status bar :)
action->setChecked(_logDock->isVisible());
// Install action in the menu.
_viewMenu->addAction(action);
addDockWidget(Qt::BottomDockWidgetArea, _logDock);
}
void MainWindow::updateMenus()
{
if (!_workArea)
return;
bool isEnable = false;
if (_updateMenusAtStart)
isEnable = false;
else {
if (getWelcomeTab() && getWelcomeTab()->isVisible())
isEnable = false;
else if (_workArea->count() == 0)
isEnable = false;
else
isEnable = true;
}
_execToolBar->setEnabled(isEnable);
_openAction->setEnabled(isEnable);
_saveAction->setEnabled(isEnable);
_saveAsAction->setEnabled(isEnable);
}
void MainWindow::createTabs()
{
_workArea = new WorkAreaTabWidget(this);
AppRegistry::instance().bus()->subscribe(_workArea, OpeningShellEvent::Type);
VERIFY(connect(_workArea, SIGNAL(currentChanged(int)), this, SLOT(updateMenus())));
VERIFY(connect(_workArea, SIGNAL(currentChanged(int)), this, SLOT(on_tabChange())));
QHBoxLayout *hlayout = new QHBoxLayout;
hlayout->setContentsMargins(0, 3, 0, 0);
hlayout->addWidget(_workArea);
QWidget *window = new QWidget;
window->setLayout(hlayout);
setCentralWidget(window);
}
void MainWindow::onConnectToolbarVisibilityChanged(bool isVisible)
{
AppRegistry::instance().settingsManager()->setToolbarSettings("connect", isVisible);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::onOpenSaveToolbarVisibilityChanged(bool isVisible)
{
AppRegistry::instance().settingsManager()->setToolbarSettings("open_save", isVisible);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::onExecToolbarVisibilityChanged(bool isVisible)
{
AppRegistry::instance().settingsManager()->setToolbarSettings("exec", isVisible);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::onExplorerVisibilityChanged(bool isVisible)
{
AppRegistry::instance().settingsManager()->setToolbarSettings("explorer", isVisible);
AppRegistry::instance().settingsManager()->save();
}
void MainWindow::on_tabChange()
{
auto activeTab = dynamic_cast<QueryWidget*>(_workArea->currentWidget());
if (activeTab) {
activeTab->bringDockToFront();
}
}
void MainWindow::toggleMinimize()
{
if (isHidden()) {
show();
}
else {
hide();
}
}
void MainWindow::trayActivated(QSystemTrayIcon::ActivationReason reason)
{
if (QSystemTrayIcon::DoubleClick == reason && isHidden()) {
show();
}
}
void MainWindow::toggleMinimizeToTray()
{
QAction *send = qobject_cast<QAction*>(sender());
saveMinimizeToTraySettings(send->isChecked());
}
void MainWindow::on_focusChanged()
{
// If focus is on floating output window, make it's parent (which is a QueryWidget tab) as active tab
auto const activeDock = dynamic_cast<QueryWidget::CustomDockWidget*>(qApp->activeWindow());
if (activeDock) {
_workArea->setCurrentWidget(activeDock->getParentQueryWidget());
}
}
void MainWindow::on_networkReply(QNetworkReply* reply)
{
QString str(QUrl::fromPercentEncoding(reply->readAll()));
if (str.contains("NO-UPDATES")
|| reply->error() != QNetworkReply::NoError
|| str.isEmpty()
) {
_updateLabel->setText("");
_updateBar->setVisible(false);
return;
}
str.replace('+', ' ');
str.remove("Update,");
_updateLabel->setText(str);
_updateBar->setVisible(true);
adjustUpdatesBarHeight();
}
void MainWindow::on_closeButton_clicked()
{
_updateBar->setVisible(false);
}
void MainWindow::checkUpdates()
{
auto const& settings { AppRegistry::instance().settingsManager() };
if (!settings->checkForUpdates() || settings->disableHttpsFeatures())
return;
#ifdef _WIN32
QString const OS = "win";
#elif __APPLE__
QString const OS = "osx";
#elif __linux__
QString const OS = "linux";
#else
QString const OS = "unknown";
#endif
// Build dbVersionsConnected in following format: "3.4.3,2.6.0,..."
QString dbVersionsConnected;
for (auto const& version : settings->dbVersionsConnected())
dbVersionsConnected.append(version + ',');
if (dbVersionsConnected.endsWith(','))
dbVersionsConnected.chop(1);
// softwareId=8: Robomongo product ID
QUrl url("https://updates.3t.io/check.php?os=" + OS + "&softwareId=8&softwareVersion=" +
QString(PROJECT_VERSION) + "&licenseInfo=FREE&setup=" + settings->anonymousID() +
"&dbVersionsConnected=" + dbVersionsConnected + "¬ify=true#");
_networkAccessManager->get(QNetworkRequest(url));
}
}
| 57,688
|
C++
|
.cpp
| 1,221
| 38.677314
| 203
| 0.662053
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,695
|
AppStyle.cpp
|
Studio3T_robomongo/src/robomongo/gui/AppStyle.cpp
|
#include "robomongo/gui/AppStyle.h"
#include <QApplication>
#include <QStyleFactory>
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/settings/SettingsManager.h"
namespace Robomongo
{
const QString AppStyle::StyleName = "Native";
namespace AppStyleUtils
{
void applyStyle(const QString &styleName)
{
if (styleName == "Native") {
QApplication::setStyle(new AppStyle);
return;
}
QApplication::setStyle(QStyleFactory::create(styleName));
}
QStringList getSupportedStyles()
{
static QStringList result = QStringList() << AppStyle::StyleName << QStyleFactory::keys();
return result;
}
void initStyle()
{
AppRegistry::instance().settingsManager()->save();
QString style = AppRegistry::instance().settingsManager()->currentStyle();
applyStyle(style);
}
}
void AppStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
{
return QProxyStyle::drawControl(element, option, painter, widget);
}
void AppStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
{
#ifdef Q_OS_WIN
if (element == QStyle::PE_FrameFocusRect)
return;
#endif
return QProxyStyle::drawPrimitive(element, option, painter, widget);
}
QRect AppStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget /*= 0 */) const
{
return QProxyStyle::subElementRect(element, option, widget);
}
}
| 1,730
|
C++
|
.cpp
| 47
| 29.276596
| 134
| 0.661483
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,696
|
DocumentTextEditor.cpp
|
Studio3T_robomongo/src/robomongo/gui/dialogs/DocumentTextEditor.cpp
|
#include "robomongo/gui/dialogs/DocumentTextEditor.h"
#include <QApplication>
#include <QHBoxLayout>
#include <QPushButton>
#include <QMessageBox>
#include <QDialogButtonBox>
#include <QDesktopWidget>
#include <QSettings>
#include <Qsci/qscilexerjavascript.h>
#include <mongo/client/dbclient_base.h>
#include "robomongo/gui/editors/JSLexer.h"
#include "robomongo/gui/editors/FindFrame.h"
#include "robomongo/gui/editors/PlainJavaScriptEditor.h"
#include "robomongo/gui/widgets/workarea/IndicatorLabel.h"
#include "robomongo/gui/GuiRegistry.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/shell/bson/json.h"
namespace Robomongo
{
const QSize DocumentTextEditor::minimumSize = QSize(800, 400);
DocumentTextEditor::DocumentTextEditor(const CollectionInfo &info, const QString &json, bool readonly /* = false */, QWidget *parent) :
QDialog(parent),
_info(info),
_readonly(readonly)
{
QRect screenGeometry = QApplication::desktop()->availableGeometry();
int horizontalMargin = (int)(screenGeometry.width() * 0.35);
int verticalMargin = (int)(screenGeometry.height() * 0.20);
QSize size(screenGeometry.width() - horizontalMargin,
screenGeometry.height() - verticalMargin);
QSettings settings("3T", "Robomongo");
if (settings.contains("DocumentTextEditor/size"))
{
restoreWindowSettings();
}
else
{
resize(size);
}
setWindowFlags(Qt::Window | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint);
Indicator *collectionIndicator = new Indicator(GuiRegistry::instance().collectionIcon(), QtUtils::toQString(_info._ns.collectionName()));
Indicator *databaseIndicator = new Indicator(GuiRegistry::instance().databaseIcon(), QtUtils::toQString(_info._ns.databaseName()));
Indicator *serverIndicator = new Indicator(GuiRegistry::instance().serverIcon(), QtUtils::toQString(detail::prepareServerAddress(_info._serverAddress)));
QPushButton *validate = new QPushButton("Validate");
validate->setIcon(qApp->style()->standardIcon(QStyle::SP_MessageBoxInformation));
VERIFY(connect(validate, SIGNAL(clicked()), this, SLOT(onValidateButtonClicked())));
_queryText = new FindFrame(this);
_configureQueryText();
_queryText->sciScintilla()->setText(json);
// clear modification state after setting the content
_queryText->sciScintilla()->setModified(false);
VERIFY(connect(_queryText->sciScintilla(), SIGNAL(textChanged()), this, SLOT(onQueryTextChanged())));
QHBoxLayout *hlayout = new QHBoxLayout();
hlayout->setContentsMargins(2, 0, 5, 1);
hlayout->setSpacing(0);
hlayout->addWidget(serverIndicator, 0, Qt::AlignLeft);
hlayout->addWidget(databaseIndicator, 0, Qt::AlignLeft);
hlayout->addWidget(collectionIndicator, 0, Qt::AlignLeft);
hlayout->addStretch(1);
QDialogButtonBox *buttonBox = new QDialogButtonBox (this);
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Save);
VERIFY(connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())));
VERIFY(connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())));
QHBoxLayout *bottomlayout = new QHBoxLayout();
bottomlayout->addWidget(validate);
bottomlayout->addStretch(1);
bottomlayout->addWidget(buttonBox);
QVBoxLayout *layout = new QVBoxLayout();
// show top bar only if we have info for it
if (_info.isValid())
layout->addLayout(hlayout);
layout->addWidget(_queryText);
layout->addLayout(bottomlayout);
setLayout(layout);
if (_readonly) {
validate->hide();
buttonBox->button(QDialogButtonBox::Save)->hide();
_queryText->sciScintilla()->setReadOnly(true);
}
}
QString DocumentTextEditor::jsonText() const
{
return _queryText->sciScintilla()->text().trimmed();
}
void DocumentTextEditor::setCursorPosition(int line, int column)
{
_queryText->sciScintilla()->setCursorPosition(line, column);
}
void DocumentTextEditor::accept()
{
if (!validate())
return;
saveWindowSettings();
QDialog::accept();
}
void DocumentTextEditor::reject()
{
if (_queryText->sciScintilla()->isModified()) {
int ret = QMessageBox::warning(this, tr("Robo 3T"),
tr("The document has been modified.\n"
"Do you want to save your changes?"),
QMessageBox::Save | QMessageBox::Discard
| QMessageBox::Cancel,
QMessageBox::Save);
if (ret == QMessageBox::Save) {
this->accept();
} else if (ret == QMessageBox::Discard) {
QDialog::reject();
}
return;
}
saveWindowSettings();
QDialog::reject();
}
bool DocumentTextEditor::validate(bool silentOnSuccess /* = true */)
{
QString text = jsonText();
int len = 0;
try {
std::string textString = QtUtils::toStdString(text);
const char *json = textString.c_str();
int jsonLen = textString.length();
int offset = 0;
_obj.clear();
while (offset != jsonLen)
{
mongo::BSONObj doc = mongo::Robomongo::fromjson(json+offset, &len);
_obj.push_back(doc);
offset += len;
}
} catch (const mongo::Robomongo::ParseMsgAssertionException &ex) {
// v0.9
QString message = QtUtils::toQString(ex.reason());
int offset = ex.offset();
int line = 0, pos = 0;
_queryText->sciScintilla()->lineIndexFromPosition(offset, &line, &pos);
_queryText->sciScintilla()->setCursorPosition(line, pos);
int lineHeight = _queryText->sciScintilla()->lineLength(line);
_queryText->sciScintilla()->fillIndicatorRange(line, pos, line, lineHeight, 0);
message = QString("Unable to parse JSON:<br /> <b>%1</b>, at (%2, %3).")
.arg(message).arg(line + 1).arg(pos + 1);
QMessageBox::critical(NULL, "Parsing error", message);
_queryText->setFocus();
activateWindow();
return false;
}
if (!silentOnSuccess) {
QMessageBox::information(NULL, "Validation", "JSON is valid!");
_queryText->setFocus();
activateWindow();
}
return true;
}
void DocumentTextEditor::onQueryTextChanged()
{
_queryText->sciScintilla()->clearIndicatorRange(0, 0, _queryText->sciScintilla()->lines(), 40, 0);
}
void DocumentTextEditor::onValidateButtonClicked()
{
validate(false);
}
void DocumentTextEditor::closeEvent(QCloseEvent *event)
{
saveWindowSettings();
QWidget::closeEvent(event);
}
/*
** Configure QsciScintilla query widget
*/
void DocumentTextEditor::_configureQueryText()
{
QsciLexerJavaScript *javaScriptLexer = new JSLexer(this);
QFont font = GuiRegistry::instance().font();
javaScriptLexer->setFont(font);
_queryText->sciScintilla()->setAppropriateBraceMatching();
_queryText->sciScintilla()->setFont(font);
_queryText->sciScintilla()->setPaper(QColor(255, 0, 0, 127));
_queryText->sciScintilla()->setLexer(javaScriptLexer);
_queryText->sciScintilla()->setWrapMode((QsciScintilla::WrapMode)QsciScintilla::SC_WRAP_WORD);
_queryText->sciScintilla()->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
_queryText->sciScintilla()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
_queryText->sciScintilla()->setStyleSheet("QFrame { background-color: rgb(73, 76, 78); border: 1px solid #c7c5c4; border-radius: 4px; margin: 0px; padding: 0px;}");
}
void DocumentTextEditor::saveWindowSettings() const
{
QSettings settings("3T", "Robomongo");
settings.setValue("DocumentTextEditor/size", size());
}
void DocumentTextEditor::restoreWindowSettings()
{
QSettings settings("3T", "Robomongo");
resize(settings.value("DocumentTextEditor/size").toSize());
}
}
| 8,625
|
C++
|
.cpp
| 195
| 35.05641
| 172
| 0.634466
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,697
|
AboutDialog.cpp
|
Studio3T_robomongo/src/robomongo/gui/dialogs/AboutDialog.cpp
|
#include "robomongo/gui/dialogs/AboutDialog.h"
#include <QDate>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QLabel>
#include <QPushButton>
#include <QTabWidget>
#include <QTextBrowser>
#include <QFile>
#include <Qsci/qsciglobal.h>
#include "robomongo/gui/GuiRegistry.h"
#include "robomongo/core/utils/QtUtils.h"
namespace
{
auto const YEAR { QString::number(QDate::currentDate().year()) };
auto const MONTH { QString::number(QDate::currentDate().month()) };
const QString description {
"<h3>" PROJECT_NAME_TITLE " " PROJECT_VERSION
" (Build " BUILD_NUMBER + QString(" - ") + MONTH + "/" + YEAR + ")</h3>"
"Shell-centric MongoDB management tool.<br/>"
"<a href=\"https://" PROJECT_GITHUB_ISSUES "\">Submit</a> issues/proposals on GitHub.<br/>"
"<br/>"
"<a href=\"https://" PROJECT_DOMAIN "\">" PROJECT_DOMAIN "</a> <br/>"
"Copyright 2014-" + YEAR +
" <a href= " PROJECT_COMPANYNAME_DOMAIN " >" PROJECT_COMPANYNAME
"</a>. All rights reserved.<br/>"
"<br/>"
"The program is provided AS IS with NO WARRANTY OF ANY KIND, "
"INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A "
"PARTICULAR PURPOSE.<br/>"
"<br>"
"<b>Dependencies: <br></b>"
"Mongo-Shell " MongoDB_VERSION "<br>"
"Qt " PROJECT_QT_VERSION "<br>"
"OpenSSL " OPENSSL_VERSION "<br>"
"libssh2 " LIBSSH2_VERSION "<br>"
"QJson " QJSON_VERSION "<br>"
"QScintilla " QSCINTILLA_VERSION_STR "<br>"
"Google Test " GOOGLE_TEST_VERSION "<br>"
"ESPRIMA " ESPRIMA_VERSION "<br>"
"<br>"
"<b>Credits: <br/></b>"
"Some icons are designed by Freepik <a href=https://www.flaticon.com>www.flaticon.com</a>"
"<br/>"
};
}
namespace Robomongo
{
AboutDialog::AboutDialog(QWidget *parent)
: QDialog(parent)
{
setWindowTitle("About " PROJECT_NAME_TITLE);
//// About tab
auto aboutTab = new QWidget;
aboutTab->setWindowIcon(GuiRegistry::instance().mainWindowIcon());
aboutTab->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
auto layout = new QGridLayout(this);
layout->setSizeConstraint(QLayout::SetFixedSize);
auto copyRightLabel = new QLabel(description);
copyRightLabel->setWordWrap(true);
copyRightLabel->setOpenExternalLinks(true);
copyRightLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
QIcon icon = GuiRegistry::instance().mainWindowIcon();
QPixmap iconPixmap = icon.pixmap(128, 128);
auto logoLabel = new QLabel;
logoLabel->setPixmap(iconPixmap);
layout->addWidget(logoLabel, 0, 0, 1, 1);
layout->addWidget(copyRightLabel, 0, 1, 4, 4);
aboutTab->setLayout(layout);
//// License Agreement tab
auto licenseTab = new QWidget;
auto textBrowser = new QTextBrowser;
textBrowser->setOpenExternalLinks(true);
textBrowser->setOpenLinks(true);
QFile file(":gnu_gpl3_license.html");
if (file.open(QFile::ReadOnly | QFile::Text))
textBrowser->setText(file.readAll());
auto licenseTabLay = new QVBoxLayout;
licenseTabLay->addWidget(textBrowser);
licenseTab->setLayout(licenseTabLay);
//// Button box
auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
QPushButton *closeButton = buttonBox->button(QDialogButtonBox::Close);
buttonBox->addButton(closeButton, QDialogButtonBox::ButtonRole(QDialogButtonBox::RejectRole |
QDialogButtonBox::AcceptRole));
VERIFY(connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())));
//// Main layout
auto tabWidget = new QTabWidget;
tabWidget->addTab(aboutTab, "About");
tabWidget->addTab(licenseTab, "License Agreement");
auto mainLayout = new QVBoxLayout;
mainLayout->addWidget(tabWidget);
mainLayout->addWidget(buttonBox);
setLayout(mainLayout);
}
}
| 4,216
|
C++
|
.cpp
| 96
| 35.59375
| 102
| 0.631656
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,698
|
ConnectionsDialog.cpp
|
Studio3T_robomongo/src/robomongo/gui/dialogs/ConnectionsDialog.cpp
|
#include "robomongo/gui/dialogs/ConnectionsDialog.h"
#include <QPushButton>
#include <QHBoxLayout>
#include <QAction>
#include <QMessageBox>
#include <QLabel>
#include <QHeaderView>
#include <QDialogButtonBox>
#include <QTreeWidgetItem>
#include <QKeyEvent>
#include <QApplication>
#include <QSettings>
#include <QUuid>
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/settings/ConnectionSettings.h"
#include "robomongo/core/settings/ReplicaSetSettings.h"
#include "robomongo/core/settings/SettingsManager.h"
#include "robomongo/core/settings/SslSettings.h"
#include "robomongo/core/settings/SshSettings.h"
#include "robomongo/core/settings/CredentialSettings.h"
#include "robomongo/core/settings/SettingsManager.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/gui/GuiRegistry.h"
#include "robomongo/gui/dialogs/ConnectionDialog.h"
#include "robomongo/gui/MainWindow.h"
#include "robomongo/gui/widgets/workarea/WelcomeTab.h"
#include "robomongo/utils/common.h"
namespace Robomongo
{
/* ------------------------ ConnectionListWidgetItem ------------------------ */
/**
* @brief Simple ListWidgetItem that has several convenience methods.
*/
class ConnectionListWidgetItem : public QTreeWidgetItem
{
public:
/**
* @brief Creates ConnectionListWidgetItem with specified ConnectionSettings
*/
ConnectionListWidgetItem(ConnectionSettings *connection) { setConnection(connection); }
/**
* @brief Returns attached ConnectionSettings.
*/
ConnectionSettings *connection() { return _connection; }
/**
* @brief Attach ConnectionSettings to this item
*/
void setConnection(ConnectionSettings *connection)
{
_connection = connection;
if (_connection->isReplicaSet()) {
setIcon(0, GuiRegistry::instance().replicaSetIcon());
setText(0, QtUtils::toQString(_connection->connectionName()));
auto const repSetSize = _connection->replicaSetSettings()->members().size();
auto addrText = QString::number(repSetSize) + ((repSetSize > 1) ? " nodes" : " node");
if (!_connection->replicaSetSettings()->members().empty()) {
addrText += QString::fromStdString(" (" + _connection->replicaSetSettings()->members().front() + ")");
}
setText(1, addrText);
}
else {
setIcon(0, GuiRegistry::instance().serverIcon());
setText(0, QtUtils::toQString(_connection->connectionName()));
setText(1, QtUtils::toQString(_connection->getFullAddress()));
}
if (_connection->imported()) {
setIcon(0, GuiRegistry::instance().serverImportedIcon());
}
// Header "Attributes" (column[2])
setText(2, _connection->isReplicaSet() ? "Replica Set" : "");
if (_connection->sslSettings()->sslEnabled())
setText(2, text(2) + (text(2).isEmpty() ? "TLS" : ", TLS"));
if (!_connection->isReplicaSet() && _connection->sshSettings()->enabled())
setText(2, text(2) + (text(2).isEmpty() ? "SSH" : ", SSH"));
// Header "Auth. Database/User" (column[3])
if (_connection->hasEnabledPrimaryCredential()) {
auto primaryCredential { _connection->primaryCredential() };
auto const authString =
QString("%1 / %2").arg(QtUtils::toQString(primaryCredential->databaseName()))
.arg(QtUtils::toQString(primaryCredential->userName()));
setText(3, authString + " ");
setIcon(3, GuiRegistry::instance().keyIcon());
}
else {
setIcon(3, QIcon());
setText(3, "");
}
}
private:
ConnectionSettings *_connection;
};
/* ------------------------ ConnectionsDialog ------------------------ */
/**
* @brief Creates dialog
*/
ConnectionsDialog::ConnectionsDialog(SettingsManager *settingsManager, bool checkForImported, QWidget *parent)
: QDialog(parent), _settingsManager(settingsManager), _checkForImported(checkForImported)
{
setWindowIcon(GuiRegistry::instance().connectIcon());
setWindowTitle("MongoDB Connections");
// Remove help button (?)
setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);
QAction *addAction = new QAction("&Add...", this);
VERIFY(connect(addAction, SIGNAL(triggered()), this, SLOT(add())));
QAction *editAction = new QAction("&Edit...", this);
VERIFY(connect(editAction, SIGNAL(triggered()), this, SLOT(edit())));
QAction *cloneAction = new QAction("&Clone...", this);
VERIFY(connect(cloneAction, SIGNAL(triggered()), this, SLOT(clone())));
QAction *removeAction = new QAction("&Remove...", this);
VERIFY(connect(removeAction, SIGNAL(triggered()), this, SLOT(remove())));
_listWidget = new ConnectionsTreeWidget;
GuiRegistry::instance().setAlternatingColor(_listWidget);
#if defined(Q_OS_MAC)
_listWidget->setAttribute(Qt::WA_MacShowFocusRect, false);
#endif
_listWidget->setIndentation(5);
QStringList colums;
colums << "Name" << "Address" << "Attributes" << "Auth. Database / User";
_listWidget->setHeaderLabels(colums);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
_listWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch);
_listWidget->header()->setSectionResizeMode(1, QHeaderView::Stretch);
_listWidget->header()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
_listWidget->header()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
#endif
//_listWidget->setViewMode(QListView::ListMode);
_listWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
_listWidget->addAction(addAction);
_listWidget->addAction(editAction);
_listWidget->addAction(cloneAction);
_listWidget->addAction(removeAction);
_listWidget->setSelectionMode(QAbstractItemView::SingleSelection); // single item can be draged or droped
_listWidget->setDragEnabled(true);
_listWidget->setDragDropMode(QAbstractItemView::InternalMove);
_listWidget->setMinimumHeight(290);
_listWidget->setMinimumWidth(630);
VERIFY(connect(_listWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(accept())));
VERIFY(connect(_listWidget, SIGNAL(layoutChanged()), this, SLOT(listWidget_layoutChanged())));
QDialogButtonBox *buttonBox = new QDialogButtonBox(this);
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Save);
buttonBox->button(QDialogButtonBox::Save)->setIcon(GuiRegistry::instance().serverIcon());
buttonBox->button(QDialogButtonBox::Save)->setText("C&onnect");
VERIFY(connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())));
VERIFY(connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())));
QHBoxLayout *bottomLayout = new QHBoxLayout;
// Information message is shown when connection
// settings are imported from previous version of Robomongo
int importedCount = _settingsManager->importedConnectionsCount();
if (_checkForImported && importedCount > 0) {
QIcon importIcon = qApp->style()->standardIcon(QStyle::SP_MessageBoxInformation);
QPixmap importPixmap = importIcon.pixmap(20, 20);
QLabel *importLabelIcon = new QLabel;
importLabelIcon->setPixmap(importPixmap);
QString importedRecords = importedCount > 1 ? "records" : "record";
QLabel *importLabelMessage = new QLabel(QString(
"<span style='color: #777777;'>"
"Connection settings have been imported (%1 %2)"
"</span>").arg(importedCount).arg(importedRecords));
bottomLayout->addWidget(importLabelIcon, 0, Qt::AlignLeft);
bottomLayout->addWidget(importLabelMessage, 1, Qt::AlignLeft);
}
bottomLayout->addWidget(buttonBox, 0, Qt::AlignRight);
QLabel *intro = new QLabel(QString(
"<a style='color: %1' href='create'>Create</a>, "
"<a style='color: %1' href='edit'>edit</a>, "
"<a style='color: %1' href='remove'>remove</a>, "
"<a style='color: %1' href='clone'>clone</a> "
"or reorder connections via drag'n'drop.").arg("#106CD6"));
intro->setWordWrap(true);
VERIFY(connect(intro, SIGNAL(linkActivated(QString)), this, SLOT(linkActivated(QString))));
QVBoxLayout *firstColumnLayout = new QVBoxLayout;
firstColumnLayout->addWidget(intro);
firstColumnLayout->addWidget(_listWidget, 1);
firstColumnLayout->addLayout(bottomLayout);
QHBoxLayout *mainLayout = new QHBoxLayout(this);
mainLayout->addLayout(firstColumnLayout, 1);
// Populate list with connections
std::vector<ConnectionSettings*> connectionSettings = _settingsManager->connections();
for (auto const& connSetting : connectionSettings) {
ConnectionSettings *connectionModel { connSetting };
add(connectionModel);
}
// Highlight last item
if (_listWidget->topLevelItemCount() > 0)
_listWidget->setCurrentItem(_listWidget->topLevelItem(_listWidget->topLevelItemCount()-1));
_listWidget->setFocus();
resize(getSetting("ConnectionsDialog/size").toSize());
}
/**
* @brief This function is called when user clicks on "Connect" button.
*/
void ConnectionsDialog::accept()
{
auto currentItem = dynamic_cast<ConnectionListWidgetItem*>(_listWidget->currentItem());
// Do nothing if no item selected
if (!currentItem)
return;
_selectedConnection = currentItem->connection();
QDialog::accept();
}
void ConnectionsDialog::reject()
{
QDialog::reject();
}
ConnectionsDialog::~ConnectionsDialog()
{
saveSetting("ConnectionsDialog/size", size());
}
void ConnectionsDialog::linkActivated(const QString &link)
{
if (link == "create")
add();
else if (link == "edit")
edit();
else if (link == "remove")
remove();
else if (link == "clone")
clone();
}
/**
* @brief Initiate 'add' action, usually when user clicked on Add button
*/
void ConnectionsDialog::add()
{
auto newConnSettings = std::unique_ptr<ConnectionSettings>(new ConnectionSettings(false));
ConnectionDialog editDialog(newConnSettings.get(), this);
// Do nothing if not accepted
if (editDialog.exec() != QDialog::Accepted) {
return;
}
add(newConnSettings.get());
_settingsManager->addConnection(newConnSettings.release());
_listWidget->setFocus();
}
/**
* @brief Initiate 'edit' action, usually when user clicked on Edit button
*/
void ConnectionsDialog::edit()
{
auto currentItem = dynamic_cast<ConnectionListWidgetItem*>(_listWidget->currentItem());
// Do nothing if no item selected
if (!currentItem)
return;
auto connection = currentItem->connection();
boost::scoped_ptr<ConnectionSettings> clonedConnection(connection->clone());
ConnectionDialog editDialog(clonedConnection.get(), this);
// Do nothing if not accepted
if (editDialog.exec() != QDialog::Accepted) {
// on linux focus is lost - we need to activate connections dialog
activateWindow();
return;
}
connection->apply(editDialog.connection());
// on linux focus is lost - we need to activate connections dialog
activateWindow();
int size = _connectionItems.size();
for (int i = 0; i<size; ++i)
{
ConnectionListWidgetItem *item = _connectionItems[i];
if (_connectionItems[i]->connection() == connection) {
item->setConnection(connection);
break;
}
}
}
/**
* @brief Initiate 'remove' action, usually when user clicked on Remove button
*/
void ConnectionsDialog::remove()
{
auto currentItem = dynamic_cast<ConnectionListWidgetItem*>(_listWidget->currentItem());
// Do nothing if no item selected
if (!currentItem)
return;
ConnectionSettings *connSettings = currentItem->connection();
// Ask user
QString const question { "Are you sure you want to delete \"%1\" connection?" };
int const answer = QMessageBox::question(this,
"Connections",
question.arg(QtUtils::toQString(connSettings->getReadableName())),
QMessageBox::Yes, QMessageBox::No, QMessageBox::NoButton);
if (answer != QMessageBox::Yes)
return;
/* Temporarily disabling Recent Connections feature
_settingsManager->deleteRecentConnection(connSettings);
// Remove from WelcomeTab
for (auto widget : QApplication::topLevelWidgets()) {
if (auto mainWin = dynamic_cast<MainWindow*>(widget))
mainWin->getWelcomeTab()->removeRecentConnectionItem(connSettings);
}
*/
_settingsManager->removeConnection(connSettings);
delete currentItem;
}
void ConnectionsDialog::clone()
{
auto currentItem = dynamic_cast<ConnectionListWidgetItem*>(_listWidget->currentItem());
// Do nothing if no item selected
if (!currentItem)
return;
// Clone connection
ConnectionSettings *connection = currentItem->connection()->clone();
// This is a special clone which will actually be a new connection and must have unique UUID
connection->setUuid(QUuid::createUuid().toString());
std::string newConnectionName = "Copy of " + connection->connectionName();
connection->setConnectionName(newConnectionName);
connection->replicaSetSettings()->setCachedSetName("");
ConnectionDialog editDialog(connection, this);
// Cleanup newly created connection and return, if not accepted.
if (editDialog.exec() != QDialog::Accepted) {
delete connection;
return;
}
// Now connection will be owned by SettingsManager
_settingsManager->addConnection(connection);
add(connection);
}
/**
* @brief Handles ListWidget layoutChanged() signal
*/
void ConnectionsDialog::listWidget_layoutChanged()
{
// Make childrens toplevel again. This is a bad, but quickiest item reordering
// implementation.
for (int i = 0; i < _listWidget->topLevelItemCount(); i++)
{
auto item = (ConnectionListWidgetItem *) _listWidget->topLevelItem(i);
if (item->childCount() > 0) {
auto childItem = (ConnectionListWidgetItem *) item->child(0);
item->removeChild(childItem);
_listWidget->insertTopLevelItem(++i, childItem);
_listWidget->setCurrentItem(childItem);
break;
}
}
SettingsManager::ConnectionSettingsContainerType items;
for (int i = 0; i < _listWidget->topLevelItemCount(); i++)
{
auto item = (ConnectionListWidgetItem *) _listWidget->topLevelItem(i);
items.push_back(item->connection());
}
_settingsManager->reorderConnections(items);
}
/**
* @brief Add connection to the list widget
*/
void ConnectionsDialog::add(ConnectionSettings *connection)
{
auto item = new ConnectionListWidgetItem(connection);
_listWidget->addTopLevelItem(item);
_listWidget->setCurrentItem(item);
_connectionItems.push_back(item);
}
void ConnectionsDialog::keyPressEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_E && (event->modifiers() & Qt::ControlModifier)) {
edit();
return;
}
if (event->key() == Qt::Key_W && (event->modifiers() & Qt::ControlModifier)) {
close();
return;
}
// Shift + Return also accepts connection (this shortcut is handled
// to support DEBUG level logging)
if (event->key() == Qt::Key_Return && (event->modifiers() & Qt::ShiftModifier)) {
accept();
return;
}
QDialog::keyPressEvent(event);
}
ConnectionsTreeWidget::ConnectionsTreeWidget()
{
setDragDropMode(QAbstractItemView::InternalMove);
setSelectionMode(QAbstractItemView::SingleSelection);
setDragEnabled(true);
setAcceptDrops(true);
}
void ConnectionsTreeWidget::dropEvent(QDropEvent *event)
{
#ifdef __APPLE__
if(_dragDropCount > 0)
return;
#endif
QTreeWidget::dropEvent(event);
emit layoutChanged();
#ifdef __APPLE__
++_dragDropCount;
#endif
}
}
| 17,547
|
C++
|
.cpp
| 391
| 35.567775
| 122
| 0.629406
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,699
|
EulaDialog.cpp
|
Studio3T_robomongo/src/robomongo/gui/dialogs/EulaDialog.cpp
|
#include "robomongo/gui/dialogs/EulaDialog.h"
#include <QApplication>
#include <QHBoxLayout>
#include <QPushButton>
#include <QMessageBox>
#include <QDialogButtonBox>
#include <QFile>
#include <QSettings>
#include <QLabel>
#include <QTextBrowser>
#include <QLineEdit>
#include <QRadioButton>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrlQuery>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDesktopWidget>
#include <QTimeZone>
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/settings/SettingsManager.h"
#include "robomongo/core/utils/Logger.h"
#include "robomongo/core/utils/QtUtils.h"
namespace Robomongo
{
EulaDialog::EulaDialog(bool showFormPage, QWidget *parent)
: QWizard(parent), _showFormPage(showFormPage)
{
setWindowTitle("EULA");
//// First page
auto firstPage = new QWizardPage;
auto agreeButton = new QRadioButton("I agree");
VERIFY(connect(agreeButton, SIGNAL(clicked()),
this, SLOT(on_agreeButton_clicked())));
auto notAgreeButton = new QRadioButton("I don't agree");
notAgreeButton->setChecked(true);
VERIFY(connect(notAgreeButton, SIGNAL(clicked()),
this, SLOT(on_notAgreeButton_clicked())));
auto radioButtonsLay = new QHBoxLayout;
radioButtonsLay->setAlignment(Qt::AlignHCenter);
radioButtonsLay->setSpacing(30);
radioButtonsLay->addWidget(agreeButton);
radioButtonsLay->addWidget(notAgreeButton);
auto textBrowser = new QTextBrowser;
textBrowser->setOpenExternalLinks(true);
textBrowser->setOpenLinks(true);
QFile file(":gnu_gpl3_license.html");
if (file.open(QFile::ReadOnly | QFile::Text))
textBrowser->setText(file.readAll());
auto hline = new QFrame();
hline->setFrameShape(QFrame::HLine);
hline->setFrameShadow(QFrame::Sunken);
auto mainLayout1 = new QVBoxLayout();
mainLayout1->addWidget(new QLabel("<h3>End-User License Agreement</h3>"));
mainLayout1->addWidget(new QLabel(""));
mainLayout1->addWidget(textBrowser);
mainLayout1->addWidget(new QLabel(""));
mainLayout1->addLayout(radioButtonsLay, Qt::AlignCenter);
mainLayout1->addWidget(new QLabel(""));
mainLayout1->addWidget(hline);
firstPage->setLayout(mainLayout1);
//// Second page
auto secondPage = new QWizardPage;
auto nameLabel = new QLabel("<b>First Name:</b>");
_nameEdit = new QLineEdit;
auto lastNameLabel = new QLabel("<b>Last Name:</b>");
_lastNameEdit = new QLineEdit;
auto emailLabel = new QLabel("<b>Email:</b>");
_emailEdit = new QLineEdit;
_phone = new QLineEdit;
_company = new QLineEdit;
auto buttomLabel = new QLabel("By submitting this form I agree to 3T Software Labs "
"<a href='https://studio3t.com/privacy-policy'>Privacy Policy</a>.");
buttomLabel->setOpenExternalLinks(true);
auto bodyLabel = new QLabel("\nShare your email address with us and we'll keep you "
"up-to-date with updates from us and new features as they come out.");
bodyLabel->setWordWrap(true);
auto mainLayout2 = new QGridLayout();
mainLayout2->addWidget(new QLabel, 0, 0, 1, 2);
mainLayout2->addWidget(new QLabel("<h3>Thank you for choosing Robo 3T!</h3>"), 1, 0, 1, 2);
mainLayout2->addWidget(bodyLabel, 2, 0 , 1, 2);
mainLayout2->addWidget(new QLabel, 3, 0, 1, 2);
mainLayout2->addWidget(nameLabel, 4, 0);
mainLayout2->addWidget(_nameEdit, 4, 1);
mainLayout2->addWidget(lastNameLabel, 5, 0);
mainLayout2->addWidget(_lastNameEdit, 5, 1);
mainLayout2->addWidget(emailLabel, 6, 0);
mainLayout2->addWidget(_emailEdit, 6, 1);
mainLayout2->addWidget(new QLabel("<b>Phone: </b>"), 7, 0);
mainLayout2->addWidget(_phone, 7, 1);
mainLayout2->addWidget(new QLabel("<b>Company:</b>"), 8, 0);
mainLayout2->addWidget(_company, 8, 1);
mainLayout2->addWidget(new QLabel, 9, 0, 1, 2);
mainLayout2->addWidget(buttomLabel, 10, 0, 1, 2);
secondPage->setLayout(mainLayout2);
addPage(firstPage);
if(_showFormPage)
addPage(secondPage);
//// Buttons
setButtonText(QWizard::CustomButton1, tr("Back"));
setButtonText(QWizard::CustomButton2, tr("Next"));
setButtonText(QWizard::CustomButton3, tr("Finish"));
VERIFY(connect(button(QWizard::CustomButton1), SIGNAL(clicked()), this, SLOT(on_back_clicked())));
VERIFY(connect(button(QWizard::CustomButton2), SIGNAL(clicked()), this, SLOT(on_next_clicked())));
VERIFY(connect(button(QWizard::CustomButton3), SIGNAL(clicked()), this, SLOT(on_finish_clicked())));
setButtonLayout(QList<WizardButton>{ QWizard::Stretch, QWizard::CustomButton1, QWizard::CustomButton2,
QWizard::CancelButton, QWizard::CustomButton3});
button(QWizard::CustomButton1)->setDisabled(true);
button(QWizard::CustomButton2)->setDisabled(true);
button(QWizard::CustomButton2)->setHidden(!_showFormPage);
button(QWizard::CustomButton3)->setDisabled(true);
setWizardStyle(QWizard::ModernStyle);
QSettings const settings("3T", "Robomongo");
if (settings.contains("EulaDialog/size")) {
restoreWindowSettings();
}
else {
auto const desktop = QApplication::desktop();
auto const& mainScreenSize = desktop->availableGeometry(desktop->primaryScreen()).size();
resize(mainScreenSize.width()*0.5, mainScreenSize.height()*0.6);
}
}
void EulaDialog::accept()
{
saveWindowSettings();
if(_showFormPage)
postUserData();
QDialog::accept();
}
void EulaDialog::reject()
{
saveWindowSettings();
QDialog::reject();
}
void EulaDialog::closeEvent(QCloseEvent *event)
{
saveWindowSettings();
QWidget::closeEvent(event);
}
void EulaDialog::on_agreeButton_clicked()
{
if(_showFormPage)
button(QWizard::CustomButton2)->setEnabled(true);
else
button(QWizard::CustomButton3)->setEnabled(true);
}
void EulaDialog::on_notAgreeButton_clicked()
{
if (_showFormPage)
button(QWizard::CustomButton2)->setEnabled(false);
else
button(QWizard::CustomButton3)->setEnabled(false);
}
void EulaDialog::on_next_clicked()
{
next();
button(QWizard::CustomButton1)->setEnabled(true);
button(QWizard::CustomButton2)->setEnabled(false);
button(QWizard::CustomButton3)->setEnabled(true);
}
void EulaDialog::on_back_clicked()
{
back();
button(QWizard::CustomButton1)->setEnabled(false);
button(QWizard::CustomButton2)->setEnabled(true);
button(QWizard::CustomButton3)->setEnabled(false);
}
void EulaDialog::on_finish_clicked()
{
accept();
}
void EulaDialog::postUserData() const
{
if (_emailEdit->text().isEmpty() ||
AppRegistry::instance().settingsManager()->disableHttpsFeatures()
)
return;
// OS string
#ifdef _WIN32
QString const OS = "win";
#elif __APPLE__
QString const OS = "osx";
#elif __linux__
QString const OS = "linux";
#else
QString const OS = "unknown";
#endif
// Timezone string
QDateTime now = QDateTime::currentDateTime();
now.setOffsetFromUtc(now.offsetFromUtc());
QString dateAndTimezone = now.toString(Qt::ISODate);
QString const date = QDateTime::currentDateTime().toString(Qt::ISODate);
QString const timezone = "UTC" + dateAndTimezone.remove(date);
// Build post data and send
QJsonObject jsonStr {
{ "email", _emailEdit->text() },
{ "firstName", _nameEdit->text() },
{ "lastName", _lastNameEdit->text() },
{ "phone", _phone->text() },
{ "company", _company->text() },
{ "os", OS },
{ "timezone", timezone }
};
QJsonDocument jsonDoc(jsonStr);
QUrlQuery postData(jsonDoc.toJson());
postData = QUrlQuery("rd=" + postData.toString(QUrl::FullyEncoded).toUtf8());
QNetworkRequest request(QUrl("https://rm-form.3t.io/"));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
auto networkManager = new QNetworkAccessManager;
_reply = networkManager->post(request, postData.toString(QUrl::FullyEncoded).toUtf8());
debugLog("EulaDialog: Form posted");
}
void EulaDialog::saveWindowSettings() const
{
QSettings settings("3T", "Robomongo");
settings.setValue("EulaDialog/size", size());
}
void EulaDialog::restoreWindowSettings()
{
QSettings settings("3T", "Robomongo");
resize(settings.value("EulaDialog/size").toSize());
}
}
| 9,542
|
C++
|
.cpp
| 224
| 34.522321
| 110
| 0.624002
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,700
|
ConnectionAuthTab.cpp
|
Studio3T_robomongo/src/robomongo/gui/dialogs/ConnectionAuthTab.cpp
|
#include "robomongo/gui/dialogs/ConnectionAuthTab.h"
#include <QGridLayout>
#include <QLineEdit>
#include <QLabel>
#include <QCheckBox>
#include <QPushButton>
#include <QComboBox>
#include "robomongo/core/settings/ConnectionSettings.h"
#include "robomongo/core/settings/CredentialSettings.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/gui/GuiRegistry.h"
namespace Robomongo
{
ConnectionAuthTab::ConnectionAuthTab(ConnectionSettings *settings) :
_settings(settings)
{
_useAuth = new QCheckBox("Perform authentication");
_useAuth->setStyleSheet("margin-bottom: 7px");
VERIFY(connect(_useAuth, SIGNAL(toggled(bool)), this, SLOT(authChecked(bool))));
_databaseNameDescriptionLabel = new QLabel(
"<nobr>The admin database is unique in MongoDB.</nobr> Users with normal access "
"to the admin database have read and write access to <b>all "
"databases</b>."
);
_databaseNameDescriptionLabel->setWordWrap(true);
_userName = new QLineEdit();
_userNameLabel = new QLabel("User Name");
_mechanismLabel = new QLabel("Auth Mechanism");
_userPassword = new QLineEdit();
_userPassword->setEchoMode(QLineEdit::Password);
_userPasswordLabel = new QLabel("Password");
_databaseName = new QLineEdit("admin");
_databaseNameLabel = new QLabel("Database");
_mechanismComboBox = new QComboBox;
_mechanismComboBox->addItem("SCRAM-SHA-1");
_mechanismComboBox->addItem("SCRAM-SHA-256");
_mechanismComboBox->addItem("MONGODB-CR");
_manuallyVisibleDbs = new QLineEdit;
_manuallyVisibleDbs->setPlaceholderText("Comma-separated e.g. products, users");
_manuallyVisibleDbsLabel = new QLabel("Databases");
_manuallyVisibleDbsInfo = new QLabel(
"Some MongoDB users might not have the permission to get the list of"
" database names (<b>listDatabases</b> command). For this case, manually add"
" the name of the database(s) that this user has access to."
);
_manuallyVisibleDbsInfo->setWordWrap(true);
_useManuallyVisibleDbs = new QCheckBox("Manually specify visible databases");
_useManuallyVisibleDbs->setStyleSheet("margin-bottom: 7px");
VERIFY(connect(_useManuallyVisibleDbs, SIGNAL(toggled(bool)),
this, SLOT(useManuallyVisibleDbsChecked(bool))));
_echoModeButton = new QPushButton;
_echoModeButton->setIcon(GuiRegistry::instance().hideIcon());
#ifdef Q_OS_MAC
_echoModeButton->setMaximumWidth(50);
#else
_echoModeButton->setMinimumWidth(50);
#endif
// Attempt to fix the issue for Windows High DPI button height is slightly taller than other widgets
#ifdef Q_OS_WIN
_echoModeButton->setMaximumHeight(HighDpiConstants::WIN_HIGH_DPI_BUTTON_HEIGHT);
#endif
VERIFY(connect(_echoModeButton, SIGNAL(clicked()), this, SLOT(toggleEchoMode())));
_useAuth->setChecked(_settings->hasEnabledPrimaryCredential());
authChecked(_settings->hasEnabledPrimaryCredential());
if (_settings->credentialCount() > 0) {
CredentialSettings *primaryCredential = _settings->primaryCredential();
_userName->setText(QtUtils::toQString(primaryCredential->userName()));
_userPassword->setText(QtUtils::toQString(primaryCredential->userPassword()));
_databaseName->setText(QtUtils::toQString(primaryCredential->databaseName()));
_mechanismComboBox->setCurrentText(QtUtils::toQString(primaryCredential->mechanism()));
_useManuallyVisibleDbs->setChecked(_settings->primaryCredential()->useManuallyVisibleDbs());
_manuallyVisibleDbs->setText(QtUtils::toQString(primaryCredential->manuallyVisibleDbs()));
}
useManuallyVisibleDbsChecked(_useManuallyVisibleDbs->isChecked());
auto horline = new QFrame;
horline->setFrameShape(QFrame::HLine);
horline->setFrameShadow(QFrame::Sunken);
auto verSpacer { new QSpacerItem(0, 80, QSizePolicy::Minimum, QSizePolicy::Expanding) };
auto authLayout = new QGridLayout;
authLayout->addWidget(_useAuth, 0, 0, 1, 3);
authLayout->addWidget(_databaseNameLabel, 1, 0);
authLayout->addWidget(_databaseName, 1, 1, 1, 2);
authLayout->addWidget(_databaseNameDescriptionLabel, 2, 1, 1, 2);
authLayout->addWidget(new QLabel, 3, 0);
authLayout->addWidget(_userNameLabel, 4, 0);
authLayout->addWidget(_userName, 4, 1, 1, 2);
authLayout->addWidget(_userPasswordLabel, 5, 0);
authLayout->addWidget(_userPassword, 5, 1);
authLayout->addWidget(_echoModeButton, 5, 2);
authLayout->addWidget(_mechanismLabel, 6, 0);
authLayout->addWidget(_mechanismComboBox, 6, 1, 1, 2);
authLayout->addWidget(new QLabel, 7, 0);
authLayout->addWidget(horline, 8, 0, 1, 3);
authLayout->addWidget(_useManuallyVisibleDbs, 9, 0, 1, 3);
authLayout->addWidget(_manuallyVisibleDbsLabel, 10, 0);
authLayout->addWidget(_manuallyVisibleDbs, 10, 1, 1, 2);
authLayout->addWidget(_manuallyVisibleDbsInfo, 11, 1, 1, 2);
authLayout->addItem(verSpacer, 12, 0, 1, 3);
authLayout->setAlignment(Qt::AlignTop);
setLayout(authLayout);
}
void ConnectionAuthTab::accept()
{
_settings->clearCredentials();
// If all fields is empty - do nothing
if (_userName->text().isEmpty() &&
_userPassword->text().isEmpty() &&
_databaseName->text().isEmpty())
return;
auto credential { new CredentialSettings };
credential->setEnabled(_useAuth->isChecked());
credential->setUserName(QtUtils::toStdString(_userName->text()));
credential->setUserPassword(QtUtils::toStdString(_userPassword->text()));
credential->setDatabaseName(QtUtils::toStdString(_databaseName->text()));
credential->setMechanism(QtUtils::toStdString(_mechanismComboBox->currentText()));
credential->setUseManuallyVisibleDbs(
_useManuallyVisibleDbs->isChecked() && !_manuallyVisibleDbs->text().isEmpty()
);
credential->setManuallyVisibleDbs(
_manuallyVisibleDbs->text().simplified().replace(' ', "").toStdString()
);
_settings->addCredential(credential);
}
void ConnectionAuthTab::setAuthTab(
QString const db,
QString const username,
QString const pwd,
AuthMechanism authMech
) {
_useAuth->setChecked(true);
_databaseName->setText(db);
_userName->setText(username);
_userPassword->setText(pwd);
_mechanismComboBox->setCurrentIndex(int(authMech));
}
void ConnectionAuthTab::clearTab()
{
_useAuth->setChecked(false);
_databaseName->clear();
_userName->clear();
_userPassword->clear();
_mechanismComboBox->setCurrentIndex(0);
_useManuallyVisibleDbs->setChecked(false);
_manuallyVisibleDbs->clear();
}
void ConnectionAuthTab::toggleEchoMode()
{
bool isPassword = _userPassword->echoMode() == QLineEdit::Password;
_userPassword->setEchoMode(isPassword ? QLineEdit::Normal: QLineEdit::Password);
_echoModeButton->setIcon(isPassword ? GuiRegistry::instance().showIcon() : GuiRegistry::instance().hideIcon());
}
void ConnectionAuthTab::authChecked(bool checked)
{
_databaseName->setEnabled(checked);
_databaseNameLabel->setEnabled(checked);
_databaseNameDescriptionLabel->setEnabled(checked);
_userName->setEnabled(checked);
_userNameLabel->setEnabled(checked);
_userPassword->setEnabled(checked);
_userPasswordLabel->setEnabled(checked);
_echoModeButton->setEnabled(checked);
_mechanismLabel->setEnabled(checked);
_mechanismComboBox->setEnabled(checked);
_useManuallyVisibleDbs->setEnabled(checked);
_manuallyVisibleDbs->setEnabled(checked);
_manuallyVisibleDbsLabel->setEnabled(checked);
_manuallyVisibleDbsInfo->setEnabled(checked);
if (checked)
_databaseName->setFocus();
}
void ConnectionAuthTab::useManuallyVisibleDbsChecked(bool checked)
{
_manuallyVisibleDbs->setVisible(checked);
_manuallyVisibleDbsLabel->setVisible(checked);
_manuallyVisibleDbsInfo->setVisible(checked);
}
}
| 8,868
|
C++
|
.cpp
| 177
| 41.514124
| 119
| 0.655802
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
14,701
|
ConnectionAdvancedTab.cpp
|
Studio3T_robomongo/src/robomongo/gui/dialogs/ConnectionAdvancedTab.cpp
|
#include "robomongo/gui/dialogs/ConnectionAdvancedTab.h"
#include <QLabel>
#include <QGridLayout>
#include <QLineEdit>
/* --- Disabling unfinished export URI connection string feature
#include <QPushButton>
#include <QMessageBox>
#include <QClipboard>
#include <QApplication>
#include <QCheckBox>
#include <QToolTip>
*/
#include <mongo/client/mongo_uri.h>
#include "robomongo/core/settings/ConnectionSettings.h"
#include "robomongo/core/utils/QtUtils.h"
/* --- Disabling unfinished export URI connection string feature
#include "robomongo/core/settings/CredentialSettings.h"
#include "robomongo/core/settings/ReplicaSetSettings.h"
#include "robomongo/core/settings/SslSettings.h"
#include "robomongo/gui/utils/GuiConstants.h"
*/
namespace Robomongo
{
ConnectionAdvancedTab::ConnectionAdvancedTab(ConnectionSettings *settings) :
_settings(settings)
{
/* --- Disabling unfinished export URI connection string feature
_uriString = new QLineEdit;
_uriString->setReadOnly(true);
_includePasswordCheckBox = new QCheckBox("Include passwords");
VERIFY(connect(_includePasswordCheckBox, SIGNAL(toggled(bool)),
this, SLOT(on_includePasswordsCheckBox_toggle(bool))));
auto generateButton = new QPushButton("Generate");
generateButton->setFixedWidth(70);
generateButton->setMaximumHeight(HighDpiConstants::WIN_HIGH_DPI_BUTTON_HEIGHT);
VERIFY(connect(generateButton, SIGNAL(clicked()), this, SLOT(on_generateButton_clicked())));
_copyButton = new QPushButton("Copy");
_copyButton->setFixedWidth(50);
_copyButton->setMaximumHeight(HighDpiConstants::WIN_HIGH_DPI_BUTTON_HEIGHT);
VERIFY(connect(_copyButton, SIGNAL(clicked()), this, SLOT(on_copyButton_clicked())));
auto hlay = new QHBoxLayout;
hlay->addWidget(_includePasswordCheckBox);
hlay->addWidget(generateButton, Qt::AlignLeft);
hlay->addWidget(_copyButton, Qt::AlignLeft);
*/
auto defaultDatabaseDescriptionLabel = new QLabel(
"Database, that will be default (<code>db</code> shell variable will point to this database). "
"By default, default database will be the one you authenticate on, or <code>test</code> otherwise. "
"Leave this field empty, if you want default behavior.");
defaultDatabaseDescriptionLabel->setWordWrap(true);
defaultDatabaseDescriptionLabel->setContentsMargins(0, -2, 0, 20);
_defaultDatabaseName = new QLineEdit(QtUtils::toQString(_settings->defaultDatabase()));
auto defaultDbLabel = new QLabel("Default Database:");
#ifdef _WIN32
defaultDbLabel->setMaximumWidth(100); // Win
#elif __APPLE__
defaultDbLabel->setMaximumWidth(110); // MacOS
#else
defaultDbLabel->setMaximumWidth(140); // Linux
#endif
auto mainLayout = new QGridLayout;
mainLayout->setAlignment(Qt::AlignTop);
mainLayout->addWidget(defaultDbLabel, 1, 0);
mainLayout->addWidget(_defaultDatabaseName, 1, 1, 1, 2);
mainLayout->addWidget(defaultDatabaseDescriptionLabel, 2, 1, 1, 2);
/* --- Disabling unfinished export URI connection string feature
mainLayout->addWidget(new QLabel{ "URI Connection String:" }, 3, 0);
mainLayout->addWidget(_uriString, 3, 1);
mainLayout->addLayout(hlay, 4, 1);
*/
setLayout(mainLayout);
}
void ConnectionAdvancedTab::accept()
{
_settings->setDefaultDatabase(QtUtils::toStdString(_defaultDatabaseName->text()));
}
void ConnectionAdvancedTab::setDefaultDb(const QString& defaultDb)
{
_defaultDatabaseName->setText(defaultDb);
}
/* --- Disabling unfinished export URI connection string feature
void ConnectionAdvancedTab::on_generateButton_clicked()
{
if (_settings->isReplicaSet()) {
// todo:
// handle set name will be empty initially. It will be available(cached) after first
// successful connection.
std::string connStr = { "mongodb://" };
// todo: which credential to use if there are more than one?
if (_settings->hasEnabledPrimaryCredential() && !_settings->credentials().isEmpty()) {
connStr.append(_settings->primaryCredential()->userName() + ":");
connStr.append(_includePasswordCheckBox->isChecked() ?
_settings->primaryCredential()->userPassword() : "PASSWORD");
connStr.append("@");
}
for (auto const& member : _settings->replicaSetSettings()->membersToHostAndPort()) {
connStr.append(member.toString() + ",");
}
connStr.pop_back(); // delete last ","
connStr.append("/admin?");
connStr.append("replicaSet=" + _settings->replicaSetSettings()->setName());
if (_settings->sslSettings()->sslEnabled())
connStr.append("&ssl=true");
if (_settings->hasEnabledPrimaryCredential() && !_settings->credentials().isEmpty())
connStr.append("&authSource=" + _settings->primaryCredential()->databaseName());
// todo: validate connStr
_uriString->setText(QString::fromStdString(connStr));
_uriString->setCursorPosition(QTextCursor::Start);
}
else { // standalone server
mongo::HostAndPort server = _settings->hostAndPort();
mongo::ConnectionString connStr{ server };
auto str1 = connStr.toString();
auto uriWithStatus = mongo::StatusWith<mongo::MongoURI>(mongo::MongoURI::parse(connStr.toString()));
auto str2 = uriWithStatus.getValue().toString();
_uriString->setText(QString::fromStdString("mongodb://" + str1 + "/admin"));
_uriString->setCursorPosition(QTextCursor::Start);
}
}
void ConnectionAdvancedTab::on_copyButton_clicked()
{
if (_uriString->text().isEmpty())
return;
QClipboard *clipboard = qApp->clipboard();
clipboard->setText(_uriString->text());
auto posUnderGenerateButton = QPoint(_copyButton->pos().x()-100, _copyButton->y()+20);
QToolTip::showText(mapToGlobal(posUnderGenerateButton), "Copied into clipboard", nullptr, QRect(), 2000);
}
void ConnectionAdvancedTab::on_includePasswordsCheckBox_toggle(bool checked)
{
if (_uriString->text().isEmpty())
return;
on_generateButton_clicked();
}
*/
}
| 6,687
|
C++
|
.cpp
| 136
| 40.860294
| 113
| 0.653887
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
14,702
|
PreferencesDialog.cpp
|
Studio3T_robomongo/src/robomongo/gui/dialogs/PreferencesDialog.cpp
|
#include "robomongo/gui/dialogs/PreferencesDialog.h"
#include <QDialogButtonBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QComboBox>
#include <QPushButton>
#include <QCheckBox>
#include "robomongo/gui/GuiRegistry.h"
#include "robomongo/gui/AppStyle.h"
#include "robomongo/gui/utils/ComboBoxUtils.h"
#include "robomongo/core/utils/QtUtils.h"
#include "robomongo/core/AppRegistry.h"
#include "robomongo/core/settings/SettingsManager.h"
namespace Robomongo
{
PreferencesDialog::PreferencesDialog(QWidget *parent)
: BaseClass(parent)
{
setWindowIcon(GuiRegistry::instance().mainWindowIcon());
setWindowTitle("Preferences " PROJECT_NAME_TITLE);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setFixedSize(height, width);
QVBoxLayout *layout = new QVBoxLayout(this);
QHBoxLayout *defLayout = new QHBoxLayout(this);
QLabel *defDisplayModeLabel = new QLabel("Default display mode:");
defLayout->addWidget(defDisplayModeLabel);
_defDisplayModeComboBox = new QComboBox();
QStringList modes;
for (int i = Text; i <= Custom; ++i)
{
modes.append(convertViewModeToString(static_cast<ViewMode>(i)));
}
_defDisplayModeComboBox->addItems(modes);
defLayout->addWidget(_defDisplayModeComboBox);
layout->addLayout(defLayout);
QHBoxLayout *timeZoneLayout = new QHBoxLayout(this);
QLabel *timeZoneLabel = new QLabel("Display Dates in:");
timeZoneLayout->addWidget(timeZoneLabel);
_timeZoneComboBox = new QComboBox();
QStringList times;
for (int i = Utc; i <= LocalTime; ++i)
{
times.append(convertTimesToString(static_cast<SupportedTimes>(i)));
}
_timeZoneComboBox->addItems(times);
timeZoneLayout->addWidget(_timeZoneComboBox);
layout->addLayout(timeZoneLayout);
QHBoxLayout *uuidEncodingLayout = new QHBoxLayout(this);
QLabel *uuidEncodingLabel = new QLabel("Legacy UUID Encoding:");
uuidEncodingLayout->addWidget(uuidEncodingLabel);
_uuidEncodingComboBox = new QComboBox();
QStringList uuids;
for (int i = DefaultEncoding; i <= PythonLegacy; ++i)
{
uuids.append(convertUUIDEncodingToString(static_cast<UUIDEncoding>(i)));
}
_uuidEncodingComboBox->addItems(uuids);
uuidEncodingLayout->addWidget(_uuidEncodingComboBox);
layout->addLayout(uuidEncodingLayout);
_loadMongoRcJsCheckBox = new QCheckBox("Load .mongorc.js");
layout->addWidget(_loadMongoRcJsCheckBox);
_disabelConnectionShortcutsCheckBox = new QCheckBox("Disable connection shortcuts");
layout->addWidget(_disabelConnectionShortcutsCheckBox);
QHBoxLayout *stylesLayout = new QHBoxLayout(this);
QLabel *stylesLabel = new QLabel("Styles:");
stylesLayout->addWidget(stylesLabel);
_stylesComboBox = new QComboBox();
_stylesComboBox->addItems(AppStyleUtils::getSupportedStyles());
stylesLayout->addWidget(_stylesComboBox);
layout->addLayout(stylesLayout);
QDialogButtonBox *buttonBox = new QDialogButtonBox(this);
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Save);
VERIFY(connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())));
VERIFY(connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())));
layout->addWidget(buttonBox);
setLayout(layout);
syncWithSettings();
}
void PreferencesDialog::syncWithSettings()
{
utils::setCurrentText(_defDisplayModeComboBox, convertViewModeToString(Robomongo::AppRegistry::instance().settingsManager()->viewMode()));
utils::setCurrentText(_timeZoneComboBox, convertTimesToString(Robomongo::AppRegistry::instance().settingsManager()->timeZone()));
utils::setCurrentText(_uuidEncodingComboBox, convertUUIDEncodingToString(Robomongo::AppRegistry::instance().settingsManager()->uuidEncoding()));
_loadMongoRcJsCheckBox->setChecked(AppRegistry::instance().settingsManager()->loadMongoRcJs());
_disabelConnectionShortcutsCheckBox->setChecked(AppRegistry::instance().settingsManager()->disableConnectionShortcuts());
utils::setCurrentText(_stylesComboBox, Robomongo::AppRegistry::instance().settingsManager()->currentStyle());
}
void PreferencesDialog::accept()
{
ViewMode mode = convertStringToViewMode(QtUtils::toStdString(_defDisplayModeComboBox->currentText()).c_str());
Robomongo::AppRegistry::instance().settingsManager()->setViewMode(mode);
SupportedTimes time = convertStringToTimes(QtUtils::toStdString(_timeZoneComboBox->currentText()).c_str());
Robomongo::AppRegistry::instance().settingsManager()->setTimeZone(time);
UUIDEncoding uuidC = convertStringToUUIDEncoding(QtUtils::toStdString(_uuidEncodingComboBox->currentText()).c_str());
Robomongo::AppRegistry::instance().settingsManager()->setUuidEncoding(uuidC);
AppRegistry::instance().settingsManager()->setLoadMongoRcJs(_loadMongoRcJsCheckBox->isChecked());
AppRegistry::instance().settingsManager()->setDisableConnectionShortcuts(_disabelConnectionShortcutsCheckBox->isChecked());
Robomongo::AppRegistry::instance().settingsManager()->setCurrentStyle(_stylesComboBox->currentText());
AppStyleUtils::applyStyle(_stylesComboBox->currentText());
Robomongo::AppRegistry::instance().settingsManager()->save();
return BaseClass::accept();
}
}
| 5,710
|
C++
|
.cpp
| 105
| 46.609524
| 152
| 0.717457
|
Studio3T/robomongo
| 9,296
| 797
| 724
|
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.