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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,781
|
wslay_queue.h
|
aria2_aria2/deps/wslay/lib/wslay_queue.h
|
/*
* Wslay - The WebSocket Library
*
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WSLAY_QUEUE_H
#define WSLAY_QUEUE_H
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif /* HAVE_CONFIG_H */
#include <wslay/wslay.h>
struct wslay_queue_entry {
struct wslay_queue_entry *next;
};
struct wslay_queue {
struct wslay_queue_entry *top;
struct wslay_queue_entry **tail;
};
void wslay_queue_init(struct wslay_queue *queue);
void wslay_queue_deinit(struct wslay_queue *queue);
void wslay_queue_push(struct wslay_queue *queue, struct wslay_queue_entry *ent);
void wslay_queue_push_front(struct wslay_queue *queue,
struct wslay_queue_entry *ent);
void wslay_queue_pop(struct wslay_queue *queue);
struct wslay_queue_entry *wslay_queue_top(struct wslay_queue *queue);
struct wslay_queue_entry *wslay_queue_tail(struct wslay_queue *queue);
int wslay_queue_empty(struct wslay_queue *queue);
#endif /* WSLAY_QUEUE_H */
| 2,035
|
C++
|
.h
| 47
| 40.957447
| 80
| 0.761857
|
aria2/aria2
| 35,165
| 3,564
| 1,088
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
1,782
|
wslay_event.h
|
aria2_aria2/deps/wslay/lib/wslay_event.h
|
/*
* Wslay - The WebSocket Library
*
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WSLAY_EVENT_H
#define WSLAY_EVENT_H
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif /* HAVE_CONFIG_H */
#include <wslay/wslay.h>
#include "wslay_queue.h"
struct wslay_event_byte_chunk {
struct wslay_queue_entry qe;
uint8_t *data;
size_t data_length;
};
struct wslay_event_imsg {
uint8_t fin;
uint8_t rsv;
uint8_t opcode;
uint32_t utf8state;
struct wslay_queue chunks;
size_t msg_length;
};
enum wslay_event_msg_type { WSLAY_NON_FRAGMENTED, WSLAY_FRAGMENTED };
struct wslay_event_omsg {
struct wslay_queue_entry qe;
uint8_t fin;
uint8_t opcode;
uint8_t rsv;
enum wslay_event_msg_type type;
uint8_t *data;
size_t data_length;
union wslay_event_msg_source source;
wslay_event_fragmented_msg_callback read_callback;
};
struct wslay_event_frame_user_data {
wslay_event_context_ptr ctx;
void *user_data;
};
enum wslay_event_close_status {
WSLAY_CLOSE_RECEIVED = 1 << 0,
WSLAY_CLOSE_QUEUED = 1 << 1,
WSLAY_CLOSE_SENT = 1 << 2
};
enum wslay_event_config { WSLAY_CONFIG_NO_BUFFERING = 1 << 0 };
struct wslay_event_context {
/* config status, bitwise OR of enum wslay_event_config values*/
uint32_t config;
/* maximum message length that can be received */
uint64_t max_recv_msg_length;
/* 1 if initialized for server, otherwise 0 */
uint8_t server;
/* bitwise OR of enum wslay_event_close_status values */
uint8_t close_status;
/* status code in received close control frame */
uint16_t status_code_recv;
/* status code in sent close control frame */
uint16_t status_code_sent;
wslay_frame_context_ptr frame_ctx;
/* 1 if reading is enabled, otherwise 0. Upon receiving close
control frame this value set to 0. If any errors in read
operation will also set this value to 0. */
uint8_t read_enabled;
/* 1 if writing is enabled, otherwise 0 Upon completing sending
close control frame, this value set to 0. If any errors in write
opration will also set this value to 0. */
uint8_t write_enabled;
/* imsg buffer to allow interleaved control frame between
non-control frames. */
struct wslay_event_imsg imsgs[2];
/* Pointer to imsgs to indicate current used buffer. */
struct wslay_event_imsg *imsg;
/* payload length of frame currently being received. */
uint64_t ipayloadlen;
/* next byte offset of payload currently being received. */
uint64_t ipayloadoff;
/* error value set by user callback */
int error;
/* Pointer to the message currently being sent. NULL if no message
is currently sent. */
struct wslay_event_omsg *omsg;
/* Queue for non-control frames */
struct wslay_queue /*<wslay_omsg*>*/ send_queue;
/* Queue for control frames */
struct wslay_queue /*<wslay_omsg*>*/ send_ctrl_queue;
/* Size of send_queue + size of send_ctrl_queue */
size_t queued_msg_count;
/* The sum of message length in send_queue */
size_t queued_msg_length;
/* Buffer used for fragmented messages */
uint8_t obuf[4096];
uint8_t *obuflimit;
uint8_t *obufmark;
/* payload length of frame currently being sent. */
uint64_t opayloadlen;
/* next byte offset of payload currently being sent. */
uint64_t opayloadoff;
struct wslay_event_callbacks callbacks;
struct wslay_event_frame_user_data frame_user_data;
void *user_data;
uint8_t allowed_rsv_bits;
};
#endif /* WSLAY_EVENT_H */
| 4,518
|
C++
|
.h
| 124
| 33.733871
| 73
| 0.737443
|
aria2/aria2
| 35,165
| 3,564
| 1,088
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
1,783
|
wslay_stack.h
|
aria2_aria2/deps/wslay/lib/wslay_stack.h
|
/*
* Wslay - The WebSocket Library
*
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WSLAY_STACK_H
#define WSLAY_STACK_H
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif /* HAVE_CONFIG_H */
#include <wslay/wslay.h>
struct wslay_stack_cell {
void *data;
struct wslay_stack_cell *next;
};
struct wslay_stack {
struct wslay_stack_cell *top;
};
struct wslay_stack* wslay_stack_new();
void wslay_stack_free(struct wslay_stack *stack);
int wslay_stack_push(struct wslay_stack *stack, void *data);
void wslay_stack_pop(struct wslay_stack *stack);
void* wslay_stack_top(struct wslay_stack *stack);
int wslay_stack_empty(struct wslay_stack *stack);
#endif /* WSLAY_STACK_H */
| 1,772
|
C++
|
.h
| 44
| 38.477273
| 73
| 0.766551
|
aria2/aria2
| 35,165
| 3,564
| 1,088
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,784
|
wslay_macro.h
|
aria2_aria2/deps/wslay/lib/wslay_macro.h
|
/*
* Wslay - The WebSocket Library
*
* Copyright (c) 2020 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WSLAY_MACRO_H
#define WSLAY_MACRO_H
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif /* HAVE_CONFIG_H */
#include <wslay/wslay.h>
#include <stddef.h>
#define wslay_struct_of(ptr, type, member) \
((type *)(void *)((char *)(ptr)-offsetof(type, member)))
#endif /* WSLAY_MACRO_H */
| 1,494
|
C++
|
.h
| 34
| 42.058824
| 80
| 0.738832
|
aria2/aria2
| 35,165
| 3,564
| 1,088
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,785
|
wslay_net.h
|
aria2_aria2/deps/wslay/lib/wslay_net.h
|
/*
* Wslay - The WebSocket Library
*
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WSLAY_NET_H
#define WSLAY_NET_H
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif /* HAVE_CONFIG_H */
#include <wslay/wslay.h>
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif /* HAVE_ARPA_INET_H */
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif /* HAVE_NETINET_IN_H */
/* For Mingw build */
#ifdef HAVE_WINSOCK2_H
# include <winsock2.h>
#endif /* HAVE_WINSOCK2_H */
#ifdef WORDS_BIGENDIAN
# define ntoh64(x) (x)
# define hton64(x) (x)
#else /* !WORDS_BIGENDIAN */
uint64_t wslay_byteswap64(uint64_t x);
# define ntoh64(x) wslay_byteswap64(x)
# define hton64(x) wslay_byteswap64(x)
#endif /* !WORDS_BIGENDIAN */
#endif /* WSLAY_NET_H */
| 1,842
|
C++
|
.h
| 49
| 36.020408
| 73
| 0.748322
|
aria2/aria2
| 35,165
| 3,564
| 1,088
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,787
|
wslay.h
|
aria2_aria2/deps/wslay/lib/includes/wslay/wslay.h
|
/*
* Wslay - The WebSocket Library
*
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WSLAY_H
#define WSLAY_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stdlib.h>
#include <sys/types.h>
/*
* wslay/wslayver.h is generated from wslay/wslayver.h.in by
* configure. The projects which do not use autotools can set
* WSLAY_VERSION macro from outside to avoid to generating wslayver.h
*/
#ifndef WSLAY_VERSION
# include <wslay/wslayver.h>
#endif /* WSLAY_VERSION */
enum wslay_error {
WSLAY_ERR_WANT_READ = -100,
WSLAY_ERR_WANT_WRITE = -101,
WSLAY_ERR_PROTO = -200,
WSLAY_ERR_INVALID_ARGUMENT = -300,
WSLAY_ERR_INVALID_CALLBACK = -301,
WSLAY_ERR_NO_MORE_MSG = -302,
WSLAY_ERR_CALLBACK_FAILURE = -400,
WSLAY_ERR_WOULDBLOCK = -401,
WSLAY_ERR_NOMEM = -500
};
/*
* Status codes defined in RFC6455
*/
enum wslay_status_code {
WSLAY_CODE_NORMAL_CLOSURE = 1000,
WSLAY_CODE_GOING_AWAY = 1001,
WSLAY_CODE_PROTOCOL_ERROR = 1002,
WSLAY_CODE_UNSUPPORTED_DATA = 1003,
WSLAY_CODE_NO_STATUS_RCVD = 1005,
WSLAY_CODE_ABNORMAL_CLOSURE = 1006,
WSLAY_CODE_INVALID_FRAME_PAYLOAD_DATA = 1007,
WSLAY_CODE_POLICY_VIOLATION = 1008,
WSLAY_CODE_MESSAGE_TOO_BIG = 1009,
WSLAY_CODE_MANDATORY_EXT = 1010,
WSLAY_CODE_INTERNAL_SERVER_ERROR = 1011,
WSLAY_CODE_TLS_HANDSHAKE = 1015
};
enum wslay_io_flags {
/*
* There is more data to send.
*/
WSLAY_MSG_MORE = 1
};
/*
* Callback function used by wslay_frame_send() function when it needs
* to send data. The implementation of this function must send at most
* len bytes of data in data. flags is the bitwise OR of zero or more
* of the following flag:
*
* WSLAY_MSG_MORE
* There is more data to send
*
* It provides some hints to tune performance and behaviour. user_data
* is one given in wslay_frame_context_init() function. The
* implementation of this function must return the number of bytes
* sent. If there is an error, return -1. The return value 0 is also
* treated an error by the library.
*/
typedef ssize_t (*wslay_frame_send_callback)(const uint8_t *data, size_t len,
int flags, void *user_data);
/*
* Callback function used by wslay_frame_recv() function when it needs
* more data. The implementation of this function must fill at most
* len bytes of data into buf. The memory area of buf is allocated by
* library and not be freed by the application code. flags is always 0
* in this version. user_data is one given in
* wslay_frame_context_init() function. The implementation of this
* function must return the number of bytes filled. If there is an
* error, return -1. The return value 0 is also treated an error by
* the library.
*/
typedef ssize_t (*wslay_frame_recv_callback)(uint8_t *buf, size_t len,
int flags, void *user_data);
/*
* Callback function used by wslay_frame_send() function when it needs
* new mask key. The implementation of this function must write
* exactly len bytes of mask key to buf. user_data is one given in
* wslay_frame_context_init() function. The implementation of this
* function return 0 on success. If there is an error, return -1.
*/
typedef int (*wslay_frame_genmask_callback)(uint8_t *buf, size_t len,
void *user_data);
struct wslay_frame_callbacks {
wslay_frame_send_callback send_callback;
wslay_frame_recv_callback recv_callback;
wslay_frame_genmask_callback genmask_callback;
};
/*
* The opcode defined in RFC6455.
*/
enum wslay_opcode {
WSLAY_CONTINUATION_FRAME = 0x0u,
WSLAY_TEXT_FRAME = 0x1u,
WSLAY_BINARY_FRAME = 0x2u,
WSLAY_CONNECTION_CLOSE = 0x8u,
WSLAY_PING = 0x9u,
WSLAY_PONG = 0xau
};
/*
* Macro that returns 1 if opcode is control frame opcode, otherwise
* returns 0.
*/
#define wslay_is_ctrl_frame(opcode) ((opcode >> 3) & 1)
/*
* Macros that represent and return reserved bits: RSV1, RSV2, RSV3.
* These macros assume that rsv is constructed by ((RSV1 << 2) |
* (RSV2 << 1) | RSV3)
*/
#define WSLAY_RSV_NONE ((uint8_t)0)
#define WSLAY_RSV1_BIT (((uint8_t)1) << 2)
#define WSLAY_RSV2_BIT (((uint8_t)1) << 1)
#define WSLAY_RSV3_BIT (((uint8_t)1) << 0)
#define wslay_get_rsv1(rsv) ((rsv >> 2) & 1)
#define wslay_get_rsv2(rsv) ((rsv >> 1) & 1)
#define wslay_get_rsv3(rsv) (rsv & 1)
struct wslay_frame_iocb {
/* 1 for fragmented final frame, 0 for otherwise */
uint8_t fin;
/*
* reserved 3 bits. rsv = ((RSV1 << 2) | (RSV << 1) | RSV3).
* RFC6455 requires 0 unless extensions are negotiated.
*/
uint8_t rsv;
/* 4 bit opcode */
uint8_t opcode;
/* payload length [0, 2**63-1] */
uint64_t payload_length;
/* 1 for masked frame, 0 for unmasked */
uint8_t mask;
/* part of payload data */
const uint8_t *data;
/* bytes of data defined above */
size_t data_length;
};
struct wslay_frame_context;
typedef struct wslay_frame_context *wslay_frame_context_ptr;
/*
* Initializes ctx using given callbacks and user_data. This function
* allocates memory for struct wslay_frame_context and stores the
* result to *ctx. The callback functions specified in callbacks are
* copied to ctx. user_data is stored in ctx and it will be passed to
* callback functions. When the user code finished using ctx, it must
* call wslay_frame_context_free to deallocate memory.
*/
int wslay_frame_context_init(wslay_frame_context_ptr *ctx,
const struct wslay_frame_callbacks *callbacks,
void *user_data);
/*
* Deallocates memory pointed by ctx.
*/
void wslay_frame_context_free(wslay_frame_context_ptr ctx);
/*
* Send WebSocket frame specified in iocb. ctx must be initialized
* using wslay_frame_context_init() function. iocb->fin must be 1 if
* this is a fin frame, otherwise 0. iocb->rsv is reserved bits.
* iocb->opcode must be the opcode of this frame. iocb->mask must be
* 1 if this is masked frame, otherwise 0. iocb->payload_length is
* the payload_length of this frame. iocb->data must point to the
* payload data to be sent. iocb->data_length must be the length of
* the data. This function calls send_callback function if it needs
* to send bytes. This function calls gen_mask_callback function if
* it needs new mask key. This function returns the number of payload
* bytes sent. Please note that it does not include any number of
* header bytes. If it cannot send any single bytes of payload, it
* returns WSLAY_ERR_WANT_WRITE. If the library detects error in iocb,
* this function returns WSLAY_ERR_INVALID_ARGUMENT. If callback
* functions report a failure, this function returns
* WSLAY_ERR_INVALID_CALLBACK. This function does not always send all
* given data in iocb. If there are remaining data to be sent, adjust
* data and data_length in iocb accordingly and call this function
* again.
*/
ssize_t wslay_frame_send(wslay_frame_context_ptr ctx,
struct wslay_frame_iocb *iocb);
/*
* Write WebSocket frame specified in iocb to buf of length
* buflen. ctx must be initialized using wslay_frame_context_init()
* function. iocb->fin must be 1 if this is a fin frame, otherwise 0.
* iocb->rsv is reserved bits. iocb->opcode must be the opcode of
* this frame. iocb->mask must be 1 if this is masked frame,
* otherwise 0. iocb->payload_length is the payload_length of this
* frame. iocb->data must point to the payload data to be
* sent. iocb->data_length must be the length of the data. Unlike
* wslay_frame_send, this function does not call send_callback
* function. This function calls gen_mask_callback function if it
* needs new mask key. This function returns the number of bytes
* written to a buffer. Unlike wslay_frame_send, it includes the
* number of header bytes. Instead, the number of payload bytes
* written is assigned to *pwpayloadlen if this function succeeds. If
* there is not enough space left in a buffer, it returns 0. If the
* library detects error in iocb, this function returns
* WSLAY_ERR_INVALID_ARGUMENT. If callback functions report a
* failure, this function returns WSLAY_ERR_INVALID_CALLBACK. This
* function does not always send all given data in iocb. If there are
* remaining data to be sent, adjust data and data_length in iocb
* accordingly and call this function again.
*/
ssize_t wslay_frame_write(wslay_frame_context_ptr ctx,
struct wslay_frame_iocb *iocb, uint8_t *buf,
size_t buflen, size_t *pwpayloadlen);
/*
* Receives WebSocket frame and stores it in iocb. This function
* returns the number of payload bytes received. This does not
* include header bytes. In this case, iocb will be populated as
* follows: iocb->fin is 1 if received frame is fin frame, otherwise
* 0. iocb->rsv is reserved bits of received frame. iocb->opcode is
* opcode of received frame. iocb->mask is 1 if received frame is
* masked, otherwise 0. iocb->payload_length is the payload length of
* received frame. iocb->data is pointed to the buffer containing
* received payload data. This buffer is allocated by the library and
* must be read-only. iocb->data_length is the number of payload
* bytes recieved. This function calls recv_callback if it needs to
* receive additional bytes. If it cannot receive any single bytes of
* payload, it returns WSLAY_ERR_WANT_READ. If the library detects
* protocol violation in a received frame, this function returns
* WSLAY_ERR_PROTO. If callback functions report a failure, this
* function returns WSLAY_ERR_INVALID_CALLBACK. This function does
* not always receive whole frame in a single call. If there are
* remaining data to be received, call this function again. This
* function ensures frame alignment.
*/
ssize_t wslay_frame_recv(wslay_frame_context_ptr ctx,
struct wslay_frame_iocb *iocb);
struct wslay_event_context;
/* Pointer to the event-based API context */
typedef struct wslay_event_context *wslay_event_context_ptr;
struct wslay_event_on_msg_recv_arg {
/* reserved bits: rsv = (RSV1 << 2) | (RSV2 << 1) | RSV3 */
uint8_t rsv;
/* opcode */
uint8_t opcode;
/* received message */
const uint8_t *msg;
/* message length */
size_t msg_length;
/*
* Status code iff opcode == WSLAY_CONNECTION_CLOSE. If no status
* code is included in the close control frame, it is set to 0.
*/
uint16_t status_code;
};
/*
* Callback function invoked by wslay_event_recv() when a message is
* completely received.
*/
typedef void (*wslay_event_on_msg_recv_callback)(
wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg,
void *user_data);
struct wslay_event_on_frame_recv_start_arg {
/* fin bit; 1 for final frame, or 0. */
uint8_t fin;
/* reserved bits: rsv = (RSV1 << 2) | (RSV2 << 1) | RSV3 */
uint8_t rsv;
/* opcode of the frame */
uint8_t opcode;
/* payload length of ths frame */
uint64_t payload_length;
};
/*
* Callback function invoked by wslay_event_recv() when a new frame
* starts to be received. This callback function is only invoked once
* for each frame.
*/
typedef void (*wslay_event_on_frame_recv_start_callback)(
wslay_event_context_ptr ctx,
const struct wslay_event_on_frame_recv_start_arg *arg, void *user_data);
struct wslay_event_on_frame_recv_chunk_arg {
/* chunk of payload data */
const uint8_t *data;
/* length of data */
size_t data_length;
};
/*
* Callback function invoked by wslay_event_recv() when a chunk of
* frame payload is received.
*/
typedef void (*wslay_event_on_frame_recv_chunk_callback)(
wslay_event_context_ptr ctx,
const struct wslay_event_on_frame_recv_chunk_arg *arg, void *user_data);
/*
* Callback function invoked by wslay_event_recv() when a frame is
* completely received.
*/
typedef void (*wslay_event_on_frame_recv_end_callback)(
wslay_event_context_ptr ctx, void *user_data);
/*
* Callback function invoked by wslay_event_recv() when it wants to
* receive more data from peer. The implementation of this callback
* function must read data at most len bytes from peer and store them
* in buf and return the number of bytes read. flags is always 0 in
* this version.
*
* If there is an error, return -1 and set error code
* WSLAY_ERR_CALLBACK_FAILURE using wslay_event_set_error(). Wslay
* event-based API on the whole assumes non-blocking I/O. If the cause
* of error is EAGAIN or EWOULDBLOCK, set WSLAY_ERR_WOULDBLOCK
* instead. This is important because it tells wslay_event_recv() to
* stop receiving further data and return.
*/
typedef ssize_t (*wslay_event_recv_callback)(wslay_event_context_ptr ctx,
uint8_t *buf, size_t len,
int flags, void *user_data);
/*
* Callback function invoked by wslay_event_send() when it wants to
* send more data to peer. The implementation of this callback
* function must send data at most len bytes to peer and return the
* number of bytes sent. flags is the bitwise OR of zero or more of
* the following flag:
*
* WSLAY_MSG_MORE
* There is more data to send
*
* It provides some hints to tune performance and behaviour.
*
* If there is an error, return -1 and set error code
* WSLAY_ERR_CALLBACK_FAILURE using wslay_event_set_error(). Wslay
* event-based API on the whole assumes non-blocking I/O. If the cause
* of error is EAGAIN or EWOULDBLOCK, set WSLAY_ERR_WOULDBLOCK
* instead. This is important because it tells wslay_event_send() to
* stop sending data and return.
*/
typedef ssize_t (*wslay_event_send_callback)(wslay_event_context_ptr ctx,
const uint8_t *data, size_t len,
int flags, void *user_data);
/*
* Callback function invoked by wslay_event_send() when it wants new
* mask key. As described in RFC6455, only the traffic from WebSocket
* client is masked, so this callback function is only needed if an
* event-based API is initialized for WebSocket client use.
*/
typedef int (*wslay_event_genmask_callback)(wslay_event_context_ptr ctx,
uint8_t *buf, size_t len,
void *user_data);
struct wslay_event_callbacks {
wslay_event_recv_callback recv_callback;
wslay_event_send_callback send_callback;
wslay_event_genmask_callback genmask_callback;
wslay_event_on_frame_recv_start_callback on_frame_recv_start_callback;
wslay_event_on_frame_recv_chunk_callback on_frame_recv_chunk_callback;
wslay_event_on_frame_recv_end_callback on_frame_recv_end_callback;
wslay_event_on_msg_recv_callback on_msg_recv_callback;
};
/*
* Initializes ctx as WebSocket Server. user_data is an arbitrary
* pointer, which is directly passed to each callback functions as
* user_data argument.
*
* On success, returns 0. On error, returns one of following negative
* values:
*
* WSLAY_ERR_NOMEM
* Out of memory.
*/
int wslay_event_context_server_init(
wslay_event_context_ptr *ctx, const struct wslay_event_callbacks *callbacks,
void *user_data);
/*
* Initializes ctx as WebSocket client. user_data is an arbitrary
* pointer, which is directly passed to each callback functions as
* user_data argument.
*
* On success, returns 0. On error, returns one of following negative
* values:
*
* WSLAY_ERR_NOMEM
* Out of memory.
*/
int wslay_event_context_client_init(
wslay_event_context_ptr *ctx, const struct wslay_event_callbacks *callbacks,
void *user_data);
/*
* Releases allocated resources for ctx.
*/
void wslay_event_context_free(wslay_event_context_ptr ctx);
/*
* Sets a bit mask of allowed reserved bits.
* Currently only permitted values are WSLAY_RSV1_BIT to allow PMCE
* extension (see RFC-7692) or WSLAY_RSV_NONE to disable.
*
* Default: WSLAY_RSV_NONE
*/
void wslay_event_config_set_allowed_rsv_bits(wslay_event_context_ptr ctx,
uint8_t rsv);
/*
* Enables or disables buffering of an entire message for non-control
* frames. If val is 0, buffering is enabled. Otherwise, buffering is
* disabled. If wslay_event_on_msg_recv_callback is invoked when
* buffering is disabled, the msg_length member of struct
* wslay_event_on_msg_recv_arg is set to 0.
*
* The control frames are always buffered regardless of this function call.
*
* This function must not be used after the first invocation of
* wslay_event_recv() function.
*/
void wslay_event_config_set_no_buffering(wslay_event_context_ptr ctx, int val);
/*
* Sets maximum length of a message that can be received. The length
* of message is checked by wslay_event_recv() function. If the length
* of a message is larger than this value, reading operation is
* disabled (same effect with wslay_event_shutdown_read() call) and
* close control frame with WSLAY_CODE_MESSAGE_TOO_BIG is queued. If
* buffering for non-control frames is disabled, the library checks
* each frame payload length and does not check length of entire
* message.
*
* The default value is (1u << 31)-1.
*/
void wslay_event_config_set_max_recv_msg_length(wslay_event_context_ptr ctx,
uint64_t val);
/*
* Sets callbacks to ctx. The callbacks previously set by this function
* or wslay_event_context_server_init() or
* wslay_event_context_client_init() are replaced with callbacks.
*/
void wslay_event_config_set_callbacks(
wslay_event_context_ptr ctx, const struct wslay_event_callbacks *callbacks);
/*
* Receives messages from peer. When receiving
* messages, it uses wslay_event_recv_callback function. Single call
* of this function receives multiple messages until
* wslay_event_recv_callback function sets error code
* WSLAY_ERR_WOULDBLOCK.
*
* When close control frame is received, this function automatically
* queues close control frame. Also this function calls
* wslay_event_set_read_enabled() with second argument 0 to disable
* further read from peer.
*
* When ping control frame is received, this function automatically
* queues pong control frame.
*
* In case of a fatal errror which leads to negative return code, this
* function calls wslay_event_set_read_enabled() with second argument
* 0 to disable further read from peer.
*
* wslay_event_recv() returns 0 if it succeeds, or one of the
* following negative error codes:
*
* WSLAY_ERR_CALLBACK_FAILURE
* User defined callback function is failed.
*
* WSLAY_ERR_NOMEM
* Out of memory.
*
* When negative error code is returned, application must not make any
* further call of wslay_event_recv() and must close WebSocket
* connection.
*/
int wslay_event_recv(wslay_event_context_ptr ctx);
/*
* Sends queued messages to peer. When sending a
* message, it uses wslay_event_send_callback function. Single call of
* wslay_event_send() sends multiple messages until
* wslay_event_send_callback sets error code WSLAY_ERR_WOULDBLOCK.
*
* If ctx is initialized for WebSocket client use, wslay_event_send()
* uses wslay_event_genmask_callback to get new mask key.
*
* When a message queued using wslay_event_queue_fragmented_msg() is
* sent, wslay_event_send() invokes
* wslay_event_fragmented_msg_callback for that message.
*
* After close control frame is sent, this function calls
* wslay_event_set_write_enabled() with second argument 0 to disable
* further transmission to peer.
*
* If there are any pending messages, wslay_event_want_write() returns
* 1, otherwise returns 0.
*
* In case of a fatal errror which leads to negative return code, this
* function calls wslay_event_set_write_enabled() with second argument
* 0 to disable further transmission to peer.
*
* wslay_event_send() returns 0 if it succeeds, or one of the
* following negative error codes:
*
* WSLAY_ERR_CALLBACK_FAILURE
* User defined callback function is failed.
*
* WSLAY_ERR_NOMEM
* Out of memory.
*
* When negative error code is returned, application must not make any
* further call of wslay_event_send() and must close WebSocket
* connection.
*/
int wslay_event_send(wslay_event_context_ptr ctx);
/*
* Writes queued messages to a buffer. Unlike wslay_event_send(), this
* function writes messages into the given buffer. It does not use
* wslay_event_send_callback function. Single call of
* wslay_event_write() writes multiple messages until there is not
* enough space left in a buffer.
*
* If ctx is initialized for WebSocket client use, wslay_event_write()
* uses wslay_event_genmask_callback to get new mask key.
*
* buf is a pointer to buffer and its capacity is given in buflen. It
* should have at least 14 bytes.
*
* When a message queued using wslay_event_queue_fragmented_msg() is
* sent, wslay_event_write() invokes
* wslay_event_fragmented_msg_callback for that message.
*
* After close control frame is sent, this function calls
* wslay_event_set_write_enabled() with second argument 0 to disable
* further transmission to peer.
*
* If there are any pending messages, wslay_event_want_write() returns
* 1, otherwise returns 0.
*
* In case of a fatal errror which leads to negative return code, this
* function calls wslay_event_set_write_enabled() with second argument
* 0 to disable further transmission to peer.
*
* wslay_event_write() returns the number of bytes written to a buffer
* if it succeeds, or one of the following negative error codes:
*
* WSLAY_ERR_CALLBACK_FAILURE
* User defined callback function is failed.
*
* WSLAY_ERR_NOMEM
* Out of memory.
*
* When negative error code is returned, application must not make any
* further call of wslay_event_write() and must close WebSocket
* connection.
*/
ssize_t wslay_event_write(wslay_event_context_ptr ctx, uint8_t *buf,
size_t buflen);
struct wslay_event_msg {
uint8_t opcode;
const uint8_t *msg;
size_t msg_length;
};
/*
* Queues message specified in arg.
*
* This function supports both control and non-control messages and
* the given message is sent without fragmentation. If fragmentation
* is needed, use wslay_event_queue_fragmented_msg() function instead.
*
* This function just queues a message and does not send
* it. wslay_event_send() function call sends these queued messages.
*
* wslay_event_queue_msg() returns 0 if it succeeds, or returns the
* following negative error codes:
*
* WSLAY_ERR_NO_MORE_MSG
* Could not queue given message. The one of possible reason is that
* close control frame has been queued/sent and no further queueing
* message is not allowed.
*
* WSLAY_ERR_INVALID_ARGUMENT
* The given message is invalid.
*
* WSLAY_ERR_NOMEM
* Out of memory.
*/
int wslay_event_queue_msg(wslay_event_context_ptr ctx,
const struct wslay_event_msg *arg);
/*
* Extended version of wslay_event_queue_msg which allows to set reserved bits.
*/
int wslay_event_queue_msg_ex(wslay_event_context_ptr ctx,
const struct wslay_event_msg *arg, uint8_t rsv);
/*
* Specify "source" to generate message.
*/
union wslay_event_msg_source {
int fd;
void *data;
};
/*
* Callback function called by wslay_event_send() to read message data
* from source. The implementation of
* wslay_event_fragmented_msg_callback must store at most len bytes of
* data to buf and return the number of stored bytes. If all data is
* read (i.e., EOF), set *eof to 1. If no data can be generated at the
* moment, return 0. If there is an error, return -1 and set error
* code WSLAY_ERR_CALLBACK_FAILURE using wslay_event_set_error().
*/
typedef ssize_t (*wslay_event_fragmented_msg_callback)(
wslay_event_context_ptr ctx, uint8_t *buf, size_t len,
const union wslay_event_msg_source *source, int *eof, void *user_data);
struct wslay_event_fragmented_msg {
/* opcode */
uint8_t opcode;
/* "source" to generate message data */
union wslay_event_msg_source source;
/* Callback function to read message data from source. */
wslay_event_fragmented_msg_callback read_callback;
};
/*
* Queues a fragmented message specified in arg.
*
* This function supports non-control messages only. For control frames,
* use wslay_event_queue_msg() or wslay_event_queue_close().
*
* This function just queues a message and does not send
* it. wslay_event_send() function call sends these queued messages.
*
* wslay_event_queue_fragmented_msg() returns 0 if it succeeds, or
* returns the following negative error codes:
*
* WSLAY_ERR_NO_MORE_MSG
* Could not queue given message. The one of possible reason is that
* close control frame has been queued/sent and no further queueing
* message is not allowed.
*
* WSLAY_ERR_INVALID_ARGUMENT
* The given message is invalid.
*
* WSLAY_ERR_NOMEM
* Out of memory.
*/
int wslay_event_queue_fragmented_msg(
wslay_event_context_ptr ctx, const struct wslay_event_fragmented_msg *arg);
/*
* Extended version of wslay_event_queue_fragmented_msg which allows to set
* reserved bits.
*/
int wslay_event_queue_fragmented_msg_ex(
wslay_event_context_ptr ctx, const struct wslay_event_fragmented_msg *arg,
uint8_t rsv);
/*
* Queues close control frame. This function is provided just for
* convenience. wslay_event_queue_msg() can queue a close control
* frame as well. status_code is the status code of close control
* frame. reason is the close reason encoded in UTF-8. reason_length
* is the length of reason in bytes. reason_length must be less than
* 123 bytes.
*
* If status_code is 0, reason and reason_length is not used and close
* control frame with zero-length payload will be queued.
*
* This function just queues a message and does not send
* it. wslay_event_send() function call sends these queued messages.
*
* wslay_event_queue_close() returns 0 if it succeeds, or returns the
* following negative error codes:
*
* WSLAY_ERR_NO_MORE_MSG
* Could not queue given message. The one of possible reason is that
* close control frame has been queued/sent and no further queueing
* message is not allowed.
*
* WSLAY_ERR_INVALID_ARGUMENT
* The given message is invalid.
*
* WSLAY_ERR_NOMEM
* Out of memory.
*/
int wslay_event_queue_close(wslay_event_context_ptr ctx, uint16_t status_code,
const uint8_t *reason, size_t reason_length);
/*
* Sets error code to tell the library there is an error. This
* function is typically used in user defined callback functions. See
* the description of callback function to know which error code
* should be used.
*/
void wslay_event_set_error(wslay_event_context_ptr ctx, int val);
/*
* Query whehter the library want to read more data from peer.
*
* wslay_event_want_read() returns 1 if the library want to read more
* data from peer, or returns 0.
*/
int wslay_event_want_read(wslay_event_context_ptr ctx);
/*
* Query whehter the library want to send more data to peer.
*
* wslay_event_want_write() returns 1 if the library want to send more
* data to peer, or returns 0.
*/
int wslay_event_want_write(wslay_event_context_ptr ctx);
/*
* Prevents the event-based API context from reading any further data
* from peer.
*
* This function may be used with wslay_event_queue_close() if the
* application detects error in the data received and wants to fail
* WebSocket connection.
*/
void wslay_event_shutdown_read(wslay_event_context_ptr ctx);
/*
* Prevents the event-based API context from sending any further data
* to peer.
*/
void wslay_event_shutdown_write(wslay_event_context_ptr ctx);
/*
* Returns 1 if the event-based API context allows read operation, or
* return 0.
*
* After wslay_event_shutdown_read() is called,
* wslay_event_get_read_enabled() returns 0.
*/
int wslay_event_get_read_enabled(wslay_event_context_ptr ctx);
/*
* Returns 1 if the event-based API context allows write operation, or
* return 0.
*
* After wslay_event_shutdown_write() is called,
* wslay_event_get_write_enabled() returns 0.
*/
int wslay_event_get_write_enabled(wslay_event_context_ptr ctx);
/*
* Returns 1 if a close control frame has been received from peer, or
* returns 0.
*/
int wslay_event_get_close_received(wslay_event_context_ptr ctx);
/*
* Returns 1 if a close control frame has been sent to peer, or
* returns 0.
*/
int wslay_event_get_close_sent(wslay_event_context_ptr ctx);
/*
* Returns status code received in close control frame. If no close
* control frame has not been received, returns
* WSLAY_CODE_ABNORMAL_CLOSURE. If received close control frame has no
* status code, returns WSLAY_CODE_NO_STATUS_RCVD.
*/
uint16_t wslay_event_get_status_code_received(wslay_event_context_ptr ctx);
/*
* Returns status code sent in close control frame. If no close
* control frame has not been sent, returns
* WSLAY_CODE_ABNORMAL_CLOSURE. If sent close control frame has no
* status code, returns WSLAY_CODE_NO_STATUS_RCVD.
*/
uint16_t wslay_event_get_status_code_sent(wslay_event_context_ptr ctx);
/*
* Returns the number of queued messages.
*/
size_t wslay_event_get_queued_msg_count(wslay_event_context_ptr ctx);
/*
* Returns the sum of queued message length. It only counts the
* message length queued using wslay_event_queue_msg() or
* wslay_event_queue_close().
*/
size_t wslay_event_get_queued_msg_length(wslay_event_context_ptr ctx);
#ifdef __cplusplus
}
#endif
#endif /* WSLAY_H */
| 30,654
|
C++
|
.h
| 776
| 36.456186
| 80
| 0.729883
|
aria2/aria2
| 35,165
| 3,564
| 1,088
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
1,788
|
wslay_session_test.h
|
aria2_aria2/deps/wslay/tests/wslay_session_test.h
|
/*
* Wslay - The WebSocket Library
*
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WSLAY_SESSION_TEST_H
#define WSLAY_SESSION_TEST_H
#endif // WSLAY_SESSION_TEST_H
| 1,259
|
C++
|
.h
| 27
| 44.740741
| 73
| 0.77498
|
aria2/aria2
| 35,165
| 3,564
| 1,088
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,789
|
wslay_stack_test.h
|
aria2_aria2/deps/wslay/tests/wslay_stack_test.h
|
/*
* Wslay - The WebSocket Library
*
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WSLAY_STACK_TEST_H
#define WSLAY_STACK_TEST_H
void test_wslay_stack();
#endif // WSLAY_STACK_TEST_H
| 1,279
|
C++
|
.h
| 28
| 43.785714
| 73
| 0.773419
|
aria2/aria2
| 35,165
| 3,564
| 1,088
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,790
|
wslay_queue_test.h
|
aria2_aria2/deps/wslay/tests/wslay_queue_test.h
|
/*
* Wslay - The WebSocket Library
*
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WSLAY_QUEUE_TEST_H
#define WSLAY_QUEUE_TEST_H
void test_wslay_queue(void);
#endif /* WSLAY_QUEUE_TEST_H */
| 1,286
|
C++
|
.h
| 28
| 44.035714
| 73
| 0.772293
|
aria2/aria2
| 35,165
| 3,564
| 1,088
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
1,791
|
wslay_event_test.h
|
aria2_aria2/deps/wslay/tests/wslay_event_test.h
|
/*
* Wslay - The WebSocket Library
*
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WSLAY_EVENT_TEST_H
#define WSLAY_EVENT_TEST_H
void test_wslay_event_send_fragmented_msg(void);
void test_wslay_event_send_fragmented_msg_empty_data(void);
void test_wslay_event_send_fragmented_msg_with_ctrl(void);
void test_wslay_event_send_fragmented_msg_with_rsv1(void);
void test_wslay_event_send_msg_with_rsv1(void);
void test_wslay_event_send_ctrl_msg_first(void);
void test_wslay_event_send_ctrl_msg_with_rsv1(void);
void test_wslay_event_queue_close(void);
void test_wslay_event_queue_close_without_code(void);
void test_wslay_event_recv_close_without_code(void);
void test_wslay_event_reply_close(void);
void test_wslay_event_no_more_msg(void);
void test_wslay_event_callback_failure(void);
void test_wslay_event_no_buffering(void);
void test_wslay_event_recv_text_frame_with_rsv1(void);
void test_wslay_event_frame_too_big(void);
void test_wslay_event_message_too_big(void);
void test_wslay_event_config_set_allowed_rsv_bits(void);
void test_wslay_event_write_fragmented_msg(void);
void test_wslay_event_write_fragmented_msg_empty_data(void);
void test_wslay_event_write_fragmented_msg_with_ctrl(void);
void test_wslay_event_write_fragmented_msg_with_rsv1(void);
void test_wslay_event_write_msg_with_rsv1(void);
void test_wslay_event_write_ctrl_msg_first(void);
#endif /* WSLAY_EVENT_TEST_H */
| 2,482
|
C++
|
.h
| 51
| 47.176471
| 73
| 0.787567
|
aria2/aria2
| 35,165
| 3,564
| 1,088
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
1,792
|
wslay_frame_test.h
|
aria2_aria2/deps/wslay/tests/wslay_frame_test.h
|
/*
* Wslay - The WebSocket Library
*
* Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WSLAY_FRAME_TEST_H
#define WSLAY_FRAME_TEST_H
void test_wslay_frame_context_init(void);
void test_wslay_frame_recv(void);
void test_wslay_frame_recv_1byte(void);
void test_wslay_frame_recv_fragmented(void);
void test_wslay_frame_recv_interleaved_ctrl_frame(void);
void test_wslay_frame_recv_zero_payloadlen(void);
void test_wslay_frame_recv_too_large_payload(void);
void test_wslay_frame_recv_ctrl_frame_too_large_payload(void);
void test_wslay_frame_recv_minimum_ext_payload16(void);
void test_wslay_frame_recv_minimum_ext_payload64(void);
void test_wslay_frame_send(void);
void test_wslay_frame_send_fragmented(void);
void test_wslay_frame_send_interleaved_ctrl_frame(void);
void test_wslay_frame_send_1byte_masked(void);
void test_wslay_frame_send_zero_payloadlen(void);
void test_wslay_frame_send_too_large_payload(void);
void test_wslay_frame_send_ctrl_frame_too_large_payload(void);
void test_wslay_frame_write(void);
void test_wslay_frame_write_fragmented(void);
void test_wslay_frame_write_interleaved_ctrl_frame(void);
void test_wslay_frame_write_1byte_masked(void);
void test_wslay_frame_write_zero_payloadlen(void);
void test_wslay_frame_write_too_large_payload(void);
void test_wslay_frame_write_ctrl_frame_too_large_payload(void);
#endif /* WSLAY_FRAME_TEST_H */
| 2,455
|
C++
|
.h
| 51
| 46.647059
| 73
| 0.791007
|
aria2/aria2
| 35,165
| 3,564
| 1,088
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
1,793
|
enumerate_kenlm_vocabulary.cpp
|
mozilla_DeepSpeech/native_client/enumerate_kenlm_vocabulary.cpp
|
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include "lm/enumerate_vocab.hh"
#include "lm/virtual_interface.hh"
#include "lm/word_index.hh"
#include "lm/model.hh"
const std::string START_TOKEN = "<s>";
const std::string UNK_TOKEN = "<unk>";
const std::string END_TOKEN = "</s>";
// Implement a callback to retrieve the dictionary of language model.
class RetrieveStrEnumerateVocab : public lm::EnumerateVocab
{
public:
RetrieveStrEnumerateVocab() {}
void Add(lm::WordIndex index, const StringPiece &str) {
vocabulary.push_back(std::string(str.data(), str.length()));
}
std::vector<std::string> vocabulary;
};
int main(int argc, char** argv)
{
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " <kenlm_model> <output_path>" << std::endl;
return -1;
}
const char* kenlm_model = argv[1];
const char* output_path = argv[2];
std::unique_ptr<lm::base::Model> language_model_;
lm::ngram::Config config;
RetrieveStrEnumerateVocab enumerate;
config.enumerate_vocab = &enumerate;
language_model_.reset(lm::ngram::LoadVirtual(kenlm_model, config));
std::ofstream fout(output_path);
for (const std::string& word : enumerate.vocabulary) {
fout << word << "\n";
}
return 0;
}
| 1,258
|
C++
|
.cpp
| 40
| 28.95
| 85
| 0.701159
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,794
|
generate_scorer_package.cpp
|
mozilla_DeepSpeech/native_client/generate_scorer_package.cpp
|
#include <string>
#include <vector>
#include <fstream>
#include <unordered_set>
#include <iostream>
using namespace std;
#include "absl/types/optional.h"
#include "boost/program_options.hpp"
#include "ctcdecode/decoder_utils.h"
#include "ctcdecode/scorer.h"
#include "alphabet.h"
#include "deepspeech.h"
namespace po = boost::program_options;
int
create_package(absl::optional<string> alphabet_path,
string lm_path,
string vocab_path,
string package_path,
absl::optional<bool> force_bytes_output_mode,
float default_alpha,
float default_beta)
{
// Read vocabulary
unordered_set<string> words;
bool vocab_looks_char_based = true;
ifstream fin(vocab_path);
if (!fin) {
cerr << "Invalid vocabulary file " << vocab_path << "\n";
return 1;
}
string word;
while (fin >> word) {
words.insert(word);
if (get_utf8_str_len(word) > 1) {
vocab_looks_char_based = false;
}
}
cerr << words.size() << " unique words read from vocabulary file.\n"
<< (vocab_looks_char_based ? "Looks" : "Doesn't look")
<< " like a character based (Bytes Are All You Need) model.\n";
if (!force_bytes_output_mode.has_value()) {
force_bytes_output_mode = vocab_looks_char_based;
cerr << "--force_bytes_output_mode was not specified, using value "
<< "infered from vocabulary contents: "
<< (vocab_looks_char_based ? "true" : "false") << "\n";
}
if (!force_bytes_output_mode.value() && !alphabet_path.has_value()) {
cerr << "No --alphabet file specified, not using bytes output mode, can't continue.\n";
return 1;
}
Scorer scorer;
if (force_bytes_output_mode.value()) {
scorer.set_alphabet(UTF8Alphabet());
} else {
Alphabet alphabet;
alphabet.init(alphabet_path->c_str());
scorer.set_alphabet(alphabet);
}
scorer.set_utf8_mode(force_bytes_output_mode.value());
scorer.reset_params(default_alpha, default_beta);
int err = scorer.load_lm(lm_path);
if (err != DS_ERR_SCORER_NO_TRIE) {
cerr << "Error loading language model file: "
<< (err == DS_ERR_SCORER_UNREADABLE ? "Can't open binary LM file." : DS_ErrorCodeToErrorMessage(err))
<< "\n";
return 1;
}
scorer.fill_dictionary(words);
// Copy LM file to final package file destination
{
ifstream lm_src(lm_path, std::ios::binary);
ofstream package_dest(package_path, std::ios::binary);
package_dest << lm_src.rdbuf();
}
// Save dictionary to package file, appending instead of overwriting
if (!scorer.save_dictionary(package_path, true)) {
cerr << "Error when saving package in " << package_path << ".\n";
return 1;
}
cerr << "Package created in " << package_path << ".\n";
return 0;
}
int
main(int argc, char** argv)
{
po::options_description desc("Options");
desc.add_options()
("help", "show help message")
("alphabet", po::value<string>(), "Path of alphabet file to use for vocabulary construction. Words with characters not in the alphabet will not be included in the vocabulary. Optional if using bytes output mode.")
("lm", po::value<string>(), "Path of KenLM binary LM file. Must be built without including the vocabulary (use the -v flag). See generate_lm.py for how to create a binary LM.")
("vocab", po::value<string>(), "Path of vocabulary file. Must contain words separated by whitespace.")
("package", po::value<string>(), "Path to save scorer package.")
("default_alpha", po::value<float>(), "Default value of alpha hyperparameter (float).")
("default_beta", po::value<float>(), "Default value of beta hyperparameter (float).")
("force_bytes_output_mode", po::value<bool>(), "Boolean flag, force set or unset bytes output mode in the scorer package. If not set, infers from the vocabulary. See <https://deepspeech.readthedocs.io/en/master/Decoder.html#bytes-output-mode> for further explanation.")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
// Check required flags.
for (const string& flag : {"lm", "vocab", "package", "default_alpha", "default_beta"}) {
if (!vm.count(flag)) {
cerr << "--" << flag << " is a required flag. Pass --help for help.\n";
return 1;
}
}
// Parse optional --force_bytes_output_mode
absl::optional<bool> force_bytes_output_mode = absl::nullopt;
if (vm.count("force_bytes_output_mode")) {
force_bytes_output_mode = vm["force_bytes_output_mode"].as<bool>();
}
// Parse optional --alphabet
absl::optional<string> alphabet = absl::nullopt;
if (vm.count("alphabet")) {
alphabet = vm["alphabet"].as<string>();
}
create_package(alphabet,
vm["lm"].as<string>(),
vm["vocab"].as<string>(),
vm["package"].as<string>(),
force_bytes_output_mode,
vm["default_alpha"].as<float>(),
vm["default_beta"].as<float>());
return 0;
}
| 5,387
|
C++
|
.cpp
| 129
| 34.465116
| 277
| 0.612786
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,796
|
ctc_beam_search_decoder.cpp
|
mozilla_DeepSpeech/native_client/ctcdecode/ctc_beam_search_decoder.cpp
|
#include "ctc_beam_search_decoder.h"
#include <algorithm>
#include <cmath>
#include <iostream>
#include <limits>
#include <unordered_map>
#include <utility>
#include "decoder_utils.h"
#include "ThreadPool.h"
#include "fst/fstlib.h"
#include "path_trie.h"
int
DecoderState::init(const Alphabet& alphabet,
size_t beam_size,
double cutoff_prob,
size_t cutoff_top_n,
std::shared_ptr<Scorer> ext_scorer,
std::unordered_map<std::string, float> hot_words)
{
// assign special ids
abs_time_step_ = 0;
space_id_ = alphabet.GetSpaceLabel();
blank_id_ = alphabet.GetSize();
beam_size_ = beam_size;
cutoff_prob_ = cutoff_prob;
cutoff_top_n_ = cutoff_top_n;
ext_scorer_ = ext_scorer;
hot_words_ = hot_words;
start_expanding_ = false;
// init prefixes' root
PathTrie *root = new PathTrie;
root->score = root->log_prob_b_prev = 0.0;
prefix_root_.reset(root);
prefix_root_->timesteps = ×tep_tree_root_;
prefixes_.push_back(root);
if (ext_scorer && (bool)(ext_scorer_->dictionary)) {
// no need for std::make_shared<>() since Copy() does 'new' behind the doors
auto dict_ptr = std::shared_ptr<PathTrie::FstType>(ext_scorer->dictionary->Copy(true));
root->set_dictionary(dict_ptr);
auto matcher = std::make_shared<fst::SortedMatcher<PathTrie::FstType>>(*dict_ptr, fst::MATCH_INPUT);
root->set_matcher(matcher);
}
return 0;
}
void
DecoderState::next(const double *probs,
int time_dim,
int class_dim)
{
// prefix search over time
for (size_t rel_time_step = 0; rel_time_step < time_dim; ++rel_time_step, ++abs_time_step_) {
auto *prob = &probs[rel_time_step*class_dim];
// At the start of the decoding process, we delay beam expansion so that
// timings on the first letters is not incorrect. As soon as we see a
// timestep with blank probability lower than 0.999, we start expanding
// beams.
if (prob[blank_id_] < 0.999) {
start_expanding_ = true;
}
// If not expanding yet, just continue to next timestep.
if (!start_expanding_) {
continue;
}
float min_cutoff = -NUM_FLT_INF;
bool full_beam = false;
if (ext_scorer_) {
size_t num_prefixes = std::min(prefixes_.size(), beam_size_);
std::partial_sort(prefixes_.begin(),
prefixes_.begin() + num_prefixes,
prefixes_.end(),
prefix_compare);
min_cutoff = prefixes_[num_prefixes - 1]->score +
std::log(prob[blank_id_]) - std::max(0.0, ext_scorer_->beta);
full_beam = (num_prefixes == beam_size_);
}
std::vector<std::pair<size_t, float>> log_prob_idx =
get_pruned_log_probs(prob, class_dim, cutoff_prob_, cutoff_top_n_);
// loop over class dim
for (size_t index = 0; index < log_prob_idx.size(); index++) {
auto c = log_prob_idx[index].first;
auto log_prob_c = log_prob_idx[index].second;
for (size_t i = 0; i < prefixes_.size() && i < beam_size_; ++i) {
auto prefix = prefixes_[i];
if (full_beam && log_prob_c + prefix->score < min_cutoff) {
break;
}
if (prefix->score == -NUM_FLT_INF) {
continue;
}
assert(prefix->timesteps != nullptr);
// blank
if (c == blank_id_) {
// compute probability of current path
float log_p = log_prob_c + prefix->score;
// combine current path with previous ones with the same prefix
// the blank label comes last, so we can compare log_prob_nb_cur with log_p
if (prefix->log_prob_nb_cur < log_p) {
// keep current timesteps
prefix->previous_timesteps = nullptr;
}
prefix->log_prob_b_cur =
log_sum_exp(prefix->log_prob_b_cur, log_p);
continue;
}
// repeated character
if (c == prefix->character) {
// compute probability of current path
float log_p = log_prob_c + prefix->log_prob_nb_prev;
// combine current path with previous ones with the same prefix
if (prefix->log_prob_nb_cur < log_p) {
// keep current timesteps
prefix->previous_timesteps = nullptr;
}
prefix->log_prob_nb_cur = log_sum_exp(
prefix->log_prob_nb_cur, log_p);
}
// get new prefix
auto prefix_new = prefix->get_path_trie(c, log_prob_c);
if (prefix_new != nullptr) {
// compute probability of current path
float log_p = -NUM_FLT_INF;
if (c == prefix->character &&
prefix->log_prob_b_prev > -NUM_FLT_INF) {
log_p = log_prob_c + prefix->log_prob_b_prev;
} else if (c != prefix->character) {
log_p = log_prob_c + prefix->score;
}
if (ext_scorer_) {
// skip scoring the space in word based LMs
PathTrie* prefix_to_score;
if (ext_scorer_->is_utf8_mode()) {
prefix_to_score = prefix_new;
} else {
prefix_to_score = prefix;
}
// language model scoring
if (ext_scorer_->is_scoring_boundary(prefix_to_score, c)) {
float score = 0.0;
std::vector<std::string> ngram;
ngram = ext_scorer_->make_ngram(prefix_to_score);
float hot_boost = 0.0;
if (!hot_words_.empty()) {
std::unordered_map<std::string, float>::iterator iter;
// increase prob of prefix for every word
// that matches a word in the hot-words list
for (std::string word : ngram) {
iter = hot_words_.find(word);
if ( iter != hot_words_.end() ) {
// increase the log_cond_prob(prefix|LM)
hot_boost += iter->second;
}
}
}
bool bos = ngram.size() < ext_scorer_->get_max_order();
score = ( ext_scorer_->get_log_cond_prob(ngram, bos) + hot_boost ) * ext_scorer_->alpha;
log_p += score;
log_p += ext_scorer_->beta;
}
}
// combine current path with previous ones with the same prefix
if (prefix_new->log_prob_nb_cur < log_p) {
// record data needed to update timesteps
// the actual update will be done if nothing better is found
prefix_new->previous_timesteps = prefix->timesteps;
prefix_new->new_timestep = abs_time_step_;
}
prefix_new->log_prob_nb_cur =
log_sum_exp(prefix_new->log_prob_nb_cur, log_p);
}
} // end of loop over prefix
} // end of loop over alphabet
// update log probs
prefixes_.clear();
prefix_root_->iterate_to_vec(prefixes_);
// only preserve top beam_size prefixes
if (prefixes_.size() > beam_size_) {
std::nth_element(prefixes_.begin(),
prefixes_.begin() + beam_size_,
prefixes_.end(),
prefix_compare);
for (size_t i = beam_size_; i < prefixes_.size(); ++i) {
prefixes_[i]->remove();
}
// Remove the elements from std::vector
prefixes_.resize(beam_size_);
}
} // end of loop over time
}
std::vector<Output>
DecoderState::decode(size_t num_results) const
{
std::vector<PathTrie*> prefixes_copy = prefixes_;
std::unordered_map<const PathTrie*, float> scores;
for (PathTrie* prefix : prefixes_copy) {
scores[prefix] = prefix->score;
}
// score the last word of each prefix that doesn't end with space
if (ext_scorer_) {
for (size_t i = 0; i < beam_size_ && i < prefixes_copy.size(); ++i) {
PathTrie* prefix = prefixes_copy[i];
PathTrie* prefix_boundary = ext_scorer_->is_utf8_mode() ? prefix : prefix->parent;
if (prefix_boundary && !ext_scorer_->is_scoring_boundary(prefix_boundary, prefix->character)) {
float score = 0.0;
std::vector<std::string> ngram = ext_scorer_->make_ngram(prefix);
bool bos = ngram.size() < ext_scorer_->get_max_order();
score = ext_scorer_->get_log_cond_prob(ngram, bos) * ext_scorer_->alpha;
score += ext_scorer_->beta;
scores[prefix] += score;
}
}
}
using namespace std::placeholders;
size_t num_returned = std::min(prefixes_copy.size(), num_results);
std::partial_sort(prefixes_copy.begin(),
prefixes_copy.begin() + num_returned,
prefixes_copy.end(),
std::bind(prefix_compare_external, _1, _2, scores));
std::vector<Output> outputs;
outputs.reserve(num_returned);
for (size_t i = 0; i < num_returned; ++i) {
Output output;
prefixes_copy[i]->get_path_vec(output.tokens);
output.timesteps = get_history(prefixes_copy[i]->timesteps, ×tep_tree_root_);
assert(output.tokens.size() == output.timesteps.size());
output.confidence = scores[prefixes_copy[i]];
outputs.push_back(output);
}
return outputs;
}
std::vector<Output> ctc_beam_search_decoder(
const double *probs,
int time_dim,
int class_dim,
const Alphabet &alphabet,
size_t beam_size,
double cutoff_prob,
size_t cutoff_top_n,
std::shared_ptr<Scorer> ext_scorer,
std::unordered_map<std::string, float> hot_words,
size_t num_results)
{
VALID_CHECK_EQ(alphabet.GetSize()+1, class_dim, "Number of output classes in acoustic model does not match number of labels in the alphabet file. Alphabet file must be the same one that was used to train the acoustic model.");
DecoderState state;
state.init(alphabet, beam_size, cutoff_prob, cutoff_top_n, ext_scorer, hot_words);
state.next(probs, time_dim, class_dim);
return state.decode(num_results);
}
std::vector<std::vector<Output>>
ctc_beam_search_decoder_batch(
const double *probs,
int batch_size,
int time_dim,
int class_dim,
const int* seq_lengths,
int seq_lengths_size,
const Alphabet &alphabet,
size_t beam_size,
size_t num_processes,
double cutoff_prob,
size_t cutoff_top_n,
std::shared_ptr<Scorer> ext_scorer,
std::unordered_map<std::string, float> hot_words,
size_t num_results)
{
VALID_CHECK_GT(num_processes, 0, "num_processes must be nonnegative!");
VALID_CHECK_EQ(batch_size, seq_lengths_size, "must have one sequence length per batch element");
// thread pool
ThreadPool pool(num_processes);
// enqueue the tasks of decoding
std::vector<std::future<std::vector<Output>>> res;
for (size_t i = 0; i < batch_size; ++i) {
res.emplace_back(pool.enqueue(ctc_beam_search_decoder,
&probs[i*time_dim*class_dim],
seq_lengths[i],
class_dim,
alphabet,
beam_size,
cutoff_prob,
cutoff_top_n,
ext_scorer,
hot_words,
num_results));
}
// get decoding results
std::vector<std::vector<Output>> batch_results;
for (size_t i = 0; i < batch_size; ++i) {
batch_results.emplace_back(res[i].get());
}
return batch_results;
}
| 11,531
|
C++
|
.cpp
| 290
| 30.868966
| 228
| 0.580573
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,797
|
decoder_utils.cpp
|
mozilla_DeepSpeech/native_client/ctcdecode/decoder_utils.cpp
|
#include "decoder_utils.h"
#include <algorithm>
#include <cmath>
#include <limits>
std::vector<std::pair<size_t, float>> get_pruned_log_probs(
const double *prob_step,
size_t class_dim,
double cutoff_prob,
size_t cutoff_top_n) {
std::vector<std::pair<int, double>> prob_idx;
for (size_t i = 0; i < class_dim; ++i) {
prob_idx.push_back(std::pair<int, double>(i, prob_step[i]));
}
// pruning of vacobulary
size_t cutoff_len = class_dim;
if (cutoff_prob < 1.0 || cutoff_top_n < cutoff_len) {
std::sort(
prob_idx.begin(), prob_idx.end(), pair_comp_second_rev<int, double>);
if (cutoff_prob < 1.0) {
double cum_prob = 0.0;
cutoff_len = 0;
for (size_t i = 0; i < prob_idx.size(); ++i) {
cum_prob += prob_idx[i].second;
cutoff_len += 1;
if (cum_prob >= cutoff_prob || cutoff_len >= cutoff_top_n) break;
}
}
prob_idx = std::vector<std::pair<int, double>>(
prob_idx.begin(), prob_idx.begin() + cutoff_len);
}
std::vector<std::pair<size_t, float>> log_prob_idx;
for (size_t i = 0; i < cutoff_len; ++i) {
log_prob_idx.push_back(std::pair<int, float>(
prob_idx[i].first, log(prob_idx[i].second + NUM_FLT_MIN)));
}
return log_prob_idx;
}
size_t get_utf8_str_len(const std::string &str) {
size_t str_len = 0;
for (char c : str) {
str_len += ((c & 0xc0) != 0x80);
}
return str_len;
}
std::vector<std::string> split_into_codepoints(const std::string &str) {
std::vector<std::string> result;
std::string out_str;
for (char c : str) {
if (byte_is_codepoint_boundary(c)) {
if (!out_str.empty()) {
result.push_back(out_str);
out_str.clear();
}
}
out_str.append(1, c);
}
result.push_back(out_str);
return result;
}
std::vector<std::string> split_into_bytes(const std::string &str) {
std::vector<std::string> result;
for (char c : str) {
std::string ch(1, c);
result.push_back(ch);
}
return result;
}
std::vector<std::string> split_str(const std::string &s,
const std::string &delim) {
std::vector<std::string> result;
std::size_t start = 0, delim_len = delim.size();
while (true) {
std::size_t end = s.find(delim, start);
if (end == std::string::npos) {
if (start < s.size()) {
result.push_back(s.substr(start));
}
break;
}
if (end > start) {
result.push_back(s.substr(start, end - start));
}
start = end + delim_len;
}
return result;
}
bool prefix_compare(const PathTrie *x, const PathTrie *y) {
if (x->score == y->score) {
if (x->character == y->character) {
return false;
} else {
return (x->character < y->character);
}
} else {
return x->score > y->score;
}
}
bool prefix_compare_external(const PathTrie *x, const PathTrie *y, const std::unordered_map<const PathTrie*, float>& scores) {
if (scores.at(x) == scores.at(y)) {
if (x->character == y->character) {
return false;
} else {
return (x->character < y->character);
}
} else {
return scores.at(x) > scores.at(y);
}
}
void add_word_to_fst(const std::vector<unsigned int> &word,
fst::StdVectorFst *dictionary) {
if (dictionary->NumStates() == 0) {
fst::StdVectorFst::StateId start = dictionary->AddState();
assert(start == 0);
dictionary->SetStart(start);
}
fst::StdVectorFst::StateId src = dictionary->Start();
fst::StdVectorFst::StateId dst;
for (auto c : word) {
dst = dictionary->AddState();
dictionary->AddArc(src, fst::StdArc(c, c, 0, dst));
src = dst;
}
dictionary->SetFinal(dst, fst::StdArc::Weight::One());
}
bool add_word_to_dictionary(
const std::string &word,
const std::unordered_map<std::string, int> &char_map,
bool utf8,
int SPACE_ID,
fst::StdVectorFst *dictionary) {
auto characters = utf8 ? split_into_bytes(word) : split_into_codepoints(word);
std::vector<unsigned int> int_word;
for (auto &c : characters) {
auto int_c = char_map.find(c);
if (int_c != char_map.end()) {
int_word.push_back(int_c->second);
} else {
return false; // return without adding
}
}
if (!utf8) {
int_word.push_back(SPACE_ID);
}
add_word_to_fst(int_word, dictionary);
return true; // return with successful adding
}
| 4,374
|
C++
|
.cpp
| 146
| 25.349315
| 126
| 0.608882
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,798
|
scorer.cpp
|
mozilla_DeepSpeech/native_client/ctcdecode/scorer.cpp
|
#ifdef _MSC_VER
#include <stdlib.h>
#include <io.h>
#include <windows.h>
#define R_OK 4 /* Read permission. */
#define W_OK 2 /* Write permission. */
#define F_OK 0 /* Existence. */
#define access _access
#else /* _MSC_VER */
#include <unistd.h>
#endif
#include "scorer.h"
#include <iostream>
#include <fstream>
#include "lm/config.hh"
#include "lm/model.hh"
#include "lm/state.hh"
#include "util/string_piece.hh"
#include "decoder_utils.h"
static const int32_t MAGIC = 'TRIE';
static const int32_t FILE_VERSION = 6;
int
Scorer::init(const std::string& lm_path,
const Alphabet& alphabet)
{
set_alphabet(alphabet);
return load_lm(lm_path);
}
int
Scorer::init(const std::string& lm_path,
const std::string& alphabet_config_path)
{
int err = alphabet_.init(alphabet_config_path.c_str());
if (err != 0) {
return err;
}
setup_char_map();
return load_lm(lm_path);
}
void
Scorer::set_alphabet(const Alphabet& alphabet)
{
alphabet_ = alphabet;
setup_char_map();
}
void Scorer::setup_char_map()
{
// (Re-)Initialize character map
char_map_.clear();
SPACE_ID_ = alphabet_.GetSpaceLabel();
for (int i = 0; i < alphabet_.GetSize(); i++) {
// The initial state of FST is state 0, hence the index of chars in
// the FST should start from 1 to avoid the conflict with the initial
// state, otherwise wrong decoding results would be given.
char_map_[alphabet_.DecodeSingle(i)] = i + 1;
}
}
int Scorer::load_lm(const std::string& lm_path)
{
// Check if file is readable to avoid KenLM throwing an exception
const char* filename = lm_path.c_str();
if (access(filename, R_OK) != 0) {
return DS_ERR_SCORER_UNREADABLE;
}
// Check if the file format is valid to avoid KenLM throwing an exception
lm::ngram::ModelType model_type;
if (!lm::ngram::RecognizeBinary(filename, model_type)) {
return DS_ERR_SCORER_INVALID_LM;
}
// Load the LM
lm::ngram::Config config;
config.load_method = util::LoadMethod::LAZY;
language_model_.reset(lm::ngram::LoadVirtual(filename, config));
max_order_ = language_model_->Order();
uint64_t package_size;
{
util::scoped_fd fd(util::OpenReadOrThrow(filename));
package_size = util::SizeFile(fd.get());
}
uint64_t trie_offset = language_model_->GetEndOfSearchOffset();
if (package_size <= trie_offset) {
// File ends without a trie structure
return DS_ERR_SCORER_NO_TRIE;
}
// Read metadata and trie from file
std::ifstream fin(lm_path, std::ios::binary);
fin.seekg(trie_offset);
return load_trie(fin, lm_path);
}
int Scorer::load_trie(std::ifstream& fin, const std::string& file_path)
{
int magic;
fin.read(reinterpret_cast<char*>(&magic), sizeof(magic));
if (magic != MAGIC) {
std::cerr << "Error: Can't parse scorer file, invalid header. Try updating "
"your scorer file." << std::endl;
return DS_ERR_SCORER_INVALID_TRIE;
}
int version;
fin.read(reinterpret_cast<char*>(&version), sizeof(version));
if (version != FILE_VERSION) {
std::cerr << "Error: Scorer file version mismatch (" << version
<< " instead of expected " << FILE_VERSION
<< "). ";
if (version < FILE_VERSION) {
std::cerr << "Update your scorer file.";
} else {
std::cerr << "Downgrade your scorer file or update your version of DeepSpeech.";
}
std::cerr << std::endl;
return DS_ERR_SCORER_VERSION_MISMATCH;
}
fin.read(reinterpret_cast<char*>(&is_utf8_mode_), sizeof(is_utf8_mode_));
// Read hyperparameters from header
double alpha, beta;
fin.read(reinterpret_cast<char*>(&alpha), sizeof(alpha));
fin.read(reinterpret_cast<char*>(&beta), sizeof(beta));
reset_params(alpha, beta);
fst::FstReadOptions opt;
opt.mode = fst::FstReadOptions::MAP;
opt.source = file_path;
dictionary.reset(FstType::Read(fin, opt));
return DS_ERR_OK;
}
bool Scorer::save_dictionary(const std::string& path, bool append_instead_of_overwrite)
{
std::ios::openmode om;
if (append_instead_of_overwrite) {
om = std::ios::in|std::ios::out|std::ios::binary|std::ios::ate;
} else {
om = std::ios::out|std::ios::binary;
}
std::fstream fout(path, om);
if (!fout ||fout.bad()) {
std::cerr << "Error opening '" << path << "'" << std::endl;
return false;
}
fout.write(reinterpret_cast<const char*>(&MAGIC), sizeof(MAGIC));
if (fout.bad()) {
std::cerr << "Error writing MAGIC '" << path << "'" << std::endl;
return false;
}
fout.write(reinterpret_cast<const char*>(&FILE_VERSION), sizeof(FILE_VERSION));
if (fout.bad()) {
std::cerr << "Error writing FILE_VERSION '" << path << "'" << std::endl;
return false;
}
fout.write(reinterpret_cast<const char*>(&is_utf8_mode_), sizeof(is_utf8_mode_));
if (fout.bad()) {
std::cerr << "Error writing is_utf8_mode '" << path << "'" << std::endl;
return false;
}
fout.write(reinterpret_cast<const char*>(&alpha), sizeof(alpha));
if (fout.bad()) {
std::cerr << "Error writing alpha '" << path << "'" << std::endl;
return false;
}
fout.write(reinterpret_cast<const char*>(&beta), sizeof(beta));
if (fout.bad()) {
std::cerr << "Error writing beta '" << path << "'" << std::endl;
return false;
}
fst::FstWriteOptions opt;
opt.align = true;
opt.source = path;
return dictionary->Write(fout, opt);
}
bool Scorer::is_scoring_boundary(PathTrie* prefix, size_t new_label)
{
if (is_utf8_mode()) {
if (prefix->character == -1) {
return false;
}
unsigned char first_byte;
int distance_to_boundary = prefix->distance_to_codepoint_boundary(&first_byte, alphabet_);
int needed_bytes;
if ((first_byte >> 3) == 0x1E) {
needed_bytes = 4;
} else if ((first_byte >> 4) == 0x0E) {
needed_bytes = 3;
} else if ((first_byte >> 5) == 0x06) {
needed_bytes = 2;
} else if ((first_byte >> 7) == 0x00) {
needed_bytes = 1;
} else {
assert(false); // invalid byte sequence. should be unreachable, disallowed by vocabulary/trie
return false;
}
return distance_to_boundary == needed_bytes;
} else {
return new_label == SPACE_ID_;
}
}
double Scorer::get_log_cond_prob(const std::vector<std::string>& words,
bool bos,
bool eos)
{
return get_log_cond_prob(words.begin(), words.end(), bos, eos);
}
double Scorer::get_log_cond_prob(const std::vector<std::string>::const_iterator& begin,
const std::vector<std::string>::const_iterator& end,
bool bos,
bool eos)
{
const auto& vocab = language_model_->BaseVocabulary();
lm::ngram::State state_vec[2];
lm::ngram::State *in_state = &state_vec[0];
lm::ngram::State *out_state = &state_vec[1];
if (bos) {
language_model_->BeginSentenceWrite(in_state);
} else {
language_model_->NullContextWrite(in_state);
}
double cond_prob = 0.0;
for (auto it = begin; it != end; ++it) {
lm::WordIndex word_index = vocab.Index(*it);
// encounter OOV
if (word_index == lm::kUNK) {
return OOV_SCORE;
}
cond_prob = language_model_->BaseScore(in_state, word_index, out_state);
std::swap(in_state, out_state);
}
if (eos) {
cond_prob = language_model_->BaseScore(in_state, vocab.EndSentence(), out_state);
}
// return loge prob
return cond_prob/NUM_FLT_LOGE;
}
void Scorer::reset_params(float alpha, float beta)
{
this->alpha = alpha;
this->beta = beta;
}
std::vector<std::string> Scorer::split_labels_into_scored_units(const std::vector<unsigned int>& labels)
{
if (labels.empty()) return {};
std::string s = alphabet_.Decode(labels);
std::vector<std::string> words;
if (is_utf8_mode_) {
words = split_into_codepoints(s);
} else {
words = split_str(s, " ");
}
return words;
}
std::vector<std::string> Scorer::make_ngram(PathTrie* prefix)
{
std::vector<std::string> ngram;
PathTrie* current_node = prefix;
PathTrie* new_node = nullptr;
for (int order = 0; order < max_order_; order++) {
if (!current_node || current_node->character == -1) {
break;
}
std::vector<unsigned int> prefix_vec;
if (is_utf8_mode_) {
new_node = current_node->get_prev_grapheme(prefix_vec, alphabet_);
} else {
new_node = current_node->get_prev_word(prefix_vec, alphabet_);
}
current_node = new_node->parent;
// reconstruct word
std::string word = alphabet_.Decode(prefix_vec);
ngram.push_back(word);
}
std::reverse(ngram.begin(), ngram.end());
return ngram;
}
void Scorer::fill_dictionary(const std::unordered_set<std::string>& vocabulary)
{
// ConstFst is immutable, so we need to use a MutableFst to create the trie,
// and then we convert to a ConstFst for the decoder and for storing on disk.
fst::StdVectorFst dictionary;
// For each unigram convert to ints and put in trie
for (const auto& word : vocabulary) {
if (word != START_TOKEN && word != UNK_TOKEN && word != END_TOKEN) {
add_word_to_dictionary(word, char_map_, is_utf8_mode_, SPACE_ID_ + 1, &dictionary);
}
}
/* Simplify FST
* This gets rid of "epsilon" transitions in the FST.
* These are transitions that don't require a string input to be taken.
* Getting rid of them is necessary to make the FST deterministic, but
* can greatly increase the size of the FST
*/
fst::RmEpsilon(&dictionary);
std::unique_ptr<fst::StdVectorFst> new_dict(new fst::StdVectorFst);
/* This makes the FST deterministic, meaning for any string input there's
* only one possible state the FST could be in. It is assumed our
* dictionary is deterministic when using it.
* (lest we'd have to check for multiple transitions at each state)
*/
fst::Determinize(dictionary, new_dict.get());
/* Finds the simplest equivalent fst. This is unnecessary but decreases
* memory usage of the dictionary
*/
fst::Minimize(new_dict.get());
// Now we convert the MutableFst to a ConstFst (Scorer::FstType) via its ctor
std::unique_ptr<FstType> converted(new FstType(*new_dict));
this->dictionary = std::move(converted);
}
| 10,279
|
C++
|
.cpp
| 302
| 29.864238
| 104
| 0.651964
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,800
|
tfmodelstate.cc
|
mozilla_DeepSpeech/native_client/tfmodelstate.cc
|
#include "tfmodelstate.h"
#include "workspace_status.h"
using namespace tensorflow;
using std::vector;
TFModelState::TFModelState()
: ModelState()
, mmap_env_(nullptr)
, session_(nullptr)
{
}
TFModelState::~TFModelState()
{
if (session_) {
Status status = session_->Close();
if (!status.ok()) {
std::cerr << "Error closing TensorFlow session: " << status << std::endl;
}
}
}
int
TFModelState::init(const char* model_path)
{
int err = ModelState::init(model_path);
if (err != DS_ERR_OK) {
return err;
}
Status status;
SessionOptions options;
mmap_env_.reset(new MemmappedEnv(Env::Default()));
bool is_mmap = std::string(model_path).find(".pbmm") != std::string::npos;
if (!is_mmap) {
std::cerr << "Warning: reading entire model file into memory. Transform model file into an mmapped graph to reduce heap usage." << std::endl;
} else {
status = mmap_env_->InitializeFromFile(model_path);
if (!status.ok()) {
std::cerr << status << std::endl;
return DS_ERR_FAIL_INIT_MMAP;
}
options.config.mutable_graph_options()
->mutable_optimizer_options()
->set_opt_level(::OptimizerOptions::L0);
options.env = mmap_env_.get();
}
Session* session;
status = NewSession(options, &session);
if (!status.ok()) {
std::cerr << status << std::endl;
return DS_ERR_FAIL_INIT_SESS;
}
session_.reset(session);
if (is_mmap) {
status = ReadBinaryProto(mmap_env_.get(),
MemmappedFileSystem::kMemmappedPackageDefaultGraphDef,
&graph_def_);
} else {
status = ReadBinaryProto(Env::Default(), model_path, &graph_def_);
}
if (!status.ok()) {
std::cerr << status << std::endl;
return DS_ERR_FAIL_READ_PROTOBUF;
}
status = session_->Create(graph_def_);
if (!status.ok()) {
std::cerr << status << std::endl;
return DS_ERR_FAIL_CREATE_SESS;
}
std::vector<tensorflow::Tensor> version_output;
status = session_->Run({}, {
"metadata_version"
}, {}, &version_output);
if (!status.ok()) {
std::cerr << "Unable to fetch graph version: " << status << std::endl;
return DS_ERR_MODEL_INCOMPATIBLE;
}
int graph_version = version_output[0].scalar<int>()();
if (graph_version < ds_graph_version()) {
std::cerr << "Specified model file version (" << graph_version << ") is "
<< "incompatible with minimum version supported by this client ("
<< ds_graph_version() << "). See "
<< "https://github.com/mozilla/DeepSpeech/blob/"
<< ds_git_version() << "/doc/USING.rst#model-compatibility "
<< "for more information" << std::endl;
return DS_ERR_MODEL_INCOMPATIBLE;
}
std::vector<tensorflow::Tensor> metadata_outputs;
status = session_->Run({}, {
"metadata_sample_rate",
"metadata_feature_win_len",
"metadata_feature_win_step",
"metadata_beam_width",
"metadata_alphabet",
}, {}, &metadata_outputs);
if (!status.ok()) {
std::cout << "Unable to fetch metadata: " << status << std::endl;
return DS_ERR_MODEL_INCOMPATIBLE;
}
sample_rate_ = metadata_outputs[0].scalar<int>()();
int win_len_ms = metadata_outputs[1].scalar<int>()();
int win_step_ms = metadata_outputs[2].scalar<int>()();
audio_win_len_ = sample_rate_ * (win_len_ms / 1000.0);
audio_win_step_ = sample_rate_ * (win_step_ms / 1000.0);
int beam_width = metadata_outputs[3].scalar<int>()();
beam_width_ = (unsigned int)(beam_width);
string serialized_alphabet = metadata_outputs[4].scalar<tensorflow::tstring>()();
err = alphabet_.Deserialize(serialized_alphabet.data(), serialized_alphabet.size());
if (err != 0) {
return DS_ERR_INVALID_ALPHABET;
}
assert(sample_rate_ > 0);
assert(audio_win_len_ > 0);
assert(audio_win_step_ > 0);
assert(beam_width_ > 0);
assert(alphabet_.GetSize() > 0);
for (int i = 0; i < graph_def_.node_size(); ++i) {
NodeDef node = graph_def_.node(i);
if (node.name() == "input_node") {
const auto& shape = node.attr().at("shape").shape();
n_steps_ = shape.dim(1).size();
n_context_ = (shape.dim(2).size()-1)/2;
n_features_ = shape.dim(3).size();
mfcc_feats_per_timestep_ = shape.dim(2).size() * shape.dim(3).size();
} else if (node.name() == "previous_state_c") {
const auto& shape = node.attr().at("shape").shape();
state_size_ = shape.dim(1).size();
} else if (node.name() == "logits_shape") {
Tensor logits_shape = Tensor(DT_INT32, TensorShape({3}));
if (!logits_shape.FromProto(node.attr().at("value").tensor())) {
continue;
}
int final_dim_size = logits_shape.vec<int>()(2) - 1;
if (final_dim_size != alphabet_.GetSize()) {
std::cerr << "Error: Alphabet size does not match loaded model: alphabet "
<< "has size " << alphabet_.GetSize()
<< ", but model has " << final_dim_size
<< " classes in its output. Make sure you're passing an alphabet "
<< "file with the same size as the one used for training."
<< std::endl;
return DS_ERR_INVALID_ALPHABET;
}
}
}
if (n_context_ == -1 || n_features_ == -1) {
std::cerr << "Error: Could not infer input shape from model file. "
<< "Make sure input_node is a 4D tensor with shape "
<< "[batch_size=1, time, window_size, n_features]."
<< std::endl;
return DS_ERR_INVALID_SHAPE;
}
return DS_ERR_OK;
}
Tensor
tensor_from_vector(const std::vector<float>& vec, const TensorShape& shape)
{
Tensor ret(DT_FLOAT, shape);
auto ret_mapped = ret.flat<float>();
int i;
for (i = 0; i < vec.size(); ++i) {
ret_mapped(i) = vec[i];
}
for (; i < shape.num_elements(); ++i) {
ret_mapped(i) = 0.f;
}
return ret;
}
void
copy_tensor_to_vector(const Tensor& tensor, vector<float>& vec, int num_elements = -1)
{
auto tensor_mapped = tensor.flat<float>();
if (num_elements == -1) {
num_elements = tensor.shape().num_elements();
}
for (int i = 0; i < num_elements; ++i) {
vec.push_back(tensor_mapped(i));
}
}
void
TFModelState::infer(const std::vector<float>& mfcc,
unsigned int n_frames,
const std::vector<float>& previous_state_c,
const std::vector<float>& previous_state_h,
vector<float>& logits_output,
vector<float>& state_c_output,
vector<float>& state_h_output)
{
const size_t num_classes = alphabet_.GetSize() + 1; // +1 for blank
Tensor input = tensor_from_vector(mfcc, TensorShape({BATCH_SIZE, n_steps_, 2*n_context_+1, n_features_}));
Tensor previous_state_c_t = tensor_from_vector(previous_state_c, TensorShape({BATCH_SIZE, (long long)state_size_}));
Tensor previous_state_h_t = tensor_from_vector(previous_state_h, TensorShape({BATCH_SIZE, (long long)state_size_}));
Tensor input_lengths(DT_INT32, TensorShape({1}));
input_lengths.scalar<int>()() = n_frames;
vector<Tensor> outputs;
Status status = session_->Run(
{
{"input_node", input},
{"input_lengths", input_lengths},
{"previous_state_c", previous_state_c_t},
{"previous_state_h", previous_state_h_t}
},
{"logits", "new_state_c", "new_state_h"},
{},
&outputs);
if (!status.ok()) {
std::cerr << "Error running session: " << status << "\n";
return;
}
copy_tensor_to_vector(outputs[0], logits_output, n_frames * BATCH_SIZE * num_classes);
state_c_output.clear();
state_c_output.reserve(state_size_);
copy_tensor_to_vector(outputs[1], state_c_output);
state_h_output.clear();
state_h_output.reserve(state_size_);
copy_tensor_to_vector(outputs[2], state_h_output);
}
void
TFModelState::compute_mfcc(const vector<float>& samples, vector<float>& mfcc_output)
{
Tensor input = tensor_from_vector(samples, TensorShape({audio_win_len_}));
vector<Tensor> outputs;
Status status = session_->Run({{"input_samples", input}}, {"mfccs"}, {}, &outputs);
if (!status.ok()) {
std::cerr << "Error running session: " << status << "\n";
return;
}
// The feature computation graph is hardcoded to one audio length for now
const int n_windows = 1;
assert(outputs[0].shape().num_elements() / n_features_ == n_windows);
copy_tensor_to_vector(outputs[0], mfcc_output);
}
| 8,431
|
C++
|
.cc
| 228
| 31.70614
| 145
| 0.620791
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,801
|
deepspeech_errors.cc
|
mozilla_DeepSpeech/native_client/deepspeech_errors.cc
|
#include "deepspeech.h"
#include <string.h>
char*
DS_ErrorCodeToErrorMessage(int aErrorCode)
{
#define RETURN_MESSAGE(NAME, VALUE, DESC) \
case NAME: \
return strdup(DESC);
switch(aErrorCode)
{
DS_FOR_EACH_ERROR(RETURN_MESSAGE)
default:
return strdup("Unknown error, please make sure you are using the correct native binary.");
}
#undef RETURN_MESSAGE
}
| 387
|
C++
|
.cc
| 16
| 21.125
| 96
| 0.730978
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,802
|
deepspeech.cc
|
mozilla_DeepSpeech/native_client/deepspeech.cc
|
#include <algorithm>
#ifdef _MSC_VER
#define _USE_MATH_DEFINES
#endif
#include <cmath>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "deepspeech.h"
#include "alphabet.h"
#include "modelstate.h"
#include "workspace_status.h"
#ifndef USE_TFLITE
#include "tfmodelstate.h"
#else
#include "tflitemodelstate.h"
#endif // USE_TFLITE
#include "ctcdecode/ctc_beam_search_decoder.h"
#ifdef __ANDROID__
#include <android/log.h>
#define LOG_TAG "libdeepspeech"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#else
#define LOGD(...)
#define LOGE(...)
#endif // __ANDROID__
using std::vector;
/* This is the implementation of the streaming inference API.
The streaming process uses three buffers that are fed eagerly as audio data
is fed in. The buffers only hold the minimum amount of data needed to do a
step in the acoustic model. The three buffers which live in StreamingState
are:
- audio_buffer, used to buffer audio samples until there's enough data to
compute input features for a single window.
- mfcc_buffer, used to buffer input features until there's enough data for
a single timestep. Remember there's overlap in the features, each timestep
contains n_context past feature frames, the current feature frame, and
n_context future feature frames, for a total of 2*n_context + 1 feature
frames per timestep.
- batch_buffer, used to buffer timesteps until there's enough data to compute
a batch of n_steps.
Data flows through all three buffers as audio samples are fed via the public
API. When audio_buffer is full, features are computed from it and pushed to
mfcc_buffer. When mfcc_buffer is full, the timestep is copied to batch_buffer.
When batch_buffer is full, we do a single step through the acoustic model
and accumulate the intermediate decoding state in the DecoderState structure.
When finishStream() is called, we return the corresponding transcript from
the current decoder state.
*/
struct StreamingState {
vector<float> audio_buffer_;
vector<float> mfcc_buffer_;
vector<float> batch_buffer_;
vector<float> previous_state_c_;
vector<float> previous_state_h_;
ModelState* model_;
DecoderState decoder_state_;
StreamingState();
~StreamingState();
void feedAudioContent(const short* buffer, unsigned int buffer_size);
char* intermediateDecode() const;
Metadata* intermediateDecodeWithMetadata(unsigned int num_results) const;
void finalizeStream();
char* finishStream();
Metadata* finishStreamWithMetadata(unsigned int num_results);
void processAudioWindow(const vector<float>& buf);
void processMfccWindow(const vector<float>& buf);
void pushMfccBuffer(const vector<float>& buf);
void addZeroMfccWindow();
void processBatch(const vector<float>& buf, unsigned int n_steps);
};
StreamingState::StreamingState()
{
}
StreamingState::~StreamingState()
{
}
template<typename T>
void
shift_buffer_left(vector<T>& buf, int shift_amount)
{
std::rotate(buf.begin(), buf.begin() + shift_amount, buf.end());
buf.resize(buf.size() - shift_amount);
}
void
StreamingState::feedAudioContent(const short* buffer,
unsigned int buffer_size)
{
// Consume all the data that was passed in, processing full buffers if needed
while (buffer_size > 0) {
while (buffer_size > 0 && audio_buffer_.size() < model_->audio_win_len_) {
// Convert i16 sample into f32
float multiplier = 1.0f / (1 << 15);
audio_buffer_.push_back((float)(*buffer) * multiplier);
++buffer;
--buffer_size;
}
// If the buffer is full, process and shift it
if (audio_buffer_.size() == model_->audio_win_len_) {
processAudioWindow(audio_buffer_);
// Shift data by one step
shift_buffer_left(audio_buffer_, model_->audio_win_step_);
}
// Repeat until buffer empty
}
}
char*
StreamingState::intermediateDecode() const
{
return model_->decode(decoder_state_);
}
Metadata*
StreamingState::intermediateDecodeWithMetadata(unsigned int num_results) const
{
return model_->decode_metadata(decoder_state_, num_results);
}
char*
StreamingState::finishStream()
{
finalizeStream();
return model_->decode(decoder_state_);
}
Metadata*
StreamingState::finishStreamWithMetadata(unsigned int num_results)
{
finalizeStream();
return model_->decode_metadata(decoder_state_, num_results);
}
void
StreamingState::processAudioWindow(const vector<float>& buf)
{
// Compute MFCC features
vector<float> mfcc;
mfcc.reserve(model_->n_features_);
model_->compute_mfcc(buf, mfcc);
pushMfccBuffer(mfcc);
}
void
StreamingState::finalizeStream()
{
// Flush audio buffer
processAudioWindow(audio_buffer_);
// Add empty mfcc vectors at end of sample
for (int i = 0; i < model_->n_context_; ++i) {
addZeroMfccWindow();
}
// Process final batch
if (batch_buffer_.size() > 0) {
processBatch(batch_buffer_, batch_buffer_.size()/model_->mfcc_feats_per_timestep_);
}
}
void
StreamingState::addZeroMfccWindow()
{
vector<float> zero_buffer(model_->n_features_, 0.f);
pushMfccBuffer(zero_buffer);
}
template<typename InputIt, typename OutputIt>
InputIt
copy_up_to_n(InputIt from_begin, InputIt from_end, OutputIt to_begin, int max_elems)
{
int next_copy_amount = std::min<int>(std::distance(from_begin, from_end), max_elems);
std::copy_n(from_begin, next_copy_amount, to_begin);
return from_begin + next_copy_amount;
}
void
StreamingState::pushMfccBuffer(const vector<float>& buf)
{
auto start = buf.begin();
auto end = buf.end();
while (start != end) {
// Copy from input buffer to mfcc_buffer, stopping if we have a full context window
start = copy_up_to_n(start, end, std::back_inserter(mfcc_buffer_),
model_->mfcc_feats_per_timestep_ - mfcc_buffer_.size());
assert(mfcc_buffer_.size() <= model_->mfcc_feats_per_timestep_);
// If we have a full context window
if (mfcc_buffer_.size() == model_->mfcc_feats_per_timestep_) {
processMfccWindow(mfcc_buffer_);
// Shift data by one step of one mfcc feature vector
shift_buffer_left(mfcc_buffer_, model_->n_features_);
}
}
}
void
StreamingState::processMfccWindow(const vector<float>& buf)
{
auto start = buf.begin();
auto end = buf.end();
while (start != end) {
// Copy from input buffer to batch_buffer, stopping if we have a full batch
start = copy_up_to_n(start, end, std::back_inserter(batch_buffer_),
model_->n_steps_ * model_->mfcc_feats_per_timestep_ - batch_buffer_.size());
assert(batch_buffer_.size() <= model_->n_steps_ * model_->mfcc_feats_per_timestep_);
// If we have a full batch
if (batch_buffer_.size() == model_->n_steps_ * model_->mfcc_feats_per_timestep_) {
processBatch(batch_buffer_, model_->n_steps_);
batch_buffer_.resize(0);
}
}
}
void
StreamingState::processBatch(const vector<float>& buf, unsigned int n_steps)
{
vector<float> logits;
model_->infer(buf,
n_steps,
previous_state_c_,
previous_state_h_,
logits,
previous_state_c_,
previous_state_h_);
const size_t num_classes = model_->alphabet_.GetSize() + 1; // +1 for blank
const int n_frames = logits.size() / (ModelState::BATCH_SIZE * num_classes);
// Convert logits to double
vector<double> inputs(logits.begin(), logits.end());
decoder_state_.next(inputs.data(),
n_frames,
num_classes);
}
int
DS_CreateModel(const char* aModelPath,
ModelState** retval)
{
*retval = nullptr;
std::cerr << "TensorFlow: " << tf_local_git_version() << std::endl;
std::cerr << "DeepSpeech: " << ds_git_version() << std::endl;
#ifdef __ANDROID__
LOGE("TensorFlow: %s", tf_local_git_version());
LOGD("TensorFlow: %s", tf_local_git_version());
LOGE("DeepSpeech: %s", ds_git_version());
LOGD("DeepSpeech: %s", ds_git_version());
#endif
if (!aModelPath || strlen(aModelPath) < 1) {
std::cerr << "No model specified, cannot continue." << std::endl;
return DS_ERR_NO_MODEL;
}
std::unique_ptr<ModelState> model(
#ifndef USE_TFLITE
new TFModelState()
#else
new TFLiteModelState()
#endif
);
if (!model) {
std::cerr << "Could not allocate model state." << std::endl;
return DS_ERR_FAIL_CREATE_MODEL;
}
int err = model->init(aModelPath);
if (err != DS_ERR_OK) {
return err;
}
*retval = model.release();
return DS_ERR_OK;
}
unsigned int
DS_GetModelBeamWidth(const ModelState* aCtx)
{
return aCtx->beam_width_;
}
int
DS_SetModelBeamWidth(ModelState* aCtx, unsigned int aBeamWidth)
{
aCtx->beam_width_ = aBeamWidth;
return 0;
}
int
DS_GetModelSampleRate(const ModelState* aCtx)
{
return aCtx->sample_rate_;
}
void
DS_FreeModel(ModelState* ctx)
{
delete ctx;
}
int
DS_EnableExternalScorer(ModelState* aCtx,
const char* aScorerPath)
{
std::unique_ptr<Scorer> scorer(new Scorer());
int err = scorer->init(aScorerPath, aCtx->alphabet_);
if (err != 0) {
return DS_ERR_INVALID_SCORER;
}
aCtx->scorer_ = std::move(scorer);
return DS_ERR_OK;
}
int
DS_AddHotWord(ModelState* aCtx,
const char* word,
float boost)
{
if (aCtx->scorer_) {
const int size_before = aCtx->hot_words_.size();
aCtx->hot_words_.insert( std::pair<std::string,float> (word, boost) );
const int size_after = aCtx->hot_words_.size();
if (size_before == size_after) {
return DS_ERR_FAIL_INSERT_HOTWORD;
}
return DS_ERR_OK;
}
return DS_ERR_SCORER_NOT_ENABLED;
}
int
DS_EraseHotWord(ModelState* aCtx,
const char* word)
{
if (aCtx->scorer_) {
const int size_before = aCtx->hot_words_.size();
int err = aCtx->hot_words_.erase(word);
const int size_after = aCtx->hot_words_.size();
if (size_before == size_after) {
return DS_ERR_FAIL_ERASE_HOTWORD;
}
return DS_ERR_OK;
}
return DS_ERR_SCORER_NOT_ENABLED;
}
int
DS_ClearHotWords(ModelState* aCtx)
{
if (aCtx->scorer_) {
aCtx->hot_words_.clear();
const int size_after = aCtx->hot_words_.size();
if (size_after != 0) {
return DS_ERR_FAIL_CLEAR_HOTWORD;
}
return DS_ERR_OK;
}
return DS_ERR_SCORER_NOT_ENABLED;
}
int
DS_DisableExternalScorer(ModelState* aCtx)
{
if (aCtx->scorer_) {
aCtx->scorer_.reset();
return DS_ERR_OK;
}
return DS_ERR_SCORER_NOT_ENABLED;
}
int DS_SetScorerAlphaBeta(ModelState* aCtx,
float aAlpha,
float aBeta)
{
if (aCtx->scorer_) {
aCtx->scorer_->reset_params(aAlpha, aBeta);
return DS_ERR_OK;
}
return DS_ERR_SCORER_NOT_ENABLED;
}
int
DS_CreateStream(ModelState* aCtx,
StreamingState** retval)
{
*retval = nullptr;
std::unique_ptr<StreamingState> ctx(new StreamingState());
if (!ctx) {
std::cerr << "Could not allocate streaming state." << std::endl;
return DS_ERR_FAIL_CREATE_STREAM;
}
ctx->audio_buffer_.reserve(aCtx->audio_win_len_);
ctx->mfcc_buffer_.reserve(aCtx->mfcc_feats_per_timestep_);
ctx->mfcc_buffer_.resize(aCtx->n_features_*aCtx->n_context_, 0.f);
ctx->batch_buffer_.reserve(aCtx->n_steps_ * aCtx->mfcc_feats_per_timestep_);
ctx->previous_state_c_.resize(aCtx->state_size_, 0.f);
ctx->previous_state_h_.resize(aCtx->state_size_, 0.f);
ctx->model_ = aCtx;
const int cutoff_top_n = 40;
const double cutoff_prob = 1.0;
ctx->decoder_state_.init(aCtx->alphabet_,
aCtx->beam_width_,
cutoff_prob,
cutoff_top_n,
aCtx->scorer_,
aCtx->hot_words_);
*retval = ctx.release();
return DS_ERR_OK;
}
void
DS_FeedAudioContent(StreamingState* aSctx,
const short* aBuffer,
unsigned int aBufferSize)
{
aSctx->feedAudioContent(aBuffer, aBufferSize);
}
char*
DS_IntermediateDecode(const StreamingState* aSctx)
{
return aSctx->intermediateDecode();
}
Metadata*
DS_IntermediateDecodeWithMetadata(const StreamingState* aSctx,
unsigned int aNumResults)
{
return aSctx->intermediateDecodeWithMetadata(aNumResults);
}
char*
DS_FinishStream(StreamingState* aSctx)
{
char* str = aSctx->finishStream();
DS_FreeStream(aSctx);
return str;
}
Metadata*
DS_FinishStreamWithMetadata(StreamingState* aSctx,
unsigned int aNumResults)
{
Metadata* result = aSctx->finishStreamWithMetadata(aNumResults);
DS_FreeStream(aSctx);
return result;
}
StreamingState*
CreateStreamAndFeedAudioContent(ModelState* aCtx,
const short* aBuffer,
unsigned int aBufferSize)
{
StreamingState* ctx;
int status = DS_CreateStream(aCtx, &ctx);
if (status != DS_ERR_OK) {
return nullptr;
}
DS_FeedAudioContent(ctx, aBuffer, aBufferSize);
return ctx;
}
char*
DS_SpeechToText(ModelState* aCtx,
const short* aBuffer,
unsigned int aBufferSize)
{
StreamingState* ctx = CreateStreamAndFeedAudioContent(aCtx, aBuffer, aBufferSize);
return DS_FinishStream(ctx);
}
Metadata*
DS_SpeechToTextWithMetadata(ModelState* aCtx,
const short* aBuffer,
unsigned int aBufferSize,
unsigned int aNumResults)
{
StreamingState* ctx = CreateStreamAndFeedAudioContent(aCtx, aBuffer, aBufferSize);
return DS_FinishStreamWithMetadata(ctx, aNumResults);
}
void
DS_FreeStream(StreamingState* aSctx)
{
delete aSctx;
}
void
DS_FreeMetadata(Metadata* m)
{
if (m) {
for (int i = 0; i < m->num_transcripts; ++i) {
for (int j = 0; j < m->transcripts[i].num_tokens; ++j) {
free((void*)m->transcripts[i].tokens[j].text);
}
free((void*)m->transcripts[i].tokens);
}
free((void*)m->transcripts);
free(m);
}
}
void
DS_FreeString(char* str)
{
free(str);
}
char*
DS_Version()
{
return strdup(ds_version());
}
| 14,299
|
C++
|
.cc
| 473
| 25.877378
| 101
| 0.678717
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,803
|
modelstate.cc
|
mozilla_DeepSpeech/native_client/modelstate.cc
|
#include <vector>
#include "ctcdecode/ctc_beam_search_decoder.h"
#include "modelstate.h"
using std::vector;
ModelState::ModelState()
: beam_width_(-1)
, n_steps_(-1)
, n_context_(-1)
, n_features_(-1)
, mfcc_feats_per_timestep_(-1)
, sample_rate_(-1)
, audio_win_len_(-1)
, audio_win_step_(-1)
, state_size_(-1)
{
}
ModelState::~ModelState()
{
}
int
ModelState::init(const char* model_path)
{
return DS_ERR_OK;
}
char*
ModelState::decode(const DecoderState& state) const
{
vector<Output> out = state.decode();
return strdup(alphabet_.Decode(out[0].tokens).c_str());
}
Metadata*
ModelState::decode_metadata(const DecoderState& state,
size_t num_results)
{
vector<Output> out = state.decode(num_results);
unsigned int num_returned = out.size();
CandidateTranscript* transcripts = (CandidateTranscript*)malloc(sizeof(CandidateTranscript)*num_returned);
for (int i = 0; i < num_returned; ++i) {
TokenMetadata* tokens = (TokenMetadata*)malloc(sizeof(TokenMetadata)*out[i].tokens.size());
for (int j = 0; j < out[i].tokens.size(); ++j) {
TokenMetadata token {
strdup(alphabet_.DecodeSingle(out[i].tokens[j]).c_str()), // text
static_cast<unsigned int>(out[i].timesteps[j]), // timestep
out[i].timesteps[j] * ((float)audio_win_step_ / sample_rate_), // start_time
};
memcpy(&tokens[j], &token, sizeof(TokenMetadata));
}
CandidateTranscript transcript {
tokens, // tokens
static_cast<unsigned int>(out[i].tokens.size()), // num_tokens
out[i].confidence, // confidence
};
memcpy(&transcripts[i], &transcript, sizeof(CandidateTranscript));
}
Metadata* ret = (Metadata*)malloc(sizeof(Metadata));
Metadata metadata {
transcripts, // transcripts
num_returned, // num_transcripts
};
memcpy(ret, &metadata, sizeof(Metadata));
return ret;
}
| 1,992
|
C++
|
.cc
| 62
| 28.258065
| 108
| 0.638498
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,804
|
tflitemodelstate.cc
|
mozilla_DeepSpeech/native_client/tflitemodelstate.cc
|
#include "tflitemodelstate.h"
#include "tensorflow/lite/string_util.h"
#include "workspace_status.h"
#ifdef __ANDROID__
#include <android/log.h>
#define LOG_TAG "libdeepspeech"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#else
#define LOGD(...)
#define LOGE(...)
#endif // __ANDROID__
using namespace tflite;
using std::vector;
int
TFLiteModelState::get_tensor_by_name(const vector<int>& list,
const char* name)
{
int rv = -1;
for (int i = 0; i < list.size(); ++i) {
const string& node_name = interpreter_->tensor(list[i])->name;
if (node_name.compare(string(name)) == 0) {
rv = i;
}
}
assert(rv >= 0);
return rv;
}
int
TFLiteModelState::get_input_tensor_by_name(const char* name)
{
int idx = get_tensor_by_name(interpreter_->inputs(), name);
return interpreter_->inputs()[idx];
}
int
TFLiteModelState::get_output_tensor_by_name(const char* name)
{
int idx = get_tensor_by_name(interpreter_->outputs(), name);
return interpreter_->outputs()[idx];
}
void
push_back_if_not_present(std::deque<int>& list, int value)
{
if (std::find(list.begin(), list.end(), value) == list.end()) {
list.push_back(value);
}
}
// Backwards BFS on the node DAG. At each iteration we get the next tensor id
// from the frontier list, then for each node which has that tensor id as an
// output, add it to the parent list, and add its input tensors to the frontier
// list. Because we start from the final tensor and work backwards to the inputs,
// the parents list is constructed in reverse, adding elements to its front.
vector<int>
TFLiteModelState::find_parent_node_ids(int tensor_id)
{
std::deque<int> parents;
std::deque<int> frontier;
frontier.push_back(tensor_id);
while (!frontier.empty()) {
int next_tensor_id = frontier.front();
frontier.pop_front();
// Find all nodes that have next_tensor_id as an output
for (int node_id = 0; node_id < interpreter_->nodes_size(); ++node_id) {
TfLiteNode node = interpreter_->node_and_registration(node_id)->first;
// Search node outputs for the tensor we're looking for
for (int i = 0; i < node.outputs->size; ++i) {
if (node.outputs->data[i] == next_tensor_id) {
// This node is part of the parent tree, add it to the parent list and
// add its input tensors to the frontier list
parents.push_front(node_id);
for (int j = 0; j < node.inputs->size; ++j) {
push_back_if_not_present(frontier, node.inputs->data[j]);
}
}
}
}
}
return vector<int>(parents.begin(), parents.end());
}
TFLiteModelState::TFLiteModelState()
: ModelState()
, interpreter_(nullptr)
, fbmodel_(nullptr)
{
}
TFLiteModelState::~TFLiteModelState()
{
}
std::map<std::string, tflite::Interpreter::TfLiteDelegatePtr>
getTfliteDelegates()
{
std::map<std::string, tflite::Interpreter::TfLiteDelegatePtr> delegates;
const char* env_delegate_c = std::getenv("DS_TFLITE_DELEGATE");
std::string env_delegate = (env_delegate_c != nullptr) ? env_delegate_c : "";
#ifdef __ANDROID__
if (env_delegate == std::string("gpu")) {
LOGD("Trying to get GPU delegate ...");
// Try to get GPU delegate
{
tflite::Interpreter::TfLiteDelegatePtr delegate = evaluation::CreateGPUDelegate();
if (!delegate) {
LOGD("GPU delegation not supported");
} else {
LOGD("GPU delegation supported");
delegates.emplace("GPU", std::move(delegate));
}
}
}
if (env_delegate == std::string("nnapi")) {
LOGD("Trying to get NNAPI delegate ...");
// Try to get Android NNAPI delegate
{
tflite::Interpreter::TfLiteDelegatePtr delegate = evaluation::CreateNNAPIDelegate();
if (!delegate) {
LOGD("NNAPI delegation not supported");
} else {
LOGD("NNAPI delegation supported");
delegates.emplace("NNAPI", std::move(delegate));
}
}
}
if (env_delegate == std::string("hexagon")) {
LOGD("Trying to get Hexagon delegate ...");
// Try to get Android Hexagon delegate
{
const std::string libhexagon_path("/data/local/tmp");
tflite::Interpreter::TfLiteDelegatePtr delegate = evaluation::CreateHexagonDelegate(libhexagon_path, /* profiler */ false);
if (!delegate) {
LOGD("Hexagon delegation not supported");
} else {
LOGD("Hexagon delegation supported");
delegates.emplace("Hexagon", std::move(delegate));
}
}
}
#endif // __ANDROID__
return delegates;
}
int
TFLiteModelState::init(const char* model_path)
{
int err = ModelState::init(model_path);
if (err != DS_ERR_OK) {
return err;
}
fbmodel_ = tflite::FlatBufferModel::BuildFromFile(model_path);
if (!fbmodel_) {
std::cerr << "Error at reading model file " << model_path << std::endl;
return DS_ERR_FAIL_INIT_MMAP;
}
tflite::ops::builtin::BuiltinOpResolver resolver;
tflite::InterpreterBuilder(*fbmodel_, resolver)(&interpreter_);
if (!interpreter_) {
std::cerr << "Error at InterpreterBuilder for model file " << model_path << std::endl;
return DS_ERR_FAIL_INTERPRETER;
}
LOGD("Trying to detect delegates ...");
std::map<std::string, tflite::Interpreter::TfLiteDelegatePtr> delegates = getTfliteDelegates();
LOGD("Finished enumerating delegates ...");
interpreter_->AllocateTensors();
interpreter_->SetNumThreads(4);
LOGD("Trying to use delegates ...");
for (const auto& delegate : delegates) {
LOGD("Trying to apply delegate %s", delegate.first.c_str());
if (interpreter_->ModifyGraphWithDelegate(delegate.second.get()) != kTfLiteOk) {
LOGD("FAILED to apply delegate %s to the graph", delegate.first.c_str());
}
}
// Query all the index once
input_node_idx_ = get_input_tensor_by_name("input_node");
previous_state_c_idx_ = get_input_tensor_by_name("previous_state_c");
previous_state_h_idx_ = get_input_tensor_by_name("previous_state_h");
input_samples_idx_ = get_input_tensor_by_name("input_samples");
logits_idx_ = get_output_tensor_by_name("logits");
new_state_c_idx_ = get_output_tensor_by_name("new_state_c");
new_state_h_idx_ = get_output_tensor_by_name("new_state_h");
mfccs_idx_ = get_output_tensor_by_name("mfccs");
int metadata_version_idx = get_output_tensor_by_name("metadata_version");
int metadata_sample_rate_idx = get_output_tensor_by_name("metadata_sample_rate");
int metadata_feature_win_len_idx = get_output_tensor_by_name("metadata_feature_win_len");
int metadata_feature_win_step_idx = get_output_tensor_by_name("metadata_feature_win_step");
int metadata_beam_width_idx = get_output_tensor_by_name("metadata_beam_width");
int metadata_alphabet_idx = get_output_tensor_by_name("metadata_alphabet");
std::vector<int> metadata_exec_plan;
metadata_exec_plan.push_back(find_parent_node_ids(metadata_version_idx)[0]);
metadata_exec_plan.push_back(find_parent_node_ids(metadata_sample_rate_idx)[0]);
metadata_exec_plan.push_back(find_parent_node_ids(metadata_feature_win_len_idx)[0]);
metadata_exec_plan.push_back(find_parent_node_ids(metadata_feature_win_step_idx)[0]);
metadata_exec_plan.push_back(find_parent_node_ids(metadata_beam_width_idx)[0]);
metadata_exec_plan.push_back(find_parent_node_ids(metadata_alphabet_idx)[0]);
for (int i = 0; i < metadata_exec_plan.size(); ++i) {
assert(metadata_exec_plan[i] > -1);
}
// When we call Interpreter::Invoke, the whole graph is executed by default,
// which means every time compute_mfcc is called the entire acoustic model is
// also executed. To workaround that problem, we walk up the dependency DAG
// from the mfccs output tensor to find all the relevant nodes required for
// feature computation, building an execution plan that runs just those nodes.
auto mfcc_plan = find_parent_node_ids(mfccs_idx_);
auto orig_plan = interpreter_->execution_plan();
// Remove MFCC and Metatda nodes from original plan (all nodes) to create the acoustic model plan
auto erase_begin = std::remove_if(orig_plan.begin(), orig_plan.end(), [&mfcc_plan, &metadata_exec_plan](int elem) {
return (std::find(mfcc_plan.begin(), mfcc_plan.end(), elem) != mfcc_plan.end()
|| std::find(metadata_exec_plan.begin(), metadata_exec_plan.end(), elem) != metadata_exec_plan.end());
});
orig_plan.erase(erase_begin, orig_plan.end());
acoustic_exec_plan_ = std::move(orig_plan);
mfcc_exec_plan_ = std::move(mfcc_plan);
interpreter_->SetExecutionPlan(metadata_exec_plan);
TfLiteStatus status = interpreter_->Invoke();
if (status != kTfLiteOk) {
std::cerr << "Error running session: " << status << "\n";
return DS_ERR_FAIL_INTERPRETER;
}
int* const graph_version = interpreter_->typed_tensor<int>(metadata_version_idx);
if (graph_version == nullptr) {
std::cerr << "Unable to read model file version." << std::endl;
return DS_ERR_MODEL_INCOMPATIBLE;
}
if (*graph_version < ds_graph_version()) {
std::cerr << "Specified model file version (" << *graph_version << ") is "
<< "incompatible with minimum version supported by this client ("
<< ds_graph_version() << "). See "
<< "https://github.com/mozilla/DeepSpeech/blob/"
<< ds_git_version() << "/doc/USING.rst#model-compatibility "
<< "for more information" << std::endl;
return DS_ERR_MODEL_INCOMPATIBLE;
}
int* const model_sample_rate = interpreter_->typed_tensor<int>(metadata_sample_rate_idx);
if (model_sample_rate == nullptr) {
std::cerr << "Unable to read model sample rate." << std::endl;
return DS_ERR_MODEL_INCOMPATIBLE;
}
sample_rate_ = *model_sample_rate;
int* const win_len_ms = interpreter_->typed_tensor<int>(metadata_feature_win_len_idx);
int* const win_step_ms = interpreter_->typed_tensor<int>(metadata_feature_win_step_idx);
if (win_len_ms == nullptr || win_step_ms == nullptr) {
std::cerr << "Unable to read model feature window informations." << std::endl;
return DS_ERR_MODEL_INCOMPATIBLE;
}
audio_win_len_ = sample_rate_ * (*win_len_ms / 1000.0);
audio_win_step_ = sample_rate_ * (*win_step_ms / 1000.0);
int* const beam_width = interpreter_->typed_tensor<int>(metadata_beam_width_idx);
beam_width_ = (unsigned int)(*beam_width);
tflite::StringRef serialized_alphabet = tflite::GetString(interpreter_->tensor(metadata_alphabet_idx), 0);
err = alphabet_.Deserialize(serialized_alphabet.str, serialized_alphabet.len);
if (err != 0) {
return DS_ERR_INVALID_ALPHABET;
}
assert(sample_rate_ > 0);
assert(audio_win_len_ > 0);
assert(audio_win_step_ > 0);
assert(beam_width_ > 0);
assert(alphabet_.GetSize() > 0);
TfLiteIntArray* dims_input_node = interpreter_->tensor(input_node_idx_)->dims;
n_steps_ = dims_input_node->data[1];
n_context_ = (dims_input_node->data[2] - 1) / 2;
n_features_ = dims_input_node->data[3];
mfcc_feats_per_timestep_ = dims_input_node->data[2] * dims_input_node->data[3];
TfLiteIntArray* dims_logits = interpreter_->tensor(logits_idx_)->dims;
const int final_dim_size = dims_logits->data[1] - 1;
if (final_dim_size != alphabet_.GetSize()) {
std::cerr << "Error: Alphabet size does not match loaded model: alphabet "
<< "has size " << alphabet_.GetSize()
<< ", but model has " << final_dim_size
<< " classes in its output. Make sure you're passing an alphabet "
<< "file with the same size as the one used for training."
<< std::endl;
return DS_ERR_INVALID_ALPHABET;
}
TfLiteIntArray* dims_c = interpreter_->tensor(previous_state_c_idx_)->dims;
TfLiteIntArray* dims_h = interpreter_->tensor(previous_state_h_idx_)->dims;
assert(dims_c->data[1] == dims_h->data[1]);
assert(state_size_ > 0);
state_size_ = dims_c->data[1];
return DS_ERR_OK;
}
// Copy contents of vec into the tensor with index tensor_idx.
// If vec.size() < num_elements, set the remainder of the tensor values to zero.
void
TFLiteModelState::copy_vector_to_tensor(const vector<float>& vec,
int tensor_idx,
int num_elements)
{
float* tensor = interpreter_->typed_tensor<float>(tensor_idx);
int i;
for (i = 0; i < vec.size(); ++i) {
tensor[i] = vec[i];
}
for (; i < num_elements; ++i) {
tensor[i] = 0.f;
}
}
// Copy num_elements elements from the tensor with index tensor_idx into vec
void
TFLiteModelState::copy_tensor_to_vector(int tensor_idx,
int num_elements,
vector<float>& vec)
{
float* tensor = interpreter_->typed_tensor<float>(tensor_idx);
for (int i = 0; i < num_elements; ++i) {
vec.push_back(tensor[i]);
}
}
void
TFLiteModelState::infer(const vector<float>& mfcc,
unsigned int n_frames,
const vector<float>& previous_state_c,
const vector<float>& previous_state_h,
vector<float>& logits_output,
vector<float>& state_c_output,
vector<float>& state_h_output)
{
const size_t num_classes = alphabet_.GetSize() + 1; // +1 for blank
// Feeding input_node
copy_vector_to_tensor(mfcc, input_node_idx_, n_frames*mfcc_feats_per_timestep_);
// Feeding previous_state_c, previous_state_h
assert(previous_state_c.size() == state_size_);
copy_vector_to_tensor(previous_state_c, previous_state_c_idx_, state_size_);
assert(previous_state_h.size() == state_size_);
copy_vector_to_tensor(previous_state_h, previous_state_h_idx_, state_size_);
interpreter_->SetExecutionPlan(acoustic_exec_plan_);
TfLiteStatus status = interpreter_->Invoke();
if (status != kTfLiteOk) {
std::cerr << "Error running session: " << status << "\n";
return;
}
copy_tensor_to_vector(logits_idx_, n_frames * BATCH_SIZE * num_classes, logits_output);
state_c_output.clear();
state_c_output.reserve(state_size_);
copy_tensor_to_vector(new_state_c_idx_, state_size_, state_c_output);
state_h_output.clear();
state_h_output.reserve(state_size_);
copy_tensor_to_vector(new_state_h_idx_, state_size_, state_h_output);
}
void
TFLiteModelState::compute_mfcc(const vector<float>& samples,
vector<float>& mfcc_output)
{
// Feeding input_node
copy_vector_to_tensor(samples, input_samples_idx_, samples.size());
TfLiteStatus status = interpreter_->SetExecutionPlan(mfcc_exec_plan_);
if (status != kTfLiteOk) {
std::cerr << "Error setting execution plan: " << status << "\n";
return;
}
status = interpreter_->Invoke();
if (status != kTfLiteOk) {
std::cerr << "Error running session: " << status << "\n";
return;
}
// The feature computation graph is hardcoded to one audio length for now
int n_windows = 1;
TfLiteIntArray* out_dims = interpreter_->tensor(mfccs_idx_)->dims;
int num_elements = 1;
for (int i = 0; i < out_dims->size; ++i) {
num_elements *= out_dims->data[i];
}
assert(num_elements / n_features_ == n_windows);
copy_tensor_to_vector(mfccs_idx_, n_windows * n_features_, mfcc_output);
}
| 15,416
|
C++
|
.cc
| 361
| 37.800554
| 129
| 0.663888
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,805
|
trie_load.cc
|
mozilla_DeepSpeech/native_client/trie_load.cc
|
#include <algorithm>
#include <iostream>
#include <string>
#include "ctcdecode/scorer.h"
#include "alphabet.h"
#ifdef DEBUG
#include <limits>
#include <unordered_map>
#include "ctcdecode/path_trie.h"
#endif // DEBUG
using namespace std;
int main(int argc, char** argv)
{
const char* kenlm_path = argv[1];
const char* trie_path = argv[2];
const char* alphabet_path = argv[3];
printf("Loading trie(%s) and alphabet(%s)\n", trie_path, alphabet_path);
Alphabet alphabet;
int err = alphabet.init(alphabet_path);
if (err != 0) {
return err;
}
Scorer scorer;
err = scorer.init(kenlm_path, alphabet);
#ifndef DEBUG
return err;
#else
// Print some info about the FST
using FstType = fst::ConstFst<fst::StdArc>;
auto dict = scorer.dictionary.get();
struct state_info {
int range_min = std::numeric_limits<int>::max();
int range_max = std::numeric_limits<int>::min();
};
auto print_states_from = [&](int i) {
std::unordered_map<int, state_info> sinfo;
for (fst::ArcIterator<FstType> aiter(*dict, i); !aiter.Done(); aiter.Next()) {
const fst::StdArc& arc = aiter.Value();
sinfo[arc.nextstate].range_min = std::min(sinfo[arc.nextstate].range_min, arc.ilabel-1);
sinfo[arc.nextstate].range_max = std::max(sinfo[arc.nextstate].range_max, arc.ilabel-1);
}
for (auto it = sinfo.begin(); it != sinfo.end(); ++it) {
state_info s = it->second;
printf("%d -> state %d (chars 0x%X - 0x%X, '%c' - '%c')\n", i, it->first, (unsigned int)s.range_min, (unsigned int)s.range_max, (char)s.range_min, (char)s.range_max);
}
};
print_states_from(0);
// for (int i = 1; i < 10; ++i) {
// print_states_from(i);
// }
return 0;
#endif // DEBUG
}
| 1,739
|
C++
|
.cc
| 53
| 29.54717
| 172
| 0.650538
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,806
|
client.cc
|
mozilla_DeepSpeech/native_client/client.cc
|
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sstream>
#include <string>
#ifdef __APPLE__
#include <TargetConditionals.h>
#endif
#if defined(__ANDROID__) || defined(_MSC_VER) || TARGET_OS_IPHONE
#define NO_SOX
#endif
#if defined(_MSC_VER)
#define NO_DIR
#endif
#ifndef NO_SOX
#include <sox.h>
#endif
#ifndef NO_DIR
#include <dirent.h>
#include <unistd.h>
#endif // NO_DIR
#include <vector>
#include "deepspeech.h"
#include "args.h"
typedef struct {
const char* string;
double cpu_time_overall;
} ds_result;
struct meta_word {
std::string word;
float start_time;
float duration;
};
char*
CandidateTranscriptToString(const CandidateTranscript* transcript)
{
std::string retval = "";
for (int i = 0; i < transcript->num_tokens; i++) {
const TokenMetadata& token = transcript->tokens[i];
retval += token.text;
}
return strdup(retval.c_str());
}
std::vector<meta_word>
CandidateTranscriptToWords(const CandidateTranscript* transcript)
{
std::vector<meta_word> word_list;
std::string word = "";
float word_start_time = 0;
// Loop through each token
for (int i = 0; i < transcript->num_tokens; i++) {
const TokenMetadata& token = transcript->tokens[i];
// Append token to word if it's not a space
if (strcmp(token.text, u8" ") != 0) {
// Log the start time of the new word
if (word.length() == 0) {
word_start_time = token.start_time;
}
word.append(token.text);
}
// Word boundary is either a space or the last token in the array
if (strcmp(token.text, u8" ") == 0 || i == transcript->num_tokens-1) {
float word_duration = token.start_time - word_start_time;
if (word_duration < 0) {
word_duration = 0;
}
meta_word w;
w.word = word;
w.start_time = word_start_time;
w.duration = word_duration;
word_list.push_back(w);
// Reset
word = "";
word_start_time = 0;
}
}
return word_list;
}
std::string
CandidateTranscriptToJSON(const CandidateTranscript *transcript)
{
std::ostringstream out_string;
std::vector<meta_word> words = CandidateTranscriptToWords(transcript);
out_string << R"("metadata":{"confidence":)" << transcript->confidence << R"(},"words":[)";
for (int i = 0; i < words.size(); i++) {
meta_word w = words[i];
out_string << R"({"word":")" << w.word << R"(","time":)" << w.start_time << R"(,"duration":)" << w.duration << "}";
if (i < words.size() - 1) {
out_string << ",";
}
}
out_string << "]";
return out_string.str();
}
char*
MetadataToJSON(Metadata* result)
{
std::ostringstream out_string;
out_string << "{\n";
for (int j=0; j < result->num_transcripts; ++j) {
const CandidateTranscript *transcript = &result->transcripts[j];
if (j == 0) {
out_string << CandidateTranscriptToJSON(transcript);
if (result->num_transcripts > 1) {
out_string << ",\n" << R"("alternatives")" << ":[\n";
}
} else {
out_string << "{" << CandidateTranscriptToJSON(transcript) << "}";
if (j < result->num_transcripts - 1) {
out_string << ",\n";
} else {
out_string << "\n]";
}
}
}
out_string << "\n}\n";
return strdup(out_string.str().c_str());
}
ds_result
LocalDsSTT(ModelState* aCtx, const short* aBuffer, size_t aBufferSize,
bool extended_output, bool json_output)
{
ds_result res = {0};
clock_t ds_start_time = clock();
// sphinx-doc: c_ref_inference_start
if (extended_output) {
Metadata *result = DS_SpeechToTextWithMetadata(aCtx, aBuffer, aBufferSize, 1);
res.string = CandidateTranscriptToString(&result->transcripts[0]);
DS_FreeMetadata(result);
} else if (json_output) {
Metadata *result = DS_SpeechToTextWithMetadata(aCtx, aBuffer, aBufferSize, json_candidate_transcripts);
res.string = MetadataToJSON(result);
DS_FreeMetadata(result);
} else if (stream_size > 0) {
StreamingState* ctx;
int status = DS_CreateStream(aCtx, &ctx);
if (status != DS_ERR_OK) {
res.string = strdup("");
return res;
}
size_t off = 0;
const char *last = nullptr;
const char *prev = nullptr;
while (off < aBufferSize) {
size_t cur = aBufferSize - off > stream_size ? stream_size : aBufferSize - off;
DS_FeedAudioContent(ctx, aBuffer + off, cur);
off += cur;
prev = last;
const char* partial = DS_IntermediateDecode(ctx);
if (last == nullptr || strcmp(last, partial)) {
printf("%s\n", partial);
last = partial;
} else {
DS_FreeString((char *) partial);
}
if (prev != nullptr && prev != last) {
DS_FreeString((char *) prev);
}
}
if (last != nullptr) {
DS_FreeString((char *) last);
}
res.string = DS_FinishStream(ctx);
} else if (extended_stream_size > 0) {
StreamingState* ctx;
int status = DS_CreateStream(aCtx, &ctx);
if (status != DS_ERR_OK) {
res.string = strdup("");
return res;
}
size_t off = 0;
const char *last = nullptr;
const char *prev = nullptr;
while (off < aBufferSize) {
size_t cur = aBufferSize - off > extended_stream_size ? extended_stream_size : aBufferSize - off;
DS_FeedAudioContent(ctx, aBuffer + off, cur);
off += cur;
prev = last;
const Metadata* result = DS_IntermediateDecodeWithMetadata(ctx, 1);
const char* partial = CandidateTranscriptToString(&result->transcripts[0]);
if (last == nullptr || strcmp(last, partial)) {
printf("%s\n", partial);
last = partial;
} else {
free((char *) partial);
}
if (prev != nullptr && prev != last) {
free((char *) prev);
}
DS_FreeMetadata((Metadata *)result);
}
const Metadata* result = DS_FinishStreamWithMetadata(ctx, 1);
res.string = CandidateTranscriptToString(&result->transcripts[0]);
DS_FreeMetadata((Metadata *)result);
free((char *) last);
} else {
res.string = DS_SpeechToText(aCtx, aBuffer, aBufferSize);
}
// sphinx-doc: c_ref_inference_stop
clock_t ds_end_infer = clock();
res.cpu_time_overall =
((double) (ds_end_infer - ds_start_time)) / CLOCKS_PER_SEC;
return res;
}
typedef struct {
char* buffer;
size_t buffer_size;
} ds_audio_buffer;
ds_audio_buffer
GetAudioBuffer(const char* path, int desired_sample_rate)
{
ds_audio_buffer res = {0};
#ifndef NO_SOX
sox_format_t* input = sox_open_read(path, NULL, NULL, NULL);
assert(input);
// Resample/reformat the audio so we can pass it through the MFCC functions
sox_signalinfo_t target_signal = {
static_cast<sox_rate_t>(desired_sample_rate), // Rate
1, // Channels
16, // Precision
SOX_UNSPEC, // Length
NULL // Effects headroom multiplier
};
sox_signalinfo_t interm_signal;
sox_encodinginfo_t target_encoding = {
SOX_ENCODING_SIGN2, // Sample format
16, // Bits per sample
0.0, // Compression factor
sox_option_default, // Should bytes be reversed
sox_option_default, // Should nibbles be reversed
sox_option_default, // Should bits be reversed (pairs of bits?)
sox_false // Reverse endianness
};
#if TARGET_OS_OSX
// It would be preferable to use sox_open_memstream_write here, but OS-X
// doesn't support POSIX 2008, which it requires. See Issue #461.
// Instead, we write to a temporary file.
char* output_name = tmpnam(NULL);
assert(output_name);
sox_format_t* output = sox_open_write(output_name, &target_signal,
&target_encoding, "raw", NULL, NULL);
#else
sox_format_t* output = sox_open_memstream_write(&res.buffer,
&res.buffer_size,
&target_signal,
&target_encoding,
"raw", NULL);
#endif
assert(output);
if ((int)input->signal.rate < desired_sample_rate) {
fprintf(stderr, "Warning: original sample rate (%d) is lower than %dkHz. "
"Up-sampling might produce erratic speech recognition.\n",
desired_sample_rate, (int)input->signal.rate);
}
// Setup the effects chain to decode/resample
char* sox_args[10];
sox_effects_chain_t* chain =
sox_create_effects_chain(&input->encoding, &output->encoding);
interm_signal = input->signal;
sox_effect_t* e = sox_create_effect(sox_find_effect("input"));
sox_args[0] = (char*)input;
assert(sox_effect_options(e, 1, sox_args) == SOX_SUCCESS);
assert(sox_add_effect(chain, e, &interm_signal, &input->signal) ==
SOX_SUCCESS);
free(e);
e = sox_create_effect(sox_find_effect("rate"));
assert(sox_effect_options(e, 0, NULL) == SOX_SUCCESS);
assert(sox_add_effect(chain, e, &interm_signal, &output->signal) ==
SOX_SUCCESS);
free(e);
e = sox_create_effect(sox_find_effect("channels"));
assert(sox_effect_options(e, 0, NULL) == SOX_SUCCESS);
assert(sox_add_effect(chain, e, &interm_signal, &output->signal) ==
SOX_SUCCESS);
free(e);
e = sox_create_effect(sox_find_effect("output"));
sox_args[0] = (char*)output;
assert(sox_effect_options(e, 1, sox_args) == SOX_SUCCESS);
assert(sox_add_effect(chain, e, &interm_signal, &output->signal) ==
SOX_SUCCESS);
free(e);
// Finally run the effects chain
sox_flow_effects(chain, NULL, NULL);
sox_delete_effects_chain(chain);
// Close sox handles
sox_close(output);
sox_close(input);
#endif // NO_SOX
#ifdef NO_SOX
// FIXME: Hack and support only mono 16-bits PCM with standard SoX header
FILE* wave = fopen(path, "r");
size_t rv;
unsigned short audio_format;
fseek(wave, 20, SEEK_SET); rv = fread(&audio_format, 2, 1, wave);
unsigned short num_channels;
fseek(wave, 22, SEEK_SET); rv = fread(&num_channels, 2, 1, wave);
unsigned int sample_rate;
fseek(wave, 24, SEEK_SET); rv = fread(&sample_rate, 4, 1, wave);
unsigned short bits_per_sample;
fseek(wave, 34, SEEK_SET); rv = fread(&bits_per_sample, 2, 1, wave);
assert(audio_format == 1); // 1 is PCM
assert(num_channels == 1); // MONO
assert(sample_rate == desired_sample_rate); // at desired sample rate
assert(bits_per_sample == 16); // 16 bits per sample
fprintf(stderr, "audio_format=%d\n", audio_format);
fprintf(stderr, "num_channels=%d\n", num_channels);
fprintf(stderr, "sample_rate=%d (desired=%d)\n", sample_rate, desired_sample_rate);
fprintf(stderr, "bits_per_sample=%d\n", bits_per_sample);
fseek(wave, 40, SEEK_SET); rv = fread(&res.buffer_size, 4, 1, wave);
fprintf(stderr, "res.buffer_size=%ld\n", res.buffer_size);
fseek(wave, 44, SEEK_SET);
res.buffer = (char*)malloc(sizeof(char) * res.buffer_size);
rv = fread(res.buffer, sizeof(char), res.buffer_size, wave);
fclose(wave);
#endif // NO_SOX
#if TARGET_OS_OSX
res.buffer_size = (size_t)(output->olength * 2);
res.buffer = (char*)malloc(sizeof(char) * res.buffer_size);
FILE* output_file = fopen(output_name, "rb");
assert(fread(res.buffer, sizeof(char), res.buffer_size, output_file) == res.buffer_size);
fclose(output_file);
unlink(output_name);
#endif
return res;
}
void
ProcessFile(ModelState* context, const char* path, bool show_times)
{
ds_audio_buffer audio = GetAudioBuffer(path, DS_GetModelSampleRate(context));
// Pass audio to DeepSpeech
// We take half of buffer_size because buffer is a char* while
// LocalDsSTT() expected a short*
ds_result result = LocalDsSTT(context,
(const short*)audio.buffer,
audio.buffer_size / 2,
extended_metadata,
json_output);
free(audio.buffer);
if (result.string) {
printf("%s\n", result.string);
DS_FreeString((char*)result.string);
}
if (show_times) {
printf("cpu_time_overall=%.05f\n",
result.cpu_time_overall);
}
}
std::vector<std::string>
SplitStringOnDelim(std::string in_string, std::string delim)
{
std::vector<std::string> out_vector;
char * tmp_str = new char[in_string.size() + 1];
std::copy(in_string.begin(), in_string.end(), tmp_str);
tmp_str[in_string.size()] = '\0';
const char* token = strtok(tmp_str, delim.c_str());
while( token != NULL ) {
out_vector.push_back(token);
token = strtok(NULL, delim.c_str());
}
delete[] tmp_str;
return out_vector;
}
int
main(int argc, char **argv)
{
if (!ProcessArgs(argc, argv)) {
return 1;
}
// Initialise DeepSpeech
ModelState* ctx;
// sphinx-doc: c_ref_model_start
int status = DS_CreateModel(model, &ctx);
if (status != 0) {
char* error = DS_ErrorCodeToErrorMessage(status);
fprintf(stderr, "Could not create model: %s\n", error);
free(error);
return 1;
}
if (set_beamwidth) {
status = DS_SetModelBeamWidth(ctx, beam_width);
if (status != 0) {
fprintf(stderr, "Could not set model beam width.\n");
return 1;
}
}
if (scorer) {
status = DS_EnableExternalScorer(ctx, scorer);
if (status != 0) {
fprintf(stderr, "Could not enable external scorer.\n");
return 1;
}
if (set_alphabeta) {
status = DS_SetScorerAlphaBeta(ctx, lm_alpha, lm_beta);
if (status != 0) {
fprintf(stderr, "Error setting scorer alpha and beta.\n");
return 1;
}
}
}
// sphinx-doc: c_ref_model_stop
if (hot_words) {
std::vector<std::string> hot_words_ = SplitStringOnDelim(hot_words, ",");
for ( std::string hot_word_ : hot_words_ ) {
std::vector<std::string> pair_ = SplitStringOnDelim(hot_word_, ":");
const char* word = (pair_[0]).c_str();
// the strtof function will return 0 in case of non numeric characters
// so, check the boost string before we turn it into a float
bool boost_is_valid = (pair_[1].find_first_not_of("-.0123456789") == std::string::npos);
float boost = strtof((pair_[1]).c_str(),0);
status = DS_AddHotWord(ctx, word, boost);
if (status != 0 || !boost_is_valid) {
fprintf(stderr, "Could not enable hot-word.\n");
return 1;
}
}
}
#ifndef NO_SOX
// Initialise SOX
assert(sox_init() == SOX_SUCCESS);
#endif
struct stat wav_info;
if (0 != stat(audio, &wav_info)) {
printf("Error on stat: %d\n", errno);
}
switch (wav_info.st_mode & S_IFMT) {
#ifndef _MSC_VER
case S_IFLNK:
#endif
case S_IFREG:
ProcessFile(ctx, audio, show_times);
break;
#ifndef NO_DIR
case S_IFDIR:
{
printf("Running on directory %s\n", audio);
DIR* wav_dir = opendir(audio);
assert(wav_dir);
struct dirent* entry;
while ((entry = readdir(wav_dir)) != NULL) {
std::string fname = std::string(entry->d_name);
if (fname.find(".wav") == std::string::npos) {
continue;
}
std::ostringstream fullpath;
fullpath << audio << "/" << fname;
std::string path = fullpath.str();
printf("> %s\n", path.c_str());
ProcessFile(ctx, path.c_str(), show_times);
}
closedir(wav_dir);
}
break;
#endif
default:
printf("Unexpected type for %s: %d\n", audio, (wav_info.st_mode & S_IFMT));
break;
}
#ifndef NO_SOX
// Deinitialise and quit
sox_quit();
#endif // NO_SOX
DS_FreeModel(ctx);
return 0;
}
| 15,684
|
C++
|
.cc
| 470
| 28.059574
| 119
| 0.625818
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,807
|
alphabet.cc
|
mozilla_DeepSpeech/native_client/alphabet.cc
|
#include "alphabet.h"
#include "ctcdecode/decoder_utils.h"
#include <fstream>
// std::getline, but handle newline conventions from multiple platforms instead
// of just the platform this code was built for
std::istream&
getline_crossplatform(std::istream& is, std::string& t)
{
t.clear();
// The characters in the stream are read one-by-one using a std::streambuf.
// That is faster than reading them one-by-one using the std::istream.
// Code that uses streambuf this way must be guarded by a sentry object.
// The sentry object performs various tasks,
// such as thread synchronization and updating the stream state.
std::istream::sentry se(is, true);
std::streambuf* sb = is.rdbuf();
while (true) {
int c = sb->sbumpc();
switch (c) {
case '\n':
return is;
case '\r':
if(sb->sgetc() == '\n')
sb->sbumpc();
return is;
case std::streambuf::traits_type::eof():
// Also handle the case when the last line has no line ending
if(t.empty())
is.setstate(std::ios::eofbit);
return is;
default:
t += (char)c;
}
}
}
int
Alphabet::init(const char *config_file)
{
std::ifstream in(config_file, std::ios::in);
if (!in) {
return 1;
}
unsigned int label = 0;
space_label_ = -2;
for (std::string line; getline_crossplatform(in, line);) {
if (line.size() == 2 && line[0] == '\\' && line[1] == '#') {
line = '#';
} else if (line[0] == '#') {
continue;
}
//TODO: we should probably do something more i18n-aware here
if (line == " ") {
space_label_ = label;
}
if (line.length() == 0) {
continue;
}
label_to_str_[label] = line;
str_to_label_[line] = label;
++label;
}
size_ = label;
in.close();
return 0;
}
std::string
Alphabet::Serialize()
{
// Serialization format is a sequence of (key, value) pairs, where key is
// a uint16_t and value is a uint16_t length followed by `length` UTF-8
// encoded bytes with the label.
std::stringstream out;
// We start by writing the number of pairs in the buffer as uint16_t.
uint16_t size = size_;
out.write(reinterpret_cast<char*>(&size), sizeof(size));
for (auto it = label_to_str_.begin(); it != label_to_str_.end(); ++it) {
uint16_t key = it->first;
string str = it->second;
uint16_t len = str.length();
// Then we write the key as uint16_t, followed by the length of the value
// as uint16_t, followed by `length` bytes (the value itself).
out.write(reinterpret_cast<char*>(&key), sizeof(key));
out.write(reinterpret_cast<char*>(&len), sizeof(len));
out.write(str.data(), len);
}
return out.str();
}
int
Alphabet::Deserialize(const char* buffer, const int buffer_size)
{
// See util/text.py for an explanation of the serialization format.
int offset = 0;
if (buffer_size - offset < sizeof(uint16_t)) {
return 1;
}
uint16_t size = *(uint16_t*)(buffer + offset);
offset += sizeof(uint16_t);
size_ = size;
for (int i = 0; i < size; ++i) {
if (buffer_size - offset < sizeof(uint16_t)) {
return 1;
}
uint16_t label = *(uint16_t*)(buffer + offset);
offset += sizeof(uint16_t);
if (buffer_size - offset < sizeof(uint16_t)) {
return 1;
}
uint16_t val_len = *(uint16_t*)(buffer + offset);
offset += sizeof(uint16_t);
if (buffer_size - offset < val_len) {
return 1;
}
std::string val(buffer+offset, val_len);
offset += val_len;
label_to_str_[label] = val;
str_to_label_[val] = label;
if (val == " ") {
space_label_ = label;
}
}
return 0;
}
bool
Alphabet::CanEncodeSingle(const std::string& input) const
{
auto it = str_to_label_.find(input);
return it != str_to_label_.end();
}
bool
Alphabet::CanEncode(const std::string& input) const
{
for (auto cp : split_into_codepoints(input)) {
if (!CanEncodeSingle(cp)) {
return false;
}
}
return true;
}
std::string
Alphabet::DecodeSingle(unsigned int label) const
{
auto it = label_to_str_.find(label);
if (it != label_to_str_.end()) {
return it->second;
} else {
std::cerr << "Invalid label " << label << std::endl;
abort();
}
}
unsigned int
Alphabet::EncodeSingle(const std::string& string) const
{
auto it = str_to_label_.find(string);
if (it != str_to_label_.end()) {
return it->second;
} else {
std::cerr << "Invalid string " << string << std::endl;
abort();
}
}
std::string
Alphabet::Decode(const std::vector<unsigned int>& input) const
{
std::string word;
for (auto ind : input) {
word += DecodeSingle(ind);
}
return word;
}
std::string
Alphabet::Decode(const unsigned int* input, int length) const
{
std::string word;
for (int i = 0; i < length; ++i) {
word += DecodeSingle(input[i]);
}
return word;
}
std::vector<unsigned int>
Alphabet::Encode(const std::string& input) const
{
std::vector<unsigned int> result;
for (auto cp : split_into_codepoints(input)) {
result.push_back(EncodeSingle(cp));
}
return result;
}
bool
UTF8Alphabet::CanEncodeSingle(const std::string& input) const
{
return true;
}
bool
UTF8Alphabet::CanEncode(const std::string& input) const
{
return true;
}
std::vector<unsigned int>
UTF8Alphabet::Encode(const std::string& input) const
{
std::vector<unsigned int> result;
for (auto byte_char : input) {
std::string byte_str(1, byte_char);
result.push_back(EncodeSingle(byte_str));
}
return result;
}
| 5,495
|
C++
|
.cc
| 207
| 23.082126
| 79
| 0.645002
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
2,111
|
modelstate.h
|
mozilla_DeepSpeech/native_client/modelstate.h
|
#ifndef MODELSTATE_H
#define MODELSTATE_H
#include <vector>
#include "deepspeech.h"
#include "alphabet.h"
#include "ctcdecode/scorer.h"
#include "ctcdecode/output.h"
class DecoderState;
struct ModelState {
//TODO: infer batch size from model/use dynamic batch size
static constexpr unsigned int BATCH_SIZE = 1;
Alphabet alphabet_;
std::shared_ptr<Scorer> scorer_;
std::unordered_map<std::string, float> hot_words_;
unsigned int beam_width_;
unsigned int n_steps_;
unsigned int n_context_;
unsigned int n_features_;
unsigned int mfcc_feats_per_timestep_;
unsigned int sample_rate_;
unsigned int audio_win_len_;
unsigned int audio_win_step_;
unsigned int state_size_;
ModelState();
virtual ~ModelState();
virtual int init(const char* model_path);
virtual void compute_mfcc(const std::vector<float>& audio_buffer, std::vector<float>& mfcc_output) = 0;
/**
* @brief Do a single inference step in the acoustic model, with:
* input=mfcc
* input_lengths=[n_frames]
*
* @param mfcc batch input data
* @param n_frames number of timesteps in the data
*
* @param[out] output_logits Where to store computed logits.
*/
virtual void infer(const std::vector<float>& mfcc,
unsigned int n_frames,
const std::vector<float>& previous_state_c,
const std::vector<float>& previous_state_h,
std::vector<float>& logits_output,
std::vector<float>& state_c_output,
std::vector<float>& state_h_output) = 0;
/**
* @brief Perform decoding of the logits, using basic CTC decoder or
* CTC decoder with KenLM enabled
*
* @param state Decoder state to use when decoding.
*
* @return String representing the decoded text.
*/
virtual char* decode(const DecoderState& state) const;
/**
* @brief Return character-level metadata including letter timings.
*
* @param state Decoder state to use when decoding.
* @param num_results Maximum number of candidate results to return.
*
* @return A Metadata struct containing CandidateTranscript structs.
* Each represents an candidate transcript, with the first ranked most probable.
* The user is responsible for freeing Result by calling DS_FreeMetadata().
*/
virtual Metadata* decode_metadata(const DecoderState& state,
size_t num_results);
};
#endif // MODELSTATE_H
| 2,497
|
C++
|
.h
| 67
| 31.820896
| 105
| 0.680596
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,112
|
workspace_status.h
|
mozilla_DeepSpeech/native_client/workspace_status.h
|
#ifndef WORKSPACE_STATUS_H
#define WORKSPACE_STATUS_H
const char *tf_local_git_version();
const char *ds_version();
const char *ds_git_version();
const int ds_graph_version();
#endif // WORKSPACE_STATUS_H
| 207
|
C++
|
.h
| 7
| 28.285714
| 35
| 0.767677
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,113
|
tflitemodelstate.h
|
mozilla_DeepSpeech/native_client/tflitemodelstate.h
|
#ifndef TFLITEMODELSTATE_H
#define TFLITEMODELSTATE_H
#include <memory>
#include <vector>
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/tools/evaluation/utils.h"
#include "modelstate.h"
struct TFLiteModelState : public ModelState
{
std::unique_ptr<tflite::Interpreter> interpreter_;
std::unique_ptr<tflite::FlatBufferModel> fbmodel_;
int input_node_idx_;
int previous_state_c_idx_;
int previous_state_h_idx_;
int input_samples_idx_;
int logits_idx_;
int new_state_c_idx_;
int new_state_h_idx_;
int mfccs_idx_;
std::vector<int> acoustic_exec_plan_;
std::vector<int> mfcc_exec_plan_;
TFLiteModelState();
virtual ~TFLiteModelState();
virtual int init(const char* model_path) override;
virtual void compute_mfcc(const std::vector<float>& audio_buffer,
std::vector<float>& mfcc_output) override;
virtual void infer(const std::vector<float>& mfcc,
unsigned int n_frames,
const std::vector<float>& previous_state_c,
const std::vector<float>& previous_state_h,
std::vector<float>& logits_output,
std::vector<float>& state_c_output,
std::vector<float>& state_h_output) override;
private:
int get_tensor_by_name(const std::vector<int>& list, const char* name);
int get_input_tensor_by_name(const char* name);
int get_output_tensor_by_name(const char* name);
std::vector<int> find_parent_node_ids(int tensor_id);
void copy_vector_to_tensor(const std::vector<float>& vec,
int tensor_idx,
int num_elements);
void copy_tensor_to_vector(int tensor_idx,
int num_elements,
std::vector<float>& vec);
};
#endif // TFLITEMODELSTATE_H
| 1,904
|
C++
|
.h
| 47
| 32.510638
| 73
| 0.646963
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,114
|
deepspeech.h
|
mozilla_DeepSpeech/native_client/deepspeech.h
|
#ifndef DEEPSPEECH_H
#define DEEPSPEECH_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef SWIG
#if defined _MSC_VER
#define DEEPSPEECH_EXPORT __declspec(dllexport)
#else
#define DEEPSPEECH_EXPORT __attribute__ ((visibility("default")))
#endif /*End of _MSC_VER*/
#else
#define DEEPSPEECH_EXPORT
#endif
typedef struct ModelState ModelState;
typedef struct StreamingState StreamingState;
/**
* @brief Stores text of an individual token, along with its timing information
*/
typedef struct TokenMetadata {
/** The text corresponding to this token */
const char* const text;
/** Position of the token in units of 20ms */
const unsigned int timestep;
/** Position of the token in seconds */
const float start_time;
} TokenMetadata;
/**
* @brief A single transcript computed by the model, including a confidence
* value and the metadata for its constituent tokens.
*/
typedef struct CandidateTranscript {
/** Array of TokenMetadata objects */
const TokenMetadata* const tokens;
/** Size of the tokens array */
const unsigned int num_tokens;
/** Approximated confidence value for this transcript. This is roughly the
* sum of the acoustic model logit values for each timestep/character that
* contributed to the creation of this transcript.
*/
const double confidence;
} CandidateTranscript;
/**
* @brief An array of CandidateTranscript objects computed by the model.
*/
typedef struct Metadata {
/** Array of CandidateTranscript objects */
const CandidateTranscript* const transcripts;
/** Size of the transcripts array */
const unsigned int num_transcripts;
} Metadata;
// sphinx-doc: error_code_listing_start
#define DS_FOR_EACH_ERROR(APPLY) \
APPLY(DS_ERR_OK, 0x0000, "No error.") \
APPLY(DS_ERR_NO_MODEL, 0x1000, "Missing model information.") \
APPLY(DS_ERR_INVALID_ALPHABET, 0x2000, "Invalid alphabet embedded in model. (Data corruption?)") \
APPLY(DS_ERR_INVALID_SHAPE, 0x2001, "Invalid model shape.") \
APPLY(DS_ERR_INVALID_SCORER, 0x2002, "Invalid scorer file.") \
APPLY(DS_ERR_MODEL_INCOMPATIBLE, 0x2003, "Incompatible model.") \
APPLY(DS_ERR_SCORER_NOT_ENABLED, 0x2004, "External scorer is not enabled.") \
APPLY(DS_ERR_SCORER_UNREADABLE, 0x2005, "Could not read scorer file.") \
APPLY(DS_ERR_SCORER_INVALID_LM, 0x2006, "Could not recognize language model header in scorer.") \
APPLY(DS_ERR_SCORER_NO_TRIE, 0x2007, "Reached end of scorer file before loading vocabulary trie.") \
APPLY(DS_ERR_SCORER_INVALID_TRIE, 0x2008, "Invalid magic in trie header.") \
APPLY(DS_ERR_SCORER_VERSION_MISMATCH, 0x2009, "Scorer file version does not match expected version.") \
APPLY(DS_ERR_FAIL_INIT_MMAP, 0x3000, "Failed to initialize memory mapped model.") \
APPLY(DS_ERR_FAIL_INIT_SESS, 0x3001, "Failed to initialize the session.") \
APPLY(DS_ERR_FAIL_INTERPRETER, 0x3002, "Interpreter failed.") \
APPLY(DS_ERR_FAIL_RUN_SESS, 0x3003, "Failed to run the session.") \
APPLY(DS_ERR_FAIL_CREATE_STREAM, 0x3004, "Error creating the stream.") \
APPLY(DS_ERR_FAIL_READ_PROTOBUF, 0x3005, "Error reading the proto buffer model file.") \
APPLY(DS_ERR_FAIL_CREATE_SESS, 0x3006, "Failed to create session.") \
APPLY(DS_ERR_FAIL_CREATE_MODEL, 0x3007, "Could not allocate model state.") \
APPLY(DS_ERR_FAIL_INSERT_HOTWORD, 0x3008, "Could not insert hot-word.") \
APPLY(DS_ERR_FAIL_CLEAR_HOTWORD, 0x3009, "Could not clear hot-words.") \
APPLY(DS_ERR_FAIL_ERASE_HOTWORD, 0x3010, "Could not erase hot-word.")
// sphinx-doc: error_code_listing_end
enum DeepSpeech_Error_Codes
{
#define DEFINE(NAME, VALUE, DESC) NAME = VALUE,
DS_FOR_EACH_ERROR(DEFINE)
#undef DEFINE
};
/**
* @brief An object providing an interface to a trained DeepSpeech model.
*
* @param aModelPath The path to the frozen model graph.
* @param[out] retval a ModelState pointer
*
* @return Zero on success, non-zero on failure.
*/
DEEPSPEECH_EXPORT
int DS_CreateModel(const char* aModelPath,
ModelState** retval);
/**
* @brief Get beam width value used by the model. If {@link DS_SetModelBeamWidth}
* was not called before, will return the default value loaded from the
* model file.
*
* @param aCtx A ModelState pointer created with {@link DS_CreateModel}.
*
* @return Beam width value used by the model.
*/
DEEPSPEECH_EXPORT
unsigned int DS_GetModelBeamWidth(const ModelState* aCtx);
/**
* @brief Set beam width value used by the model.
*
* @param aCtx A ModelState pointer created with {@link DS_CreateModel}.
* @param aBeamWidth The beam width used by the model. A larger beam width value
* generates better results at the cost of decoding time.
*
* @return Zero on success, non-zero on failure.
*/
DEEPSPEECH_EXPORT
int DS_SetModelBeamWidth(ModelState* aCtx,
unsigned int aBeamWidth);
/**
* @brief Return the sample rate expected by a model.
*
* @param aCtx A ModelState pointer created with {@link DS_CreateModel}.
*
* @return Sample rate expected by the model for its input.
*/
DEEPSPEECH_EXPORT
int DS_GetModelSampleRate(const ModelState* aCtx);
/**
* @brief Frees associated resources and destroys model object.
*/
DEEPSPEECH_EXPORT
void DS_FreeModel(ModelState* ctx);
/**
* @brief Enable decoding using an external scorer.
*
* @param aCtx The ModelState pointer for the model being changed.
* @param aScorerPath The path to the external scorer file.
*
* @return Zero on success, non-zero on failure (invalid arguments).
*/
DEEPSPEECH_EXPORT
int DS_EnableExternalScorer(ModelState* aCtx,
const char* aScorerPath);
/**
* @brief Add a hot-word and its boost.
*
* Words that don't occur in the scorer (e.g. proper nouns) or strings that contain spaces won't be taken into account.
*
* @param aCtx The ModelState pointer for the model being changed.
* @param word The hot-word.
* @param boost The boost. Positive value increases and negative reduces chance of a word occuring in a transcription. Excessive positive boost might lead to splitting up of letters of the word following the hot-word.
*
* @return Zero on success, non-zero on failure (invalid arguments).
*/
DEEPSPEECH_EXPORT
int DS_AddHotWord(ModelState* aCtx,
const char* word,
float boost);
/**
* @brief Remove entry for a hot-word from the hot-words map.
*
* @param aCtx The ModelState pointer for the model being changed.
* @param word The hot-word.
*
* @return Zero on success, non-zero on failure (invalid arguments).
*/
DEEPSPEECH_EXPORT
int DS_EraseHotWord(ModelState* aCtx,
const char* word);
/**
* @brief Removes all elements from the hot-words map.
*
* @param aCtx The ModelState pointer for the model being changed.
*
* @return Zero on success, non-zero on failure (invalid arguments).
*/
DEEPSPEECH_EXPORT
int DS_ClearHotWords(ModelState* aCtx);
/**
* @brief Disable decoding using an external scorer.
*
* @param aCtx The ModelState pointer for the model being changed.
*
* @return Zero on success, non-zero on failure.
*/
DEEPSPEECH_EXPORT
int DS_DisableExternalScorer(ModelState* aCtx);
/**
* @brief Set hyperparameters alpha and beta of the external scorer.
*
* @param aCtx The ModelState pointer for the model being changed.
* @param aAlpha The alpha hyperparameter of the decoder. Language model weight.
* @param aLMBeta The beta hyperparameter of the decoder. Word insertion weight.
*
* @return Zero on success, non-zero on failure.
*/
DEEPSPEECH_EXPORT
int DS_SetScorerAlphaBeta(ModelState* aCtx,
float aAlpha,
float aBeta);
/**
* @brief Use the DeepSpeech model to convert speech to text.
*
* @param aCtx The ModelState pointer for the model to use.
* @param aBuffer A 16-bit, mono raw audio signal at the appropriate
* sample rate (matching what the model was trained on).
* @param aBufferSize The number of samples in the audio signal.
*
* @return The STT result. The user is responsible for freeing the string using
* {@link DS_FreeString()}. Returns NULL on error.
*/
DEEPSPEECH_EXPORT
char* DS_SpeechToText(ModelState* aCtx,
const short* aBuffer,
unsigned int aBufferSize);
/**
* @brief Use the DeepSpeech model to convert speech to text and output results
* including metadata.
*
* @param aCtx The ModelState pointer for the model to use.
* @param aBuffer A 16-bit, mono raw audio signal at the appropriate
* sample rate (matching what the model was trained on).
* @param aBufferSize The number of samples in the audio signal.
* @param aNumResults The maximum number of CandidateTranscript structs to return. Returned value might be smaller than this.
*
* @return Metadata struct containing multiple CandidateTranscript structs. Each
* transcript has per-token metadata including timing information. The
* user is responsible for freeing Metadata by calling {@link DS_FreeMetadata()}.
* Returns NULL on error.
*/
DEEPSPEECH_EXPORT
Metadata* DS_SpeechToTextWithMetadata(ModelState* aCtx,
const short* aBuffer,
unsigned int aBufferSize,
unsigned int aNumResults);
/**
* @brief Create a new streaming inference state. The streaming state returned
* by this function can then be passed to {@link DS_FeedAudioContent()}
* and {@link DS_FinishStream()}.
*
* @param aCtx The ModelState pointer for the model to use.
* @param[out] retval an opaque pointer that represents the streaming state. Can
* be NULL if an error occurs.
*
* @return Zero for success, non-zero on failure.
*/
DEEPSPEECH_EXPORT
int DS_CreateStream(ModelState* aCtx,
StreamingState** retval);
/**
* @brief Feed audio samples to an ongoing streaming inference.
*
* @param aSctx A streaming state pointer returned by {@link DS_CreateStream()}.
* @param aBuffer An array of 16-bit, mono raw audio samples at the
* appropriate sample rate (matching what the model was trained on).
* @param aBufferSize The number of samples in @p aBuffer.
*/
DEEPSPEECH_EXPORT
void DS_FeedAudioContent(StreamingState* aSctx,
const short* aBuffer,
unsigned int aBufferSize);
/**
* @brief Compute the intermediate decoding of an ongoing streaming inference.
*
* @param aSctx A streaming state pointer returned by {@link DS_CreateStream()}.
*
* @return The STT intermediate result. The user is responsible for freeing the
* string using {@link DS_FreeString()}.
*/
DEEPSPEECH_EXPORT
char* DS_IntermediateDecode(const StreamingState* aSctx);
/**
* @brief Compute the intermediate decoding of an ongoing streaming inference,
* return results including metadata.
*
* @param aSctx A streaming state pointer returned by {@link DS_CreateStream()}.
* @param aNumResults The number of candidate transcripts to return.
*
* @return Metadata struct containing multiple candidate transcripts. Each transcript
* has per-token metadata including timing information. The user is
* responsible for freeing Metadata by calling {@link DS_FreeMetadata()}.
* Returns NULL on error.
*/
DEEPSPEECH_EXPORT
Metadata* DS_IntermediateDecodeWithMetadata(const StreamingState* aSctx,
unsigned int aNumResults);
/**
* @brief Compute the final decoding of an ongoing streaming inference and return
* the result. Signals the end of an ongoing streaming inference.
*
* @param aSctx A streaming state pointer returned by {@link DS_CreateStream()}.
*
* @return The STT result. The user is responsible for freeing the string using
* {@link DS_FreeString()}.
*
* @note This method will free the state pointer (@p aSctx).
*/
DEEPSPEECH_EXPORT
char* DS_FinishStream(StreamingState* aSctx);
/**
* @brief Compute the final decoding of an ongoing streaming inference and return
* results including metadata. Signals the end of an ongoing streaming
* inference.
*
* @param aSctx A streaming state pointer returned by {@link DS_CreateStream()}.
* @param aNumResults The number of candidate transcripts to return.
*
* @return Metadata struct containing multiple candidate transcripts. Each transcript
* has per-token metadata including timing information. The user is
* responsible for freeing Metadata by calling {@link DS_FreeMetadata()}.
* Returns NULL on error.
*
* @note This method will free the state pointer (@p aSctx).
*/
DEEPSPEECH_EXPORT
Metadata* DS_FinishStreamWithMetadata(StreamingState* aSctx,
unsigned int aNumResults);
/**
* @brief Destroy a streaming state without decoding the computed logits. This
* can be used if you no longer need the result of an ongoing streaming
* inference and don't want to perform a costly decode operation.
*
* @param aSctx A streaming state pointer returned by {@link DS_CreateStream()}.
*
* @note This method will free the state pointer (@p aSctx).
*/
DEEPSPEECH_EXPORT
void DS_FreeStream(StreamingState* aSctx);
/**
* @brief Free memory allocated for metadata information.
*/
DEEPSPEECH_EXPORT
void DS_FreeMetadata(Metadata* m);
/**
* @brief Free a char* string returned by the DeepSpeech API.
*/
DEEPSPEECH_EXPORT
void DS_FreeString(char* str);
/**
* @brief Returns the version of this library. The returned version is a semantic
* version (SemVer 2.0.0). The string returned must be freed with {@link DS_FreeString()}.
*
* @return The version string.
*/
DEEPSPEECH_EXPORT
char* DS_Version();
/**
* @brief Returns a textual description corresponding to an error code.
* The string returned must be freed with @{link DS_FreeString()}.
*
* @return The error description.
*/
DEEPSPEECH_EXPORT
char* DS_ErrorCodeToErrorMessage(int aErrorCode);
#undef DEEPSPEECH_EXPORT
#ifdef __cplusplus
}
#endif
#endif /* DEEPSPEECH_H */
| 14,371
|
C++
|
.h
| 358
| 36.807263
| 217
| 0.712445
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,115
|
alphabet.h
|
mozilla_DeepSpeech/native_client/alphabet.h
|
#ifndef ALPHABET_H
#define ALPHABET_H
#include <string>
#include <unordered_map>
#include <vector>
/*
* Loads a text file describing a mapping of labels to strings, one string per
* line. This is used by the decoder, client and Python scripts to convert the
* output of the decoder to a human-readable string and vice-versa.
*/
class Alphabet {
public:
Alphabet() = default;
Alphabet(const Alphabet&) = default;
Alphabet& operator=(const Alphabet&) = default;
virtual ~Alphabet() = default;
virtual int init(const char *config_file);
// Serialize alphabet into a binary buffer.
std::string Serialize();
// Deserialize alphabet from a binary buffer.
int Deserialize(const char* buffer, const int buffer_size);
size_t GetSize() const {
return size_;
}
bool IsSpace(unsigned int label) const {
return label == space_label_;
}
unsigned int GetSpaceLabel() const {
return space_label_;
}
// Returns true if the single character/output class has a corresponding label
// in the alphabet.
virtual bool CanEncodeSingle(const std::string& string) const;
// Returns true if the entire string can be encoded into labels in this
// alphabet.
virtual bool CanEncode(const std::string& string) const;
// Decode a single label into a string.
std::string DecodeSingle(unsigned int label) const;
// Encode a single character/output class into a label. Character must be in
// the alphabet, this method will assert that. Use `CanEncodeSingle` to test.
unsigned int EncodeSingle(const std::string& string) const;
// Decode a sequence of labels into a string.
std::string Decode(const std::vector<unsigned int>& input) const;
// We provide a C-style overload for accepting NumPy arrays as input, since
// the NumPy library does not have built-in typemaps for std::vector<T>.
std::string Decode(const unsigned int* input, int length) const;
// Encode a sequence of character/output classes into a sequence of labels.
// Characters are assumed to always take a single Unicode codepoint.
// Characters must be in the alphabet, this method will assert that. Use
// `CanEncode` and `CanEncodeSingle` to test.
virtual std::vector<unsigned int> Encode(const std::string& input) const;
protected:
size_t size_;
unsigned int space_label_;
std::unordered_map<unsigned int, std::string> label_to_str_;
std::unordered_map<std::string, unsigned int> str_to_label_;
};
class UTF8Alphabet : public Alphabet
{
public:
UTF8Alphabet() {
size_ = 255;
space_label_ = ' ' - 1;
for (size_t i = 0; i < size_; ++i) {
std::string val(1, i+1);
label_to_str_[i] = val;
str_to_label_[val] = i;
}
}
int init(const char*) override {
return 0;
}
bool CanEncodeSingle(const std::string& string) const override;
bool CanEncode(const std::string& string) const override;
std::vector<unsigned int> Encode(const std::string& input) const override;
};
#endif //ALPHABET_H
| 2,983
|
C++
|
.h
| 77
| 35.558442
| 80
| 0.727651
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,116
|
args.h
|
mozilla_DeepSpeech/native_client/args.h
|
#ifndef __ARGS_H__
#define __ARGS_H__
#if defined(_MSC_VER)
#include "getopt_win.h"
#else
#include <getopt.h>
#endif
#include <iostream>
#include "deepspeech.h"
char* model = NULL;
char* scorer = NULL;
char* audio = NULL;
bool set_beamwidth = false;
int beam_width = 0;
bool set_alphabeta = false;
float lm_alpha = 0.f;
float lm_beta = 0.f;
bool show_times = false;
bool has_versions = false;
bool extended_metadata = false;
bool json_output = false;
int json_candidate_transcripts = 3;
int stream_size = 0;
int extended_stream_size = 0;
char* hot_words = NULL;
void PrintHelp(const char* bin)
{
std::cout <<
"Usage: " << bin << " --model MODEL [--scorer SCORER] --audio AUDIO [-t] [-e]\n"
"\n"
"Running DeepSpeech inference.\n"
"\n"
"\t--model MODEL\t\t\tPath to the model (protocol buffer binary file)\n"
"\t--scorer SCORER\t\t\tPath to the external scorer file\n"
"\t--audio AUDIO\t\t\tPath to the audio file to run (WAV format)\n"
"\t--beam_width BEAM_WIDTH\t\tValue for decoder beam width (int)\n"
"\t--lm_alpha LM_ALPHA\t\tValue for language model alpha param (float)\n"
"\t--lm_beta LM_BETA\t\tValue for language model beta param (float)\n"
"\t-t\t\t\t\tRun in benchmark mode, output mfcc & inference time\n"
"\t--extended\t\t\tOutput string from extended metadata\n"
"\t--json\t\t\t\tExtended output, shows word timings as JSON\n"
"\t--candidate_transcripts NUMBER\tNumber of candidate transcripts to include in JSON output\n"
"\t--stream size\t\t\tRun in stream mode, output intermediate results\n"
"\t--extended_stream size\t\t\tRun in stream mode using metadata output, output intermediate results\n"
"\t--hot_words\t\t\tHot-words and their boosts. Word:Boost pairs are comma-separated\n"
"\t--help\t\t\t\tShow help\n"
"\t--version\t\t\tPrint version and exits\n";
char* version = DS_Version();
std::cerr << "DeepSpeech " << version << "\n";
DS_FreeString(version);
exit(1);
}
bool ProcessArgs(int argc, char** argv)
{
const char* const short_opts = "m:l:a:b:c:d:tejs:w:vh";
const option long_opts[] = {
{"model", required_argument, nullptr, 'm'},
{"scorer", required_argument, nullptr, 'l'},
{"audio", required_argument, nullptr, 'a'},
{"beam_width", required_argument, nullptr, 'b'},
{"lm_alpha", required_argument, nullptr, 'c'},
{"lm_beta", required_argument, nullptr, 'd'},
{"t", no_argument, nullptr, 't'},
{"extended", no_argument, nullptr, 'e'},
{"json", no_argument, nullptr, 'j'},
{"candidate_transcripts", required_argument, nullptr, 150},
{"stream", required_argument, nullptr, 's'},
{"extended_stream", required_argument, nullptr, 'S'},
{"hot_words", required_argument, nullptr, 'w'},
{"version", no_argument, nullptr, 'v'},
{"help", no_argument, nullptr, 'h'},
{nullptr, no_argument, nullptr, 0}
};
while (true)
{
const auto opt = getopt_long(argc, argv, short_opts, long_opts, nullptr);
if (-1 == opt)
break;
switch (opt)
{
case 'm':
model = optarg;
break;
case 'l':
scorer = optarg;
break;
case 'a':
audio = optarg;
break;
case 'b':
set_beamwidth = true;
beam_width = atoi(optarg);
break;
case 'c':
set_alphabeta = true;
lm_alpha = atof(optarg);
break;
case 'd':
set_alphabeta = true;
lm_beta = atof(optarg);
break;
case 't':
show_times = true;
break;
case 'e':
extended_metadata = true;
break;
case 'j':
json_output = true;
break;
case 150:
json_candidate_transcripts = atoi(optarg);
break;
case 's':
stream_size = atoi(optarg);
break;
case 'S':
extended_stream_size = atoi(optarg);
break;
case 'v':
has_versions = true;
break;
case 'w':
hot_words = optarg;
break;
case 'h': // -h or --help
case '?': // Unrecognized option
default:
PrintHelp(argv[0]);
break;
}
}
if (has_versions) {
char* version = DS_Version();
std::cout << "DeepSpeech " << version << "\n";
DS_FreeString(version);
return false;
}
if (!model || !audio) {
PrintHelp(argv[0]);
return false;
}
if ((stream_size < 0 || stream_size % 160 != 0) || (extended_stream_size < 0 || extended_stream_size % 160 != 0)) {
std::cout <<
"Stream buffer size must be multiples of 160\n";
return false;
}
return true;
}
#endif // __ARGS_H__
| 5,057
|
C++
|
.h
| 150
| 25.793333
| 119
| 0.561562
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,118
|
tfmodelstate.h
|
mozilla_DeepSpeech/native_client/tfmodelstate.h
|
#ifndef TFMODELSTATE_H
#define TFMODELSTATE_H
#include <vector>
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/util/memmapped_file_system.h"
#include "modelstate.h"
struct TFModelState : public ModelState
{
std::unique_ptr<tensorflow::MemmappedEnv> mmap_env_;
std::unique_ptr<tensorflow::Session> session_;
tensorflow::GraphDef graph_def_;
TFModelState();
virtual ~TFModelState();
virtual int init(const char* model_path) override;
virtual void infer(const std::vector<float>& mfcc,
unsigned int n_frames,
const std::vector<float>& previous_state_c,
const std::vector<float>& previous_state_h,
std::vector<float>& logits_output,
std::vector<float>& state_c_output,
std::vector<float>& state_h_output) override;
virtual void compute_mfcc(const std::vector<float>& audio_buffer,
std::vector<float>& mfcc_output) override;
};
#endif // TFMODELSTATE_H
| 1,092
|
C++
|
.h
| 26
| 34.115385
| 70
| 0.663198
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,119
|
ctc_beam_search_decoder.h
|
mozilla_DeepSpeech/native_client/ctcdecode/ctc_beam_search_decoder.h
|
#ifndef CTC_BEAM_SEARCH_DECODER_H_
#define CTC_BEAM_SEARCH_DECODER_H_
#include <memory>
#include <string>
#include <vector>
#include "scorer.h"
#include "output.h"
#include "alphabet.h"
class DecoderState {
int abs_time_step_;
int space_id_;
int blank_id_;
size_t beam_size_;
double cutoff_prob_;
size_t cutoff_top_n_;
bool start_expanding_;
std::shared_ptr<Scorer> ext_scorer_;
std::vector<PathTrie*> prefixes_;
std::unique_ptr<PathTrie> prefix_root_;
TimestepTreeNode timestep_tree_root_{nullptr, 0};
std::unordered_map<std::string, float> hot_words_;
public:
DecoderState() = default;
~DecoderState() = default;
// Disallow copying
DecoderState(const DecoderState&) = delete;
DecoderState& operator=(DecoderState&) = delete;
/* Initialize CTC beam search decoder
*
* Parameters:
* alphabet: The alphabet.
* beam_size: The width of beam search.
* cutoff_prob: Cutoff probability for pruning.
* cutoff_top_n: Cutoff number for pruning.
* ext_scorer: External scorer to evaluate a prefix, which consists of
* n-gram language model scoring and word insertion term.
* Default null, decoding the input sample without scorer.
* Return:
* Zero on success, non-zero on failure.
*/
int init(const Alphabet& alphabet,
size_t beam_size,
double cutoff_prob,
size_t cutoff_top_n,
std::shared_ptr<Scorer> ext_scorer,
std::unordered_map<std::string, float> hot_words);
/* Send data to the decoder
*
* Parameters:
* probs: 2-D vector where each element is a vector of probabilities
* over alphabet of one time step.
* time_dim: Number of timesteps.
* class_dim: Number of classes (alphabet length + 1 for space character).
*/
void next(const double *probs,
int time_dim,
int class_dim);
/* Get up to num_results transcriptions from current decoder state.
*
* Parameters:
* num_results: Number of beams to return.
*
* Return:
* A vector where each element is a pair of score and decoding result,
* in descending order.
*/
std::vector<Output> decode(size_t num_results=1) const;
};
/* CTC Beam Search Decoder
* Parameters:
* probs: 2-D vector where each element is a vector of probabilities
* over alphabet of one time step.
* time_dim: Number of timesteps.
* class_dim: Alphabet length (plus 1 for space character).
* alphabet: The alphabet.
* beam_size: The width of beam search.
* cutoff_prob: Cutoff probability for pruning.
* cutoff_top_n: Cutoff number for pruning.
* ext_scorer: External scorer to evaluate a prefix, which consists of
* n-gram language model scoring and word insertion term.
* Default null, decoding the input sample without scorer.
* hot_words: A map of hot-words and their corresponding boosts
* The hot-word is a string and the boost is a float.
* num_results: Number of beams to return.
* Return:
* A vector where each element is a pair of score and decoding result,
* in descending order.
*/
std::vector<Output> ctc_beam_search_decoder(
const double* probs,
int time_dim,
int class_dim,
const Alphabet &alphabet,
size_t beam_size,
double cutoff_prob,
size_t cutoff_top_n,
std::shared_ptr<Scorer> ext_scorer,
std::unordered_map<std::string, float> hot_words,
size_t num_results=1);
/* CTC Beam Search Decoder for batch data
* Parameters:
* probs: 3-D vector where each element is a 2-D vector that can be used
* by ctc_beam_search_decoder().
* alphabet: The alphabet.
* beam_size: The width of beam search.
* num_processes: Number of threads for beam search.
* cutoff_prob: Cutoff probability for pruning.
* cutoff_top_n: Cutoff number for pruning.
* ext_scorer: External scorer to evaluate a prefix, which consists of
* n-gram language model scoring and word insertion term.
* Default null, decoding the input sample without scorer.
* hot_words: A map of hot-words and their corresponding boosts
* The hot-word is a string and the boost is a float.
* num_results: Number of beams to return.
* Return:
* A 2-D vector where each element is a vector of beam search decoding
* result for one audio sample.
*/
std::vector<std::vector<Output>>
ctc_beam_search_decoder_batch(
const double* probs,
int batch_size,
int time_dim,
int class_dim,
const int* seq_lengths,
int seq_lengths_size,
const Alphabet &alphabet,
size_t beam_size,
size_t num_processes,
double cutoff_prob,
size_t cutoff_top_n,
std::shared_ptr<Scorer> ext_scorer,
std::unordered_map<std::string, float> hot_words,
size_t num_results=1);
#endif // CTC_BEAM_SEARCH_DECODER_H_
| 5,002
|
C++
|
.h
| 135
| 33.474074
| 80
| 0.669895
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,120
|
scorer.h
|
mozilla_DeepSpeech/native_client/ctcdecode/scorer.h
|
#ifndef SCORER_H_
#define SCORER_H_
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "lm/virtual_interface.hh"
#include "lm/word_index.hh"
#include "util/string_piece.hh"
#include "path_trie.h"
#include "alphabet.h"
#include "deepspeech.h"
const double OOV_SCORE = -1000.0;
const std::string START_TOKEN = "<s>";
const std::string UNK_TOKEN = "<unk>";
const std::string END_TOKEN = "</s>";
/* External scorer to query score for n-gram or sentence, including language
* model scoring and word insertion.
*
* Example:
* Scorer scorer(alpha, beta, "path_of_language_model");
* scorer.get_log_cond_prob({ "WORD1", "WORD2", "WORD3" });
*/
class Scorer {
public:
using FstType = PathTrie::FstType;
Scorer() = default;
~Scorer() = default;
// disallow copying
Scorer(const Scorer&) = delete;
Scorer& operator=(const Scorer&) = delete;
int init(const std::string &lm_path,
const Alphabet &alphabet);
int init(const std::string &lm_path,
const std::string &alphabet_config_path);
double get_log_cond_prob(const std::vector<std::string> &words,
bool bos = false,
bool eos = false);
double get_log_cond_prob(const std::vector<std::string>::const_iterator &begin,
const std::vector<std::string>::const_iterator &end,
bool bos = false,
bool eos = false);
// return the max order
size_t get_max_order() const { return max_order_; }
// return true if the language model is character based
bool is_utf8_mode() const { return is_utf8_mode_; }
// reset params alpha & beta
void reset_params(float alpha, float beta);
// force set UTF-8 mode, ignore value read from file
void set_utf8_mode(bool utf8) { is_utf8_mode_ = utf8; }
// make ngram for a given prefix
std::vector<std::string> make_ngram(PathTrie *prefix);
// trransform the labels in index to the vector of words (word based lm) or
// the vector of characters (character based lm)
std::vector<std::string> split_labels_into_scored_units(const std::vector<unsigned int> &labels);
void set_alphabet(const Alphabet& alphabet);
// save dictionary in file
bool save_dictionary(const std::string &path, bool append_instead_of_overwrite=false);
// return weather this step represents a boundary where beam scoring should happen
bool is_scoring_boundary(PathTrie* prefix, size_t new_label);
// fill dictionary FST from a vocabulary
void fill_dictionary(const std::unordered_set<std::string> &vocabulary);
// load language model from given path
int load_lm(const std::string &lm_path);
// language model weight
double alpha = 0.;
// word insertion weight
double beta = 0.;
// pointer to the dictionary of FST
std::unique_ptr<FstType> dictionary;
protected:
// necessary setup after setting alphabet
void setup_char_map();
int load_trie(std::ifstream& fin, const std::string& file_path);
private:
std::unique_ptr<lm::base::Model> language_model_;
bool is_utf8_mode_ = true;
size_t max_order_ = 0;
int SPACE_ID_;
Alphabet alphabet_;
std::unordered_map<std::string, int> char_map_;
};
#endif // SCORER_H_
| 3,292
|
C++
|
.h
| 84
| 34.785714
| 99
| 0.688267
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,121
|
path_trie.h
|
mozilla_DeepSpeech/native_client/ctcdecode/path_trie.h
|
#ifndef PATH_TRIE_H
#define PATH_TRIE_H
#include <algorithm>
#include <limits>
#include <memory>
#include <utility>
#include <vector>
#include "fst/fstlib.h"
#include "alphabet.h"
#include "object_pool.h"
/* Tree structure with parent and children information
* It is used to store the timesteps data for the PathTrie below
*/
template<class DataT>
struct TreeNode {
TreeNode<DataT>* parent;
std::vector<std::unique_ptr< TreeNode<DataT>, godefv::object_pool_deleter_t<TreeNode<DataT>> >> children;
DataT data;
TreeNode(TreeNode<DataT>* parent_, DataT const& data_): parent{parent_}, data{data_} {}
};
/* Creates a new TreeNode<NodeDataT> with given data as a child to the given node.
* Returns a pointer to the created node. This pointer remains valid as long as the child is not destroyed.
*/
template<class NodeDataT, class ChildDataT>
TreeNode<NodeDataT>* add_child(TreeNode<NodeDataT>* tree_node, ChildDataT&& data);
/* Returns the sequence of tree node's data from the given root (exclusive) to the given tree_node (inclusive).
* By default (if no root is provided), the full sequence from the root of the tree is returned.
*/
template<class DataT>
std::vector<DataT> get_history(TreeNode<DataT> const* tree_node, TreeNode<DataT> const* root = nullptr);
using TimestepTreeNode = TreeNode<unsigned int>;
/* Trie tree for prefix storing and manipulating, with a dictionary in
* finite-state transducer for spelling correction.
*/
class PathTrie {
public:
using FstType = fst::ConstFst<fst::StdArc>;
PathTrie();
~PathTrie();
// get new prefix after appending new char
PathTrie* get_path_trie(unsigned int new_char, float log_prob_c, bool reset = true);
// get the prefix data in correct time order from root to current node
void get_path_vec(std::vector<unsigned int>& output);
// get the prefix data in correct time order from beginning of last grapheme to current node
PathTrie* get_prev_grapheme(std::vector<unsigned int>& output,
const Alphabet& alphabet);
// get the distance from current node to the first codepoint boundary, and the byte value at the boundary
int distance_to_codepoint_boundary(unsigned char *first_byte, const Alphabet& alphabet);
// get the prefix data in correct time order from beginning of last word to current node
PathTrie* get_prev_word(std::vector<unsigned int>& output,
const Alphabet& alphabet);
// update log probs
void iterate_to_vec(std::vector<PathTrie*>& output);
// set dictionary for FST
void set_dictionary(std::shared_ptr<FstType> dictionary);
void set_matcher(std::shared_ptr<fst::SortedMatcher<FstType>>);
bool is_empty() { return ROOT_ == character; }
// remove current path from root
void remove();
#ifdef DEBUG
void vec(std::vector<PathTrie*>& out);
void print(const Alphabet& a);
#endif // DEBUG
float log_prob_b_prev;
float log_prob_nb_prev;
float log_prob_b_cur;
float log_prob_nb_cur;
float log_prob_c;
float score;
float approx_ctc;
unsigned int character;
TimestepTreeNode* timesteps = nullptr;
// timestep temporary storage for each decoding step.
TimestepTreeNode* previous_timesteps = nullptr;
unsigned int new_timestep;
PathTrie* parent;
private:
int ROOT_;
bool exists_;
bool has_dictionary_;
std::vector<std::pair<unsigned int, PathTrie*>> children_;
// pointer to dictionary of FST
std::shared_ptr<FstType> dictionary_;
FstType::StateId dictionary_state_;
std::shared_ptr<fst::SortedMatcher<FstType>> matcher_;
};
// TreeNode implementation
template<class NodeDataT, class ChildDataT>
TreeNode<NodeDataT>* add_child(TreeNode<NodeDataT>* tree_node, ChildDataT&& data) {
static thread_local godefv::object_pool_t<TreeNode<NodeDataT>> tree_node_pool;
tree_node->children.push_back(tree_node_pool.make_unique(tree_node, std::forward<ChildDataT>(data)));
return tree_node->children.back().get();
}
template<class DataT>
void get_history_helper(TreeNode<DataT> const* tree_node, TreeNode<DataT> const* root, std::vector<DataT>* output) {
if (tree_node == root) return;
assert(tree_node != nullptr);
assert(tree_node->parent != tree_node);
get_history_helper(tree_node->parent, root, output);
output->push_back(tree_node->data);
}
template<class DataT>
std::vector<DataT> get_history(TreeNode<DataT> const* tree_node, TreeNode<DataT> const* root) {
std::vector<DataT> output;
get_history_helper(tree_node, root, &output);
return output;
}
#endif // PATH_TRIE_H
| 4,564
|
C++
|
.h
| 108
| 38.990741
| 116
| 0.738757
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,186
|
types.h
|
mozilla_DeepSpeech/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/types.h
|
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Various type definitions (mostly for Google compatibility).
#include <cstddef> // For std::ptrdiff_t.
#include <cstdlib> // for ssize_t.
#include <cstdint> // for ?int*_t.
#ifndef FST_LIB_TYPES_H_
#define FST_LIB_TYPES_H_
//using ssize_t = std::ptrdiff_t;
//#ifdef _MSC_VER
// Not really Windows-specific: they should have used ptrdiff_t in the first
// place. But on Windows there has never been ssize_t.
//using ssize_t = std::ptrdiff_t;
//#endif // _MSC_VER
#endif // FST_LIB_TYPES_H_
| 1,182
|
C++
|
.h
| 28
| 41.035714
| 76
| 0.73107
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,236
|
config.h
|
mozilla_DeepSpeech/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/config.h
|
// Windows-specific OpenFst config file
// No dynamic registration.
#define FST_NO_DYNAMIC_LINKING 1
| 101
|
C++
|
.h
| 3
| 32.666667
| 39
| 0.806122
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,311
|
farlib.h
|
mozilla_DeepSpeech/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/extensions/far/farlib.h
|
// See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// A finite-state archive (FAR) is used to store an indexable collection of
// FSTs in a single file. Utilities are provided to create FARs from FSTs,
// to iterate over FARs, and to extract specific FSTs from FARs.
#ifndef FST_EXTENSIONS_FAR_FARLIB_H_
#define FST_EXTENSIONS_FAR_FARLIB_H_
#include <fst/extensions/far/compile-strings.h>
#include <fst/extensions/far/create.h>
#include <fst/extensions/far/extract.h>
#include <fst/extensions/far/far.h>
#include <fst/extensions/far/getters.h>
#include <fst/extensions/far/info.h>
#include <fst/extensions/far/print-strings.h>
#endif // FST_EXTENSIONS_FAR_FARLIB_H_
| 726
|
C++
|
.h
| 16
| 44.1875
| 75
| 0.783593
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,315
|
nthbit.h
|
mozilla_DeepSpeech/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/extensions/ngram/nthbit.h
|
// See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#ifndef FST_EXTENSIONS_NGRAM_NTHBIT_H_
#define FST_EXTENSIONS_NGRAM_NTHBIT_H_
#include <fst/types.h>
#include <fst/compat.h>
extern uint32_t nth_bit_bit_offset[];
inline uint32_t nth_bit(uint64_t v, uint32_t r) {
uint32_t shift = 0;
uint32_t c = __builtin_popcount(v & 0xffffffff);
uint32_t mask = -(r > c);
r -= c & mask;
shift += (32 & mask);
c = __builtin_popcount((v >> shift) & 0xffff);
mask = -(r > c);
r -= c & mask;
shift += (16 & mask);
c = __builtin_popcount((v >> shift) & 0xff);
mask = -(r > c);
r -= c & mask;
shift += (8 & mask);
return shift +
((nth_bit_bit_offset[(v >> shift) & 0xff] >> ((r - 1) << 2)) & 0xf);
}
#endif // FST_EXTENSIONS_NGRAM_NTHBIT_H_
| 821
|
C++
|
.h
| 25
| 30.04
| 77
| 0.620558
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,319
|
mpdtlib.h
|
mozilla_DeepSpeech/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/extensions/mpdt/mpdtlib.h
|
// See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// This is an experimental multipush-down transducer (MPDT) library. An MPDT is
// encoded as an FST, where some transitions are labeled with open or close
// parentheses, each mated pair of which is associated to one stack. To be
// interpreted as an MPDT, the parentheses within a stack must balance on a
// path.
#ifndef FST_EXTENSIONS_MPDT_MPDTLIB_H_
#define FST_EXTENSIONS_MPDT_MPDTLIB_H_
#include <fst/extensions/mpdt/compose.h>
#include <fst/extensions/mpdt/expand.h>
#include <fst/extensions/mpdt/mpdt.h>
#include <fst/extensions/mpdt/reverse.h>
#endif // FST_EXTENSIONS_MPDT_MPDTLIB_H_
| 706
|
C++
|
.h
| 15
| 45.866667
| 79
| 0.784884
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,339
|
pdtlib.h
|
mozilla_DeepSpeech/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/extensions/pdt/pdtlib.h
|
// See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// This is an experimental push-down transducer (PDT) library. A PDT is
// encoded as an FST, where some transitions are labeled with open or close
// parentheses. To be interpreted as a PDT, the parentheses must balance on a
// path.
#ifndef FST_EXTENSIONS_PDT_PDTLIB_H_
#define FST_EXTENSIONS_PDT_PDTLIB_H_
#include <fst/extensions/pdt/compose.h>
#include <fst/extensions/pdt/expand.h>
#include <fst/extensions/pdt/pdt.h>
#include <fst/extensions/pdt/replace.h>
#include <fst/extensions/pdt/reverse.h>
#include <fst/extensions/pdt/shortest-path.h>
#endif // FST_EXTENSIONS_PDT_PDTLIB_H_
| 700
|
C++
|
.h
| 16
| 42.5625
| 77
| 0.781204
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,461
|
nthbit.h
|
mozilla_DeepSpeech/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/extensions/ngram/nthbit.h
|
// See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#ifndef FST_EXTENSIONS_NGRAM_NTHBIT_H_
#define FST_EXTENSIONS_NGRAM_NTHBIT_H_
#include <fst/types.h>
extern uint32 nth_bit_bit_offset[];
inline uint32 nth_bit(uint64 v, uint32 r) {
uint32 shift = 0;
uint32 c = __builtin_popcount(v & 0xffffffff);
uint32 mask = -(r > c);
r -= c & mask;
shift += (32 & mask);
c = __builtin_popcount((v >> shift) & 0xffff);
mask = -(r > c);
r -= c & mask;
shift += (16 & mask);
c = __builtin_popcount((v >> shift) & 0xff);
mask = -(r > c);
r -= c & mask;
shift += (8 & mask);
return shift +
((nth_bit_bit_offset[(v >> shift) & 0xff] >> ((r - 1) << 2)) & 0xf);
}
#endif // FST_EXTENSIONS_NGRAM_NTHBIT_H_
| 783
|
C++
|
.h
| 24
| 29.75
| 77
| 0.619174
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,485
|
unique_ptr.h
|
mozilla_DeepSpeech/native_client/ctcdecode/third_party/object_pool/unique_ptr.h
|
#ifndef GODEFV_MEMORY_ALLOCATED_UNIQUE_PTR_H
#define GODEFV_MEMORY_ALLOCATED_UNIQUE_PTR_H
#include <memory>
namespace godefv{
//! A deleter to deallocate memory which have been allocated by the given allocator.
template<class Allocator>
struct allocator_deleter_t
{
allocator_deleter_t(Allocator const& allocator) :
mAllocator{ allocator }
{}
void operator()(typename Allocator::value_type* ptr)
{
mAllocator.deallocate(ptr, 1);
}
private:
Allocator mAllocator;
};
//! A smart pointer like std::unique_ptr but templated on an allocator instead of a deleter.
//! The deleter is deduced from the given allocator.
template<class T, class Allocator = std::allocator<T>>
struct unique_ptr_t : public std::unique_ptr<T, allocator_deleter_t<Allocator>>
{
using base_t = std::unique_ptr<T, allocator_deleter_t<Allocator>>;
unique_ptr_t(Allocator allocator = Allocator{}) :
base_t{ allocator.allocate(1), allocator_deleter_t<Allocator>{ allocator } }
{}
};
} // namespace godefv
#endif // GODEFV_MEMORY_ALLOCATED_UNIQUE_PTR_H
| 1,044
|
C++
|
.h
| 30
| 32.9
| 92
| 0.768159
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,486
|
object_pool.h
|
mozilla_DeepSpeech/native_client/ctcdecode/third_party/object_pool/object_pool.h
|
#ifndef GODEFV_MEMORY_OBJECT_POOL_H
#define GODEFV_MEMORY_OBJECT_POOL_H
#include "unique_ptr.h"
#include <memory>
#include <vector>
#include <array>
namespace godefv{
// Forward declaration
template<class Object, template<class T> class Allocator = std::allocator, std::size_t ChunkSize = 1024>
class object_pool_t;
//! Custom deleter to recycle the deleted pointers of the object_pool_t.
template<class Object, template<class T> class Allocator = std::allocator, std::size_t ChunkSize = 1024>
struct object_pool_deleter_t{
private:
object_pool_t<Object, Allocator, ChunkSize>* object_pool_ptr;
public:
explicit object_pool_deleter_t(decltype(object_pool_ptr) input_object_pool_ptr) :
object_pool_ptr(input_object_pool_ptr)
{}
void operator()(Object* object_ptr)
{
object_pool_ptr->delete_object(object_ptr);
}
};
//! Allocates instances of Object efficiently (constant time and log((maximum number of Objects used at the same time)/ChunkSize) calls to malloc in the whole lifetime of the object pool).
//! When an instance returned by the object pool is destroyed, its allocated memory is recycled by the object pool. Defragmenting the object pool to free memory is not possible.
template<class Object, template<class T> class Allocator, std::size_t ChunkSize>
class object_pool_t{
//! An object slot is an uninitialized memory space of the same size as Object.
//! It is initially "free". It can then be "used" to construct an Object in place and the pointer to it is returned by the object pool. When the pointer is destroyed, the object slot is "recycled" and can be used again but it is not "free" anymore because "free" object slots are contiguous in memory.
using object_slot_t=std::array<char, sizeof(Object)>;
//! To minimize calls to malloc, the object slots are allocated in chunks.
//! For example, if ChunkSize=8, a chunk may look like this : |used|recycled|used|used|recycled|free|free|free|. In this example, if more than 5 new Object are now asked from the object pool, at least one new chunk of 8 object slots will be allocated.
using chunk_t=std::array<object_slot_t, ChunkSize>;
Allocator<chunk_t> chunk_allocator; //!< This allocator can be used to have aligned memory if required.
std::vector<unique_ptr_t<chunk_t, decltype(chunk_allocator)>> memory_chunks;
//! Recycled object slots are tracked using a stack of pointers to them. When an object slot is recycled, a pointer to it is pushed in constant time. When a new object is constructed, a recycled object slot can be found and poped in constant time.
std::vector<object_slot_t*> recycled_object_slots;
object_slot_t* free_object_slots_begin;
object_slot_t* free_object_slots_end;
//! When a pointer provided by the ObjectPool is deleted, its memory is converted to an object slot to be recycled.
void delete_object(Object* object_ptr){
object_ptr->~Object();
recycled_object_slots.push_back(reinterpret_cast<object_slot_t*>(object_ptr));
}
friend object_pool_deleter_t<Object, Allocator, ChunkSize>;
public:
using object_t = Object;
using deleter_t = object_pool_deleter_t<Object, Allocator, ChunkSize>;
using object_unique_ptr_t = std::unique_ptr<object_t, deleter_t>; //!< The type returned by the object pool.
object_pool_t(Allocator<chunk_t> const& allocator = Allocator<chunk_t>{}) :
chunk_allocator{ allocator },
free_object_slots_begin{ free_object_slots_end } // At the begining, set the 2 iterators at the same value to simulate a full pool.
{}
//! Returns a unique pointer to an object_t using an unused object slot from the object pool.
template<class... Args> object_unique_ptr_t make_unique(Args&&... vars){
auto construct_object_unique_ptr=[&](object_slot_t* object_slot){
return object_unique_ptr_t{ new (reinterpret_cast<object_t*>(object_slot)) object_t{ std::forward<Args>(vars)... } , deleter_t{ this } };
};
// If a recycled object slot is available, use it.
if (!recycled_object_slots.empty())
{
auto object_slot = recycled_object_slots.back();
recycled_object_slots.pop_back();
return construct_object_unique_ptr(object_slot);
}
// If the pool is full: add a new chunk.
if (free_object_slots_begin == free_object_slots_end)
{
memory_chunks.emplace_back(chunk_allocator);
auto& new_chunk = memory_chunks.back();
free_object_slots_begin=new_chunk->data();
free_object_slots_end =free_object_slots_begin+new_chunk->size();
}
// We know that there is now at least one free object slot, use it.
return construct_object_unique_ptr(free_object_slots_begin++);
}
//! Returns the total number of object slots (free, recycled, or used).
std::size_t capacity() const{
return memory_chunks.size()*ChunkSize;
}
//! Returns the number of currently used object slots.
std::size_t size() const{
return capacity() - static_cast<std::size_t>(free_object_slots_end-free_object_slots_begin) - recycled_object_slots.size();
}
};
} /* namespace godefv */
#endif /* GODEFV_MEMORY_OBJECT_POOL_H */
| 5,004
|
C++
|
.h
| 88
| 54.375
| 302
| 0.74857
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,487
|
deepspeech_ios.h
|
mozilla_DeepSpeech/native_client/swift/deepspeech_ios/deepspeech_ios.h
|
//
// deepspeech_ios.h
// deepspeech_ios
//
// Created by Reuben Morais on 14.06.20.
// Copyright © 2020 Mozilla. All rights reserved.
//
#import <Foundation/Foundation.h>
// In this header, you should import all the public headers of your framework using statements like #import <deepspeech_ios/PublicHeader.h>
| 321
|
C++
|
.h
| 9
| 34.222222
| 139
| 0.756494
|
mozilla/DeepSpeech
| 25,099
| 3,941
| 150
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
2,586
|
main.cpp
|
flameshot-org_flameshot/external/singleapplication/examples/calculator/main.cpp
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QApplication>
#include <singleapplication.h>
#include "calculator.h"
int main(int argc, char* argv[])
{
SingleApplication app(argc, argv);
Calculator calc;
QObject::connect(&app, &SingleApplication::instanceStarted, [&calc]() {
calc.raise();
calc.activateWindow();
});
calc.show();
return app.exec();
}
| 2,886
|
C++
|
.cpp
| 63
| 42.920635
| 78
| 0.697186
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
2,594
|
color_delegate.cpp
|
flameshot-org_flameshot/external/Qt-Color-Widgets/src/QtColorWidgets/color_delegate.cpp
|
/**
* \file
*
* \author Mattia Basaglia
*
* \copyright Copyright (C) 2013-2020 Mattia Basaglia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "QtColorWidgets/color_delegate.hpp"
#include "QtColorWidgets/color_selector.hpp"
#include "QtColorWidgets/color_dialog.hpp"
#include <QPainter>
#include <QMouseEvent>
#include <QApplication>
void color_widgets::ReadOnlyColorDelegate::paintItem(
QPainter* painter,
const QStyleOptionViewItem& option,
const QModelIndex& index,
const QBrush& brush
) const
{
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
const QWidget* widget = option.widget;
opt.showDecorationSelected = true;
QStyle *style = widget ? widget->style() : QApplication::style();
QRect geom = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, widget);
opt.text = "";
QStyleOptionFrame panel;
panel.initFrom(option.widget);
if (option.widget->isEnabled())
panel.state = QStyle::State_Enabled;
panel.rect = geom;
panel.lineWidth = 2;
panel.midLineWidth = 0;
panel.state |= QStyle::State_Sunken;
style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);
style->drawPrimitive(QStyle::PE_Frame, &panel, painter, nullptr);
QRect r = style->subElementRect(QStyle::SE_FrameContents, &panel, nullptr);
painter->fillRect(r, brush);
}
void color_widgets::ReadOnlyColorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if ( index.data().type() == QVariant::Color )
{
paintItem(painter, option, index, index.data().value<QColor>());
}
else
{
QStyledItemDelegate::paint(painter, option, index);
}
}
QSize color_widgets::ReadOnlyColorDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if ( index.data().type() == QVariant::Color )
return size_hint;
return QStyledItemDelegate::sizeHint(option, index);
}
void color_widgets::ReadOnlyColorDelegate::setSizeHintForColor(const QSize& size_hint)
{
this->size_hint = size_hint;
}
const QSize& color_widgets::ReadOnlyColorDelegate::sizeHintForColor() const
{
return size_hint;
}
QWidget *color_widgets::ColorDelegate::createEditor(
QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if ( index.data().type() == QVariant::Color )
{
ColorDialog *editor = new ColorDialog(const_cast<QWidget*>(parent));
connect(editor, &QDialog::accepted, this, &ColorDelegate::close_editor);
connect(editor, &ColorDialog::colorSelected, this, &ColorDelegate::color_changed);
return editor;
}
return QStyledItemDelegate::createEditor(parent, option, index);
}
void color_widgets::ColorDelegate::color_changed()
{
ColorDialog *editor = qobject_cast<ColorDialog*>(sender());
emit commitData(editor);
}
void color_widgets::ColorDelegate::close_editor()
{
ColorDialog *editor = qobject_cast<ColorDialog*>(sender());
emit closeEditor(editor);
}
void color_widgets::ColorDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
if ( index.data().type() == QVariant::Color )
{
ColorDialog *selector = qobject_cast<ColorDialog*>(editor);
selector->setColor(qvariant_cast<QColor>(index.data()));
return;
}
QStyledItemDelegate::setEditorData(editor, index);
}
void color_widgets::ColorDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
if ( index.data().type() == QVariant::Color )
{
ColorDialog *selector = qobject_cast<ColorDialog *>(editor);
model->setData(index, QVariant::fromValue(selector->color()));
return;
}
QStyledItemDelegate::setModelData(editor, model, index);
}
void color_widgets::ColorDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if ( index.data().type() == QVariant::Color )
{
return;
}
QStyledItemDelegate::updateEditorGeometry(editor, option, index);
}
bool color_widgets::ColorDelegate::eventFilter(QObject * watched, QEvent * event)
{
if ( event->type() == QEvent::Hide )
{
if ( auto editor = qobject_cast<ColorDialog*>(watched) )
{
emit closeEditor(editor, QAbstractItemDelegate::NoHint);
return false;
}
}
return QStyledItemDelegate::eventFilter(watched, event);
}
| 5,348
|
C++
|
.cpp
| 146
| 31.335616
| 120
| 0.695383
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
2,627
|
main.cpp
|
flameshot-org_flameshot/src/main.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#ifndef USE_EXTERNAL_SINGLEAPPLICATION
#include "singleapplication.h"
#else
#include "QtSolutions/qtsingleapplication.h"
#endif
#include "abstractlogger.h"
#include "src/cli/commandlineparser.h"
#include "src/config/cacheutils.h"
#include "src/config/styleoverride.h"
#include "src/core/capturerequest.h"
#include "src/core/flameshot.h"
#include "src/core/flameshotdaemon.h"
#include "src/utils/confighandler.h"
#include "src/utils/filenamehandler.h"
#include "src/utils/pathinfo.h"
#include "src/utils/valuehandler.h"
#include <QApplication>
#include <QDir>
#include <QLibraryInfo>
#include <QSharedMemory>
#include <QTimer>
#include <QTranslator>
#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX)
#include "abstractlogger.h"
#include "src/core/flameshotdbusadapter.h"
#include <QApplication>
#include <QDBusConnection>
#include <QDBusMessage>
#include <desktopinfo.h>
#endif
#ifdef Q_OS_LINUX
// source: https://github.com/ksnip/ksnip/issues/416
void wayland_hacks()
{
// Workaround to https://github.com/ksnip/ksnip/issues/416
DesktopInfo info;
if (info.windowManager() == DesktopInfo::GNOME) {
qputenv("QT_QPA_PLATFORM", "xcb");
}
}
#endif
void requestCaptureAndWait(const CaptureRequest& req)
{
Flameshot* flameshot = Flameshot::instance();
flameshot->requestCapture(req);
QObject::connect(flameshot, &Flameshot::captureTaken, [&](const QPixmap&) {
#if defined(Q_OS_MACOS)
// Only useful on MacOS because each instance hosts its own widgets
if (!FlameshotDaemon::isThisInstanceHostingWidgets()) {
qApp->exit(0);
}
#else
// if this instance is not daemon, make sure it exit after caputre finish
if (FlameshotDaemon::instance() == nullptr && !Flameshot::instance()->haveExternalWidget()) {
qApp->exit(0);
}
#endif
});
QObject::connect(flameshot, &Flameshot::captureFailed, []() {
AbstractLogger::info() << "Screenshot aborted.";
qApp->exit(1);
});
qApp->exec();
}
QSharedMemory* guiMutexLock()
{
QString key = "org.flameshot.Flameshot-" APP_VERSION;
auto* shm = new QSharedMemory(key);
#ifdef Q_OS_UNIX
// Destroy shared memory if the last instance crashed on Unix
shm->attach();
delete shm;
shm = new QSharedMemory(key);
#endif
if (!shm->create(1)) {
return nullptr;
}
return shm;
}
QTranslator translator, qtTranslator;
void configureApp(bool gui)
{
if (gui) {
QApplication::setStyle(new StyleOverride);
}
// Configure translations
for (const QString& path : PathInfo::translationsPaths()) {
bool match = translator.load(QLocale(),
QStringLiteral("Internationalization"),
QStringLiteral("_"),
path);
if (match) {
break;
}
}
qtTranslator.load(QLocale::system(),
"qt",
"_",
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
auto app = QCoreApplication::instance();
app->installTranslator(&translator);
app->installTranslator(&qtTranslator);
app->setAttribute(Qt::AA_DontCreateNativeWidgetSiblings, true);
}
// TODO find a way so we don't have to do this
/// Recreate the application as a QApplication
void reinitializeAsQApplication(int& argc, char* argv[])
{
delete QCoreApplication::instance();
new QApplication(argc, argv);
configureApp(true);
}
int main(int argc, char* argv[])
{
#ifdef Q_OS_LINUX
wayland_hacks();
#endif
// required for the button serialization
// TODO: change to QVector in v1.0
qRegisterMetaTypeStreamOperators<QList<int>>("QList<int>");
QCoreApplication::setApplicationVersion(APP_VERSION);
QCoreApplication::setApplicationName(QStringLiteral("flameshot"));
QCoreApplication::setOrganizationName(QStringLiteral("flameshot"));
// no arguments, just launch Flameshot
if (argc == 1) {
#ifndef USE_EXTERNAL_SINGLEAPPLICATION
SingleApplication app(argc, argv);
#else
QtSingleApplication app(argc, argv);
#endif
configureApp(true);
auto c = Flameshot::instance();
FlameshotDaemon::start();
#if !(defined(Q_OS_MACOS) || defined(Q_OS_WIN))
new FlameshotDBusAdapter(c);
QDBusConnection dbus = QDBusConnection::sessionBus();
if (!dbus.isConnected()) {
AbstractLogger::error()
<< QObject::tr("Unable to connect via DBus");
}
dbus.registerObject(QStringLiteral("/"), c);
dbus.registerService(QStringLiteral("org.flameshot.Flameshot"));
#endif
return qApp->exec();
}
#if !defined(Q_OS_WIN)
/*--------------|
* CLI parsing |
* ------------*/
new QCoreApplication(argc, argv);
configureApp(false);
CommandLineParser parser;
// Add description
parser.setDescription(
QObject::tr("Powerful yet simple to use screenshot software."));
parser.setGeneralErrorMessage(QObject::tr("See") + " flameshot --help.");
// Arguments
CommandArgument fullArgument(
QStringLiteral("full"),
QObject::tr("Capture screenshot of all monitors at the same time."));
CommandArgument launcherArgument(QStringLiteral("launcher"),
QObject::tr("Open the capture launcher."));
CommandArgument guiArgument(
QStringLiteral("gui"),
QObject::tr("Start a manual capture in GUI mode."));
CommandArgument configArgument(QStringLiteral("config"),
QObject::tr("Configure") + " flameshot.");
CommandArgument screenArgument(
QStringLiteral("screen"),
QObject::tr("Capture a screenshot of the specified monitor."));
// Options
CommandOption pathOption(
{ "p", "path" },
QObject::tr("Existing directory or new file to save to"),
QStringLiteral("path"));
CommandOption clipboardOption(
{ "c", "clipboard" }, QObject::tr("Save the capture to the clipboard"));
CommandOption pinOption("pin",
QObject::tr("Pin the capture to the screen"));
CommandOption uploadOption({ "u", "upload" },
QObject::tr("Upload screenshot"));
CommandOption delayOption({ "d", "delay" },
QObject::tr("Delay time in milliseconds"),
QStringLiteral("milliseconds"));
CommandOption useLastRegionOption(
"last-region",
QObject::tr("Repeat screenshot with previously selected region"));
CommandOption regionOption("region",
QObject::tr("Screenshot region to select"),
QStringLiteral("WxH+X+Y or string"));
CommandOption filenameOption({ "f", "filename" },
QObject::tr("Set the filename pattern"),
QStringLiteral("pattern"));
CommandOption acceptOnSelectOption(
{ "s", "accept-on-select" },
QObject::tr("Accept capture as soon as a selection is made"));
CommandOption trayOption({ "t", "trayicon" },
QObject::tr("Enable or disable the trayicon"),
QStringLiteral("bool"));
CommandOption autostartOption(
{ "a", "autostart" },
QObject::tr("Enable or disable run at startup"),
QStringLiteral("bool"));
CommandOption checkOption(
"check", QObject::tr("Check the configuration for errors"));
CommandOption showHelpOption(
{ "s", "showhelp" },
QObject::tr("Show the help message in the capture mode"),
QStringLiteral("bool"));
CommandOption mainColorOption({ "m", "maincolor" },
QObject::tr("Define the main UI color"),
QStringLiteral("color-code"));
CommandOption contrastColorOption(
{ "k", "contrastcolor" },
QObject::tr("Define the contrast UI color"),
QStringLiteral("color-code"));
CommandOption rawImageOption({ "r", "raw" },
QObject::tr("Print raw PNG capture"));
CommandOption selectionOption(
{ "g", "print-geometry" },
QObject::tr("Print geometry of the selection in the format WxH+X+Y. Does "
"nothing if raw is specified"));
CommandOption screenNumberOption(
{ "n", "number" },
QObject::tr("Define the screen to capture (starting from 0)") + ",\n" +
QObject::tr("default: screen containing the cursor"),
QObject::tr("Screen number"),
QStringLiteral("-1"));
// Add checkers
auto colorChecker = [](const QString& colorCode) -> bool {
QColor parsedColor(colorCode);
return parsedColor.isValid() && parsedColor.alphaF() == 1.0;
};
QString colorErr =
QObject::tr("Invalid color, "
"this flag supports the following formats:\n"
"- #RGB (each of R, G, and B is a single hex digit)\n"
"- #RRGGBB\n- #RRRGGGBBB\n"
"- #RRRRGGGGBBBB\n"
"- Named colors like 'blue' or 'red'\n"
"You may need to escape the '#' sign as in '\\#FFF'");
const QString delayErr =
QObject::tr("Invalid delay, it must be a number greater than 0");
const QString numberErr =
QObject::tr("Invalid screen number, it must be non negative");
const QString regionErr = QObject::tr(
"Invalid region, use 'WxH+X+Y' or 'all' or 'screen0/screen1/...'.");
auto numericChecker = [](const QString& delayValue) -> bool {
bool ok;
int value = delayValue.toInt(&ok);
return ok && value >= 0;
};
auto regionChecker = [](const QString& region) -> bool {
Region valueHandler;
return valueHandler.check(region);
};
const QString pathErr =
QObject::tr("Invalid path, must be an existing directory or a new file "
"in an existing directory");
auto pathChecker = [pathErr](const QString& pathValue) -> bool {
QFileInfo fileInfo(pathValue);
if (fileInfo.isDir() || fileInfo.dir().exists()) {
return true;
} else {
AbstractLogger::error() << QObject::tr(pathErr.toLatin1().data());
return false;
}
};
const QString booleanErr =
QObject::tr("Invalid value, it must be defined as 'true' or 'false'");
auto booleanChecker = [](const QString& value) -> bool {
return value == QLatin1String("true") ||
value == QLatin1String("false");
};
contrastColorOption.addChecker(colorChecker, colorErr);
mainColorOption.addChecker(colorChecker, colorErr);
delayOption.addChecker(numericChecker, delayErr);
regionOption.addChecker(regionChecker, regionErr);
useLastRegionOption.addChecker(booleanChecker, booleanErr);
pathOption.addChecker(pathChecker, pathErr);
trayOption.addChecker(booleanChecker, booleanErr);
autostartOption.addChecker(booleanChecker, booleanErr);
showHelpOption.addChecker(booleanChecker, booleanErr);
screenNumberOption.addChecker(numericChecker, numberErr);
// Relationships
parser.AddArgument(guiArgument);
parser.AddArgument(screenArgument);
parser.AddArgument(fullArgument);
parser.AddArgument(launcherArgument);
parser.AddArgument(configArgument);
auto helpOption = parser.addHelpOption();
auto versionOption = parser.addVersionOption();
parser.AddOptions({ pathOption,
clipboardOption,
delayOption,
regionOption,
useLastRegionOption,
rawImageOption,
selectionOption,
uploadOption,
pinOption,
acceptOnSelectOption },
guiArgument);
parser.AddOptions({ screenNumberOption,
clipboardOption,
pathOption,
delayOption,
regionOption,
rawImageOption,
uploadOption,
pinOption },
screenArgument);
parser.AddOptions({ pathOption,
clipboardOption,
delayOption,
regionOption,
rawImageOption,
uploadOption },
fullArgument);
parser.AddOptions({ autostartOption,
filenameOption,
trayOption,
showHelpOption,
mainColorOption,
contrastColorOption,
checkOption },
configArgument);
// Parse
if (!parser.parse(qApp->arguments())) {
goto finish;
}
// PROCESS DATA
//--------------
Flameshot::setOrigin(Flameshot::CLI);
if (parser.isSet(helpOption) || parser.isSet(versionOption)) {
} else if (parser.isSet(launcherArgument)) { // LAUNCHER
reinitializeAsQApplication(argc, argv);
Flameshot* flameshot = Flameshot::instance();
flameshot->launcher();
qApp->exec();
} else if (parser.isSet(guiArgument)) { // GUI
reinitializeAsQApplication(argc, argv);
// Prevent multiple instances of 'flameshot gui' from running if not
// configured to do so.
if (!ConfigHandler().allowMultipleGuiInstances()) {
auto* mutex = guiMutexLock();
if (!mutex) {
return 1;
}
QObject::connect(
qApp, &QCoreApplication::aboutToQuit, qApp, [mutex]() {
mutex->detach();
delete mutex;
});
}
// Option values
QString path = parser.value(pathOption);
if (!path.isEmpty()) {
path = QDir(path).absolutePath();
}
int delay = parser.value(delayOption).toInt();
QString region = parser.value(regionOption);
bool useLastRegion = parser.isSet(useLastRegionOption);
bool clipboard = parser.isSet(clipboardOption);
bool raw = parser.isSet(rawImageOption);
bool printGeometry = parser.isSet(selectionOption);
bool pin = parser.isSet(pinOption);
bool upload = parser.isSet(uploadOption);
bool acceptOnSelect = parser.isSet(acceptOnSelectOption);
CaptureRequest req(CaptureRequest::GRAPHICAL_MODE, delay, path);
if (!region.isEmpty()) {
auto selectionRegion = Region().value(region).toRect();
req.setInitialSelection(selectionRegion);
} else if (useLastRegion) {
req.setInitialSelection(getLastRegion());
}
if (clipboard) {
req.addTask(CaptureRequest::COPY);
}
if (raw) {
req.addTask(CaptureRequest::PRINT_RAW);
}
if (!path.isEmpty()) {
req.addSaveTask(path);
}
if (printGeometry) {
req.addTask(CaptureRequest::PRINT_GEOMETRY);
}
if (pin) {
req.addTask(CaptureRequest::PIN);
}
if (upload) {
req.addTask(CaptureRequest::UPLOAD);
}
if (acceptOnSelect) {
req.addTask(CaptureRequest::ACCEPT_ON_SELECT);
if (!clipboard && !raw && path.isEmpty() && !printGeometry &&
!pin && !upload) {
req.addSaveTask();
}
}
requestCaptureAndWait(req);
} else if (parser.isSet(fullArgument)) { // FULL
reinitializeAsQApplication(argc, argv);
// Option values
QString path = parser.value(pathOption);
if (!path.isEmpty()) {
path = QDir(path).absolutePath();
}
int delay = parser.value(delayOption).toInt();
QString region = parser.value(regionOption);
bool clipboard = parser.isSet(clipboardOption);
bool raw = parser.isSet(rawImageOption);
bool upload = parser.isSet(uploadOption);
// Not a valid command
CaptureRequest req(CaptureRequest::FULLSCREEN_MODE, delay);
if (!region.isEmpty()) {
req.setInitialSelection(Region().value(region).toRect());
}
if (clipboard) {
req.addTask(CaptureRequest::COPY);
}
if (!path.isEmpty()) {
req.addSaveTask(path);
}
if (raw) {
req.addTask(CaptureRequest::PRINT_RAW);
}
if (upload) {
req.addTask(CaptureRequest::UPLOAD);
}
if (!clipboard && path.isEmpty() && !raw && !upload) {
req.addSaveTask();
}
requestCaptureAndWait(req);
} else if (parser.isSet(screenArgument)) { // SCREEN
reinitializeAsQApplication(argc, argv);
QString numberStr = parser.value(screenNumberOption);
// Option values
int screenNumber =
numberStr.startsWith(QLatin1String("-")) ? -1 : numberStr.toInt();
QString path = parser.value(pathOption);
if (!path.isEmpty()) {
path = QDir(path).absolutePath();
}
int delay = parser.value(delayOption).toInt();
QString region = parser.value(regionOption);
bool clipboard = parser.isSet(clipboardOption);
bool raw = parser.isSet(rawImageOption);
bool pin = parser.isSet(pinOption);
bool upload = parser.isSet(uploadOption);
CaptureRequest req(CaptureRequest::SCREEN_MODE, delay, screenNumber);
if (!region.isEmpty()) {
if (region.startsWith("screen")) {
AbstractLogger::error()
<< "The 'screen' command does not support "
"'--region screen<N>'.\n"
"See flameshot --help.\n";
exit(1);
}
req.setInitialSelection(Region().value(region).toRect());
}
if (clipboard) {
req.addTask(CaptureRequest::COPY);
}
if (raw) {
req.addTask(CaptureRequest::PRINT_RAW);
}
if (!path.isEmpty()) {
req.addSaveTask(path);
}
if (pin) {
req.addTask(CaptureRequest::PIN);
}
if (upload) {
req.addTask(CaptureRequest::UPLOAD);
}
if (!clipboard && !raw && path.isEmpty() && !pin && !upload) {
req.addSaveTask();
}
requestCaptureAndWait(req);
} else if (parser.isSet(configArgument)) { // CONFIG
bool autostart = parser.isSet(autostartOption);
bool filename = parser.isSet(filenameOption);
bool tray = parser.isSet(trayOption);
bool mainColor = parser.isSet(mainColorOption);
bool contrastColor = parser.isSet(contrastColorOption);
bool check = parser.isSet(checkOption);
bool someFlagSet =
(filename || tray || mainColor || contrastColor || check);
if (check) {
AbstractLogger err = AbstractLogger::error(AbstractLogger::Stderr);
bool ok = ConfigHandler().checkForErrors(&err);
if (ok) {
AbstractLogger::info()
<< QStringLiteral("No errors detected.\n");
goto finish;
} else {
return 1;
}
}
if (!someFlagSet) {
// Open gui when no options are given
reinitializeAsQApplication(argc, argv);
QObject::connect(
qApp, &QApplication::lastWindowClosed, qApp, &QApplication::quit);
Flameshot::instance()->config();
qApp->exec();
} else {
ConfigHandler config;
if (autostart) {
config.setStartupLaunch(parser.value(autostartOption) ==
"true");
}
if (filename) {
QString newFilename(parser.value(filenameOption));
config.setFilenamePattern(newFilename);
FileNameHandler fh;
QTextStream(stdout)
<< QStringLiteral("The new pattern is '%1'\n"
"Parsed pattern example: %2\n")
.arg(newFilename)
.arg(fh.parsedPattern());
}
if (tray) {
config.setDisabledTrayIcon(parser.value(trayOption) == "false");
}
if (mainColor) {
// TODO use value handler
QString colorCode = parser.value(mainColorOption);
QColor parsedColor(colorCode);
config.setUiColor(parsedColor);
}
if (contrastColor) {
QString colorCode = parser.value(contrastColorOption);
QColor parsedColor(colorCode);
config.setContrastUiColor(parsedColor);
}
}
}
finish:
#endif
return 0;
}
| 21,286
|
C++
|
.cpp
| 546
| 28.983516
| 101
| 0.590775
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,628
|
flameshot.cpp
|
flameshot-org_flameshot/src/core/flameshot.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "flameshot.h"
#include "flameshotdaemon.h"
#if defined(Q_OS_MACOS)
#include "external/QHotkey/QHotkey"
#endif
#include "abstractlogger.h"
#include "screenshotsaver.h"
#include "src/config/configresolver.h"
#include "src/config/configwindow.h"
#include "src/core/qguiappcurrentscreen.h"
#include "src/tools/imgupload/imguploadermanager.h"
#include "src/tools/imgupload/storages/imguploaderbase.h"
#include "src/utils/confighandler.h"
#include "src/utils/screengrabber.h"
#include "src/widgets/capture/capturewidget.h"
#include "src/widgets/capturelauncher.h"
#include "src/widgets/imguploaddialog.h"
#include "src/widgets/infowindow.h"
#include "src/widgets/uploadhistory.h"
#include <QApplication>
#include <QBuffer>
#include <QDebug>
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QFile>
#include <QMessageBox>
#include <QThread>
#include <QTimer>
#include <QUrl>
#include <QVersionNumber>
#if defined(Q_OS_MACOS)
#include <QScreen>
#endif
Flameshot::Flameshot()
: m_captureWindow(nullptr)
, m_haveExternalWidget(false)
#if defined(Q_OS_MACOS)
, m_HotkeyScreenshotCapture(nullptr)
, m_HotkeyScreenshotHistory(nullptr)
#endif
{
QString StyleSheet = CaptureButton::globalStyleSheet();
qApp->setStyleSheet(StyleSheet);
#if defined(Q_OS_MACOS)
// Try to take a test screenshot, MacOS will request a "Screen Recording"
// permissions on the first run. Otherwise it will be hidden under the
// CaptureWidget
QScreen* currentScreen = QGuiAppCurrentScreen().currentScreen();
currentScreen->grabWindow(QApplication::desktop()->winId(), 0, 0, 1, 1);
// set global shortcuts for MacOS
m_HotkeyScreenshotCapture = new QHotkey(
QKeySequence(ConfigHandler().shortcut("TAKE_SCREENSHOT")), true, this);
QObject::connect(m_HotkeyScreenshotCapture,
&QHotkey::activated,
qApp,
[this]() { gui(); });
m_HotkeyScreenshotHistory = new QHotkey(
QKeySequence(ConfigHandler().shortcut("SCREENSHOT_HISTORY")), true, this);
QObject::connect(m_HotkeyScreenshotHistory,
&QHotkey::activated,
qApp,
[this]() { history(); });
#endif
}
Flameshot* Flameshot::instance()
{
static Flameshot c;
return &c;
}
CaptureWidget* Flameshot::gui(const CaptureRequest& req)
{
if (!resolveAnyConfigErrors()) {
return nullptr;
}
#if defined(Q_OS_MACOS)
// This is required on MacOS because of Mission Control. If you'll switch to
// another Desktop you cannot take a new screenshot from the tray, you have
// to switch back to the Flameshot Desktop manually. It is not obvious and a
// large number of users are confused and report a bug.
if (m_captureWindow != nullptr) {
m_captureWindow->close();
delete m_captureWindow;
m_captureWindow = nullptr;
}
#endif
if (nullptr == m_captureWindow) {
// TODO is this unnecessary now?
int timeout = 5000; // 5 seconds
const int delay = 100;
QWidget* modalWidget = nullptr;
for (; timeout >= 0; timeout -= delay) {
modalWidget = qApp->activeModalWidget();
if (nullptr == modalWidget) {
break;
}
modalWidget->close();
modalWidget->deleteLater();
QThread::msleep(delay);
}
if (0 == timeout) {
QMessageBox::warning(
nullptr, tr("Error"), tr("Unable to close active modal widgets"));
return nullptr;
}
m_captureWindow = new CaptureWidget(req);
#ifdef Q_OS_WIN
m_captureWindow->show();
#elif defined(Q_OS_MACOS)
// In "Emulate fullscreen mode"
m_captureWindow->showFullScreen();
m_captureWindow->activateWindow();
m_captureWindow->raise();
#else
m_captureWindow->showFullScreen();
// m_captureWindow->show(); // For CaptureWidget Debugging under Linux
#endif
return m_captureWindow;
} else {
emit captureFailed();
return nullptr;
}
}
void Flameshot::screen(CaptureRequest req, const int screenNumber)
{
if (!resolveAnyConfigErrors()) {
return;
}
bool ok = true;
QScreen* screen;
if (screenNumber < 0) {
QPoint globalCursorPos = QCursor::pos();
screen = qApp->screenAt(globalCursorPos);
} else if (screenNumber >= qApp->screens().count()) {
AbstractLogger() << QObject::tr(
"Requested screen exceeds screen count");
emit captureFailed();
return;
} else {
screen = qApp->screens()[screenNumber];
}
QPixmap p(ScreenGrabber().grabScreen(screen, ok));
if (ok) {
QRect geometry = ScreenGrabber().screenGeometry(screen);
QRect region = req.initialSelection();
if (region.isNull()) {
region = ScreenGrabber().screenGeometry(screen);
} else {
QRect screenGeom = ScreenGrabber().screenGeometry(screen);
screenGeom.moveTopLeft({ 0, 0 });
region = region.intersected(screenGeom);
p = p.copy(region);
}
if (req.tasks() & CaptureRequest::PIN) {
// change geometry for pin task
req.addPinTask(region);
}
exportCapture(p, geometry, req);
} else {
emit captureFailed();
}
}
void Flameshot::full(const CaptureRequest& req)
{
if (!resolveAnyConfigErrors()) {
return;
}
bool ok = true;
QPixmap p(ScreenGrabber().grabEntireDesktop(ok));
QRect region = req.initialSelection();
if (!region.isNull()) {
p = p.copy(region);
}
if (ok) {
QRect selection; // `flameshot full` does not support --selection
exportCapture(p, selection, req);
} else {
emit captureFailed();
}
}
void Flameshot::launcher()
{
if (!resolveAnyConfigErrors()) {
return;
}
if (m_launcherWindow == nullptr) {
m_launcherWindow = new CaptureLauncher();
}
m_launcherWindow->show();
#if defined(Q_OS_MACOS)
m_launcherWindow->activateWindow();
m_launcherWindow->raise();
#endif
}
void Flameshot::config()
{
if (!resolveAnyConfigErrors()) {
return;
}
if (m_configWindow == nullptr) {
m_configWindow = new ConfigWindow();
m_configWindow->show();
#if defined(Q_OS_MACOS)
m_configWindow->activateWindow();
m_configWindow->raise();
#endif
}
}
void Flameshot::info()
{
if (m_infoWindow == nullptr) {
m_infoWindow = new InfoWindow();
#if defined(Q_OS_MACOS)
m_infoWindow->activateWindow();
m_infoWindow->raise();
#endif
}
}
void Flameshot::history()
{
static UploadHistory* historyWidget = nullptr;
if (historyWidget == nullptr) {
historyWidget = new UploadHistory;
historyWidget->loadHistory();
connect(historyWidget, &QObject::destroyed, this, []() {
historyWidget = nullptr;
});
}
historyWidget->show();
#if defined(Q_OS_MACOS)
historyWidget->activateWindow();
historyWidget->raise();
#endif
}
void Flameshot::openSavePath()
{
QString savePath = ConfigHandler().savePath();
if (!savePath.isEmpty()) {
QDesktopServices::openUrl(QUrl::fromLocalFile(savePath));
}
}
QVersionNumber Flameshot::getVersion()
{
return QVersionNumber::fromString(
QStringLiteral(APP_VERSION).replace("v", ""));
}
void Flameshot::setOrigin(Origin origin)
{
m_origin = origin;
}
Flameshot::Origin Flameshot::origin()
{
return m_origin;
}
/**
* @brief Prompt the user to resolve config errors if necessary.
* @return Whether errors were resolved.
*/
bool Flameshot::resolveAnyConfigErrors()
{
bool resolved = true;
ConfigHandler confighandler;
if (!confighandler.checkUnrecognizedSettings() ||
!confighandler.checkSemantics()) {
auto* resolver = new ConfigResolver();
QObject::connect(
resolver, &ConfigResolver::rejected, [resolver, &resolved]() {
resolved = false;
resolver->deleteLater();
if (origin() == CLI) {
exit(1);
}
});
QObject::connect(
resolver, &ConfigResolver::accepted, [resolver, &resolved]() {
resolved = true;
resolver->close();
resolver->deleteLater();
// Ensure that the dialog is closed before starting capture
qApp->processEvents();
});
resolver->exec();
qApp->processEvents();
}
return resolved;
}
void Flameshot::requestCapture(const CaptureRequest& request)
{
if (!resolveAnyConfigErrors()) {
return;
}
switch (request.captureMode()) {
case CaptureRequest::FULLSCREEN_MODE:
QTimer::singleShot(request.delay(),
[this, request] { full(request); });
break;
case CaptureRequest::SCREEN_MODE: {
int&& number = request.data().toInt();
QTimer::singleShot(request.delay(), [this, request, number]() {
screen(request, number);
});
break;
}
case CaptureRequest::GRAPHICAL_MODE: {
QTimer::singleShot(
request.delay(), this, [this, request]() { gui(request); });
break;
}
default:
emit captureFailed();
break;
}
}
void Flameshot::exportCapture(const QPixmap& capture,
QRect& selection,
const CaptureRequest& req)
{
using CR = CaptureRequest;
int tasks = req.tasks(), mode = req.captureMode();
QString path = req.path();
if (tasks & CR::PRINT_GEOMETRY) {
QByteArray byteArray;
QBuffer buffer(&byteArray);
QTextStream(stdout)
<< selection.width() << "x" << selection.height() << "+"
<< selection.x() << "+" << selection.y() << "\n";
}
if (tasks & CR::PRINT_RAW) {
QByteArray byteArray;
QBuffer buffer(&byteArray);
capture.save(&buffer, "PNG");
QFile file;
file.open(stdout, QIODevice::WriteOnly);
file.write(byteArray);
file.close();
}
if (tasks & CR::SAVE) {
if (req.path().isEmpty()) {
saveToFilesystemGUI(capture);
} else {
saveToFilesystem(capture, path);
}
}
if (tasks & CR::COPY) {
FlameshotDaemon::copyToClipboard(capture);
}
if (tasks & CR::PIN) {
FlameshotDaemon::createPin(capture, selection);
if (mode == CR::SCREEN_MODE || mode == CR::FULLSCREEN_MODE) {
AbstractLogger::info()
<< QObject::tr("Full screen screenshot pinned to screen");
}
}
if (tasks & CR::UPLOAD) {
if (!ConfigHandler().uploadWithoutConfirmation()) {
auto* dialog = new ImgUploadDialog();
if (dialog->exec() == QDialog::Rejected) {
return;
}
}
ImgUploaderBase* widget = ImgUploaderManager().uploader(capture);
widget->show();
widget->activateWindow();
// NOTE: lambda can't capture 'this' because it might be destroyed later
CR::ExportTask tasks = tasks;
QObject::connect(
widget, &ImgUploaderBase::uploadOk, [=](const QUrl& url) {
if (ConfigHandler().copyURLAfterUpload()) {
if (!(tasks & CR::COPY)) {
FlameshotDaemon::copyToClipboard(
url.toString(), tr("URL copied to clipboard."));
}
widget->showPostUploadDialog();
}
});
}
if (!(tasks & CR::UPLOAD)) {
emit captureTaken(capture);
}
}
void Flameshot::setExternalWidget(bool b)
{
m_haveExternalWidget = b;
}
bool Flameshot::haveExternalWidget()
{
return m_haveExternalWidget;
}
// STATIC ATTRIBUTES
Flameshot::Origin Flameshot::m_origin = Flameshot::DAEMON;
| 12,247
|
C++
|
.cpp
| 391
| 24.43734
| 80
| 0.617201
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,629
|
qguiappcurrentscreen.cpp
|
flameshot-org_flameshot/src/core/qguiappcurrentscreen.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2021 Yuriy Puchkov <yuriy.puchkov@namecheap.com>
#include "qguiappcurrentscreen.h"
#include <QCursor>
#include <QDesktopWidget>
#include <QGuiApplication>
#include <QPoint>
#include <QScreen>
QGuiAppCurrentScreen::QGuiAppCurrentScreen()
{
m_currentScreen = nullptr;
}
QScreen* QGuiAppCurrentScreen::currentScreen()
{
return currentScreen(QCursor::pos());
}
QScreen* QGuiAppCurrentScreen::currentScreen(const QPoint& pos)
{
m_currentScreen = screenAt(pos);
#if defined(Q_OS_MACOS)
// On the MacOS if mouse position is at the edge of bottom or right sides
// qGuiApp->screenAt will return nullptr, so we need to try to find current
// screen by moving 1 pixel inside to the current desktop area
if (!m_currentScreen && pos.x() > 0) {
QPoint posCorrected(pos.x() - 1, pos.y());
m_currentScreen = screenAt(posCorrected);
}
if (!m_currentScreen && pos.y() > 0) {
QPoint posCorrected(pos.x(), pos.y() - 1);
m_currentScreen = screenAt(posCorrected);
}
if (!m_currentScreen && pos.x() > 0 && pos.y() > 0) {
QPoint posCorrected(pos.x() - 1, pos.y() - 1);
m_currentScreen = screenAt(posCorrected);
}
#endif
if (!m_currentScreen) {
qCritical("Unable to get current screen, starting to use primary "
"screen. It may be a cause of logical error and working with "
"a wrong screen.");
m_currentScreen = qGuiApp->primaryScreen();
}
return m_currentScreen;
}
QScreen* QGuiAppCurrentScreen::screenAt(const QPoint& pos)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
m_currentScreen = qGuiApp->screenAt(pos);
#else
for (QScreen* const screen : QGuiApplication::screens()) {
m_currentScreen = screen;
if (screen->geometry().contains(pos)) {
break;
}
}
#endif
return m_currentScreen;
}
| 1,957
|
C++
|
.cpp
| 58
| 29
| 80
| 0.669483
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
2,630
|
flameshotdaemon.cpp
|
flameshot-org_flameshot/src/core/flameshotdaemon.cpp
|
#include "flameshotdaemon.h"
#include "abstractlogger.h"
#include "confighandler.h"
#include "flameshot.h"
#include "pinwidget.h"
#include "screenshotsaver.h"
#include "src/utils/globalvalues.h"
#include "src/widgets/capture/capturewidget.h"
#include "src/widgets/trayicon.h"
#include <QApplication>
#include <QClipboard>
#include <QDBusConnection>
#include <QDBusMessage>
#include <QPixmap>
#include <QRect>
#if !defined(DISABLE_UPDATE_CHECKER)
#include <QDesktopServices>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QTimer>
#include <QUrl>
#endif
#ifdef Q_OS_WIN
#include "src/core/globalshortcutfilter.h"
#endif
/**
* @brief A way of accessing the flameshot daemon both from the daemon itself,
* and from subcommands.
*
* The daemon is necessary in order to:
* - Host the system tray,
* - Listen for hotkey events that will trigger captures,
* - Host pinned screenshot widgets,
* - Host the clipboard on X11, where the clipboard gets lost once flameshot
* quits.
*
* If the `autoCloseIdleDaemon` option is true, the daemon will close as soon as
* it is not needed to host pinned screenshots and the clipboard. On Windows,
* this option is disabled and the daemon always persists, because the system
* tray is currently the only way to interact with flameshot there.
*
* Both the daemon and non-daemon flameshot processes use the same public API,
* which is implemented as static methods. In the daemon process, this class is
* also instantiated as a singleton, so it can listen to D-Bus calls via the
* sigslot mechanism. The instantiation is done by calling `start` (this must be
* done only in the daemon process). Any instance (as opposed to static) members
* can only be used if the current process is a daemon.
*
* @note The daemon will be automatically launched where necessary, via D-Bus.
* This applies only to Linux.
*/
FlameshotDaemon::FlameshotDaemon()
: m_persist(false)
, m_hostingClipboard(false)
, m_clipboardSignalBlocked(false)
, m_trayIcon(nullptr)
#if !defined(DISABLE_UPDATE_CHECKER)
, m_networkCheckUpdates(nullptr)
, m_showCheckAppUpdateStatus(false)
, m_appLatestVersion(QStringLiteral(APP_VERSION).replace("v", ""))
#endif
{
connect(
QApplication::clipboard(), &QClipboard::dataChanged, this, [this]() {
if (!m_hostingClipboard || m_clipboardSignalBlocked) {
m_clipboardSignalBlocked = false;
return;
}
m_hostingClipboard = false;
quitIfIdle();
});
#ifdef Q_OS_WIN
m_persist = true;
#else
m_persist = !ConfigHandler().autoCloseIdleDaemon();
connect(ConfigHandler::getInstance(),
&ConfigHandler::fileChanged,
this,
[this]() {
ConfigHandler config;
enableTrayIcon(!config.disabledTrayIcon());
m_persist = !config.autoCloseIdleDaemon();
});
#endif
#if !defined(DISABLE_UPDATE_CHECKER)
if (ConfigHandler().checkForUpdates()) {
getLatestAvailableVersion();
}
#endif
}
void FlameshotDaemon::start()
{
if (!m_instance) {
m_instance = new FlameshotDaemon();
// Tray icon needs FlameshotDaemon::instance() to be non-null
m_instance->initTrayIcon();
qApp->setQuitOnLastWindowClosed(false);
}
}
void FlameshotDaemon::createPin(const QPixmap& capture, QRect geometry)
{
if (instance()) {
instance()->attachPin(capture, geometry);
return;
}
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
stream << capture;
stream << geometry;
QDBusMessage m = createMethodCall(QStringLiteral("attachPin"));
m << data;
call(m);
}
void FlameshotDaemon::copyToClipboard(const QPixmap& capture)
{
if (instance()) {
instance()->attachScreenshotToClipboard(capture);
return;
}
QDBusMessage m =
createMethodCall(QStringLiteral("attachScreenshotToClipboard"));
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
stream << capture;
m << data;
call(m);
}
void FlameshotDaemon::copyToClipboard(const QString& text,
const QString& notification)
{
if (instance()) {
instance()->attachTextToClipboard(text, notification);
return;
}
auto m = createMethodCall(QStringLiteral("attachTextToClipboard"));
m << text << notification;
QDBusConnection sessionBus = QDBusConnection::sessionBus();
checkDBusConnection(sessionBus);
sessionBus.call(m);
}
/**
* @brief Is this instance of flameshot hosting any windows as a daemon?
*/
bool FlameshotDaemon::isThisInstanceHostingWidgets()
{
return instance() && !instance()->m_widgets.isEmpty();
}
void FlameshotDaemon::sendTrayNotification(const QString& text,
const QString& title,
const int timeout)
{
if (m_trayIcon) {
m_trayIcon->showMessage(
title, text, QIcon(GlobalValues::iconPath()), timeout);
}
}
#if !defined(DISABLE_UPDATE_CHECKER)
void FlameshotDaemon::showUpdateNotificationIfAvailable(CaptureWidget* widget)
{
if (!m_appLatestUrl.isEmpty() &&
ConfigHandler().ignoreUpdateToVersion().compare(m_appLatestVersion) <
0) {
widget->showAppUpdateNotification(m_appLatestVersion, m_appLatestUrl);
}
}
void FlameshotDaemon::getLatestAvailableVersion()
{
// This features is required for MacOS and Windows user and for Linux users
// who installed Flameshot not from the repository.
QNetworkRequest requestCheckUpdates(QUrl(FLAMESHOT_APP_VERSION_URL));
if (nullptr == m_networkCheckUpdates) {
m_networkCheckUpdates = new QNetworkAccessManager(this);
connect(m_networkCheckUpdates,
&QNetworkAccessManager::finished,
this,
&FlameshotDaemon::handleReplyCheckUpdates);
}
m_networkCheckUpdates->get(requestCheckUpdates);
// check for updates each 24 hours
QTimer::singleShot(1000 * 60 * 60 * 24, [this]() {
if (ConfigHandler().checkForUpdates()) {
this->getLatestAvailableVersion();
}
});
}
void FlameshotDaemon::checkForUpdates()
{
if (m_appLatestUrl.isEmpty()) {
m_showCheckAppUpdateStatus = true;
getLatestAvailableVersion();
} else {
QDesktopServices::openUrl(QUrl(m_appLatestUrl));
}
}
#endif
/**
* @brief Return the daemon instance.
*
* If this instance of flameshot is the daemon, a singleton instance of
* `FlameshotDaemon` is returned. As a side effect`start` will called if it
* wasn't called earlier. If this instance of flameshot is not the daemon,
* `nullptr` is returned.
*
* This strategy is used because the daemon needs to receive signals from D-Bus,
* for which an instance of a `QObject` is required. The singleton serves as
* that object.
*/
FlameshotDaemon* FlameshotDaemon::instance()
{
// Because we don't use DBus on MacOS, each instance of flameshot is its own
// mini-daemon, responsible for hosting its own persistent widgets (e.g.
// pins).
#if defined(Q_OS_MACOS)
start();
#endif
return m_instance;
}
/**
* @brief Quit the daemon if it has nothing to do and the 'persist' flag is not
* set.
*/
void FlameshotDaemon::quitIfIdle()
{
if (m_persist) {
return;
}
if (!m_hostingClipboard && m_widgets.isEmpty()) {
qApp->exit(0);
}
}
// SERVICE METHODS
void FlameshotDaemon::attachPin(const QPixmap& pixmap, QRect geometry)
{
auto* pinWidget = new PinWidget(pixmap, geometry);
m_widgets.append(pinWidget);
connect(pinWidget, &QObject::destroyed, this, [=]() {
m_widgets.removeOne(pinWidget);
quitIfIdle();
});
pinWidget->show();
pinWidget->activateWindow();
}
void FlameshotDaemon::attachScreenshotToClipboard(const QPixmap& pixmap)
{
m_hostingClipboard = true;
QClipboard* clipboard = QApplication::clipboard();
clipboard->blockSignals(true);
// This variable is necessary because the signal doesn't get blocked on
// windows for some reason
m_clipboardSignalBlocked = true;
saveToClipboard(pixmap);
clipboard->blockSignals(false);
}
// D-BUS ADAPTER METHODS
void FlameshotDaemon::attachPin(const QByteArray& data)
{
QDataStream stream(data);
QPixmap pixmap;
QRect geometry;
stream >> pixmap;
stream >> geometry;
attachPin(pixmap, geometry);
}
void FlameshotDaemon::attachScreenshotToClipboard(const QByteArray& screenshot)
{
QDataStream stream(screenshot);
QPixmap p;
stream >> p;
attachScreenshotToClipboard(p);
}
void FlameshotDaemon::attachTextToClipboard(const QString& text,
const QString& notification)
{
// Must send notification before clipboard modification on linux
if (!notification.isEmpty()) {
AbstractLogger::info() << notification;
}
m_hostingClipboard = true;
QClipboard* clipboard = QApplication::clipboard();
clipboard->blockSignals(true);
// This variable is necessary because the signal doesn't get blocked on
// windows for some reason
m_clipboardSignalBlocked = true;
clipboard->setText(text);
clipboard->blockSignals(false);
}
void FlameshotDaemon::initTrayIcon()
{
#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX)
if (!ConfigHandler().disabledTrayIcon()) {
enableTrayIcon(true);
}
#elif defined(Q_OS_WIN)
enableTrayIcon(true);
GlobalShortcutFilter* nativeFilter = new GlobalShortcutFilter(this);
qApp->installNativeEventFilter(nativeFilter);
connect(nativeFilter, &GlobalShortcutFilter::printPressed, this, [this]() {
Flameshot::instance()->gui();
});
#endif
}
void FlameshotDaemon::enableTrayIcon(bool enable)
{
if (enable) {
if (m_trayIcon == nullptr) {
m_trayIcon = new TrayIcon();
} else {
m_trayIcon->show();
return;
}
} else if (m_trayIcon) {
m_trayIcon->hide();
}
}
#if !defined(DISABLE_UPDATE_CHECKER)
void FlameshotDaemon::handleReplyCheckUpdates(QNetworkReply* reply)
{
if (!ConfigHandler().checkForUpdates()) {
return;
}
if (reply->error() == QNetworkReply::NoError) {
QJsonDocument response = QJsonDocument::fromJson(reply->readAll());
QJsonObject json = response.object();
m_appLatestVersion = json["tag_name"].toString().replace("v", "");
QVersionNumber appLatestVersion =
QVersionNumber::fromString(m_appLatestVersion);
if (Flameshot::instance()->getVersion() < appLatestVersion) {
emit newVersionAvailable(appLatestVersion);
m_appLatestUrl = json["html_url"].toString();
QString newVersion =
tr("New version %1 is available").arg(m_appLatestVersion);
if (m_showCheckAppUpdateStatus) {
sendTrayNotification(newVersion, "Flameshot");
QDesktopServices::openUrl(QUrl(m_appLatestUrl));
}
} else if (m_showCheckAppUpdateStatus) {
sendTrayNotification(tr("You have the latest version"),
"Flameshot");
}
} else {
qWarning() << "Failed to get information about the latest version. "
<< reply->errorString();
if (m_showCheckAppUpdateStatus) {
if (FlameshotDaemon::instance()) {
FlameshotDaemon::instance()->sendTrayNotification(
tr("Failed to get information about the latest version."),
"Flameshot");
}
}
}
m_showCheckAppUpdateStatus = false;
}
#endif
QDBusMessage FlameshotDaemon::createMethodCall(const QString& method)
{
QDBusMessage m =
QDBusMessage::createMethodCall(QStringLiteral("org.flameshot.Flameshot"),
QStringLiteral("/"),
QLatin1String(""),
method);
return m;
}
void FlameshotDaemon::checkDBusConnection(const QDBusConnection& connection)
{
if (!connection.isConnected()) {
AbstractLogger::error() << tr("Unable to connect via DBus");
qApp->exit(1);
}
}
void FlameshotDaemon::call(const QDBusMessage& m)
{
QDBusConnection sessionBus = QDBusConnection::sessionBus();
checkDBusConnection(sessionBus);
sessionBus.call(m);
}
// STATIC ATTRIBUTES
FlameshotDaemon* FlameshotDaemon::m_instance = nullptr;
| 12,655
|
C++
|
.cpp
| 379
| 27.738786
| 80
| 0.680402
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,631
|
flameshotdbusadapter.cpp
|
flameshot-org_flameshot/src/core/flameshotdbusadapter.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "flameshotdbusadapter.h"
#include "src/core/flameshotdaemon.h"
FlameshotDBusAdapter::FlameshotDBusAdapter(QObject* parent)
: QDBusAbstractAdaptor(parent)
{}
FlameshotDBusAdapter::~FlameshotDBusAdapter() = default;
void FlameshotDBusAdapter::attachScreenshotToClipboard(const QByteArray& data)
{
FlameshotDaemon::instance()->attachScreenshotToClipboard(data);
}
void FlameshotDBusAdapter::attachTextToClipboard(const QString& text,
const QString& notification)
{
FlameshotDaemon::instance()->attachTextToClipboard(text, notification);
}
void FlameshotDBusAdapter::attachPin(const QByteArray& data)
{
FlameshotDaemon::instance()->attachPin(data);
}
| 843
|
C++
|
.cpp
| 21
| 35.857143
| 78
| 0.775735
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,632
|
globalshortcutfilter.cpp
|
flameshot-org_flameshot/src/core/globalshortcutfilter.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "globalshortcutfilter.h"
#include "src/core/flameshot.h"
#include <qt_windows.h>
GlobalShortcutFilter::GlobalShortcutFilter(QObject* parent)
: QObject(parent)
{
// Forced Print Screen
if (RegisterHotKey(NULL, 1, 0, VK_SNAPSHOT)) {
// ok - capture screen
}
if (RegisterHotKey(NULL, 2, MOD_SHIFT, VK_SNAPSHOT)) {
// ok - show screenshots history
}
}
bool GlobalShortcutFilter::nativeEventFilter(const QByteArray& eventType,
void* message,
long* result)
{
Q_UNUSED(eventType)
Q_UNUSED(result)
MSG* msg = static_cast<MSG*>(message);
if (msg->message == WM_HOTKEY) {
// TODO: this is just a temporal workwrround, proper global
// support would need custom shortcuts defined by the user.
const quint32 keycode = HIWORD(msg->lParam);
const quint32 modifiers = LOWORD(msg->lParam);
// Show screenshots history
if (VK_SNAPSHOT == keycode && MOD_SHIFT == modifiers) {
Flameshot::instance()->history();
}
// Capture screen
if (VK_SNAPSHOT == keycode && 0 == modifiers) {
Flameshot::instance()->requestCapture(
CaptureRequest(CaptureRequest::GRAPHICAL_MODE));
}
return true;
}
return false;
}
| 1,494
|
C++
|
.cpp
| 41
| 28.463415
| 73
| 0.619377
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,633
|
capturerequest.cpp
|
flameshot-org_flameshot/src/core/capturerequest.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "capturerequest.h"
#include "confighandler.h"
#include "src/config/cacheutils.h"
#include <QApplication>
#include <QClipboard>
#include <QDateTime>
#include <stdexcept>
#include <utility>
CaptureRequest::CaptureRequest(CaptureRequest::CaptureMode mode,
const uint delay,
QVariant data,
CaptureRequest::ExportTask tasks)
: m_mode(mode)
, m_delay(delay)
, m_tasks(tasks)
, m_data(std::move(data))
{
ConfigHandler config;
if (m_mode == CaptureRequest::CaptureMode::GRAPHICAL_MODE &&
config.saveLastRegion()) {
setInitialSelection(getLastRegion());
}
}
CaptureRequest::CaptureMode CaptureRequest::captureMode() const
{
return m_mode;
}
uint CaptureRequest::delay() const
{
return m_delay;
}
QString CaptureRequest::path() const
{
return m_path;
}
QVariant CaptureRequest::data() const
{
return m_data;
}
CaptureRequest::ExportTask CaptureRequest::tasks() const
{
return m_tasks;
}
QRect CaptureRequest::initialSelection() const
{
return m_initialSelection;
}
void CaptureRequest::addTask(CaptureRequest::ExportTask task)
{
if (task == SAVE) {
throw std::logic_error("SAVE task must be added using addSaveTask");
}
m_tasks |= task;
}
void CaptureRequest::removeTask(ExportTask task)
{
((int&)m_tasks) &= ~task;
}
void CaptureRequest::addSaveTask(const QString& path)
{
m_tasks |= SAVE;
m_path = path;
}
void CaptureRequest::addPinTask(const QRect& pinWindowGeometry)
{
m_tasks |= PIN;
m_pinWindowGeometry = pinWindowGeometry;
}
void CaptureRequest::setInitialSelection(const QRect& selection)
{
m_initialSelection = selection;
}
| 1,862
|
C++
|
.cpp
| 74
| 21.310811
| 76
| 0.708568
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,634
|
abstractpathtool.cpp
|
flameshot-org_flameshot/src/tools/abstractpathtool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "abstractpathtool.h"
#include <cmath>
AbstractPathTool::AbstractPathTool(QObject* parent)
: CaptureTool(parent)
, m_thickness(1)
, m_padding(0)
{}
void AbstractPathTool::copyParams(const AbstractPathTool* from,
AbstractPathTool* to)
{
to->m_color = from->m_color;
to->m_thickness = from->m_thickness;
to->m_padding = from->m_padding;
to->m_pos = from->m_pos;
to->m_points.clear();
for (auto point : from->m_points) {
to->m_points.append(point);
}
}
bool AbstractPathTool::isValid() const
{
return m_points.length() > 1;
}
bool AbstractPathTool::closeOnButtonPressed() const
{
return false;
}
bool AbstractPathTool::isSelectable() const
{
return true;
}
bool AbstractPathTool::showMousePreview() const
{
return true;
}
QRect AbstractPathTool::mousePreviewRect(const CaptureContext& context) const
{
QRect rect(0, 0, context.toolSize + 2, context.toolSize + 2);
rect.moveCenter(context.mousePos);
return rect;
}
QRect AbstractPathTool::boundingRect() const
{
if (m_points.isEmpty()) {
return {};
}
int min_x = m_points.at(0).x();
int min_y = m_points.at(0).y();
int max_x = m_points.at(0).x();
int max_y = m_points.at(0).y();
for (auto point : m_points) {
if (point.x() < min_x) {
min_x = point.x();
}
if (point.y() < min_y) {
min_y = point.y();
}
if (point.x() > max_x) {
max_x = point.x();
}
if (point.y() > max_y) {
max_y = point.y();
}
}
int offset =
m_thickness <= 1 ? 1 : static_cast<int>(round(m_thickness * 0.7 + 0.5));
return QRect(min_x - offset,
min_y - offset,
std::abs(min_x - max_x) + offset * 2,
std::abs(min_y - max_y) + offset * 2)
.normalized();
}
void AbstractPathTool::drawEnd(const QPoint& p)
{
Q_UNUSED(p)
}
void AbstractPathTool::drawMove(const QPoint& p)
{
addPoint(p);
}
void AbstractPathTool::onColorChanged(const QColor& c)
{
m_color = c;
}
void AbstractPathTool::onSizeChanged(int size)
{
m_thickness = size;
}
void AbstractPathTool::addPoint(const QPoint& point)
{
if (m_pathArea.left() > point.x()) {
m_pathArea.setLeft(point.x());
} else if (m_pathArea.right() < point.x()) {
m_pathArea.setRight(point.x());
}
if (m_pathArea.top() > point.y()) {
m_pathArea.setTop(point.y());
} else if (m_pathArea.bottom() < point.y()) {
m_pathArea.setBottom(point.y());
}
m_points.append(point);
}
void AbstractPathTool::move(const QPoint& mousePos)
{
if (m_points.empty()) {
return;
}
QPoint basePos = *pos();
QPoint offset = mousePos - basePos;
for (auto& m_point : m_points) {
m_point += offset;
}
}
const QPoint* AbstractPathTool::pos()
{
if (m_points.empty()) {
m_pos = QPoint();
return &m_pos;
}
int x = m_points.at(0).x();
int y = m_points.at(0).y();
for (auto point : m_points) {
if (point.x() < x) {
x = point.x();
}
if (point.y() < y) {
y = point.y();
}
}
m_pos.setX(x);
m_pos.setY(y);
return &m_pos;
}
| 3,423
|
C++
|
.cpp
| 135
| 20.140741
| 78
| 0.584404
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,635
|
abstracttwopointtool.cpp
|
flameshot-org_flameshot/src/tools/abstracttwopointtool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "abstracttwopointtool.h"
#include <QCursor>
#include <QScreen>
#include <cmath>
namespace {
const double ADJ_UNIT = std::atan(1.0);
const int DIRS_NUMBER = 4;
enum UNIT
{
HORIZ_DIR = 0,
DIAG1_DIR = 1,
VERT_DIR = 2
};
const double ADJ_DIAG_UNIT = 2 * ADJ_UNIT;
const int DIAG_DIRS_NUMBER = 2;
enum DIAG_UNIT
{
DIR1 = 0
};
}
AbstractTwoPointTool::AbstractTwoPointTool(QObject* parent)
: CaptureTool(parent)
, m_thickness(1)
, m_padding(0)
{}
void AbstractTwoPointTool::copyParams(const AbstractTwoPointTool* from,
AbstractTwoPointTool* to)
{
CaptureTool::copyParams(from, to);
to->m_points.first = from->m_points.first;
to->m_points.second = from->m_points.second;
to->m_color = from->m_color;
to->m_thickness = from->m_thickness;
to->m_padding = from->m_padding;
to->m_supportsOrthogonalAdj = from->m_supportsOrthogonalAdj;
to->m_supportsDiagonalAdj = from->m_supportsDiagonalAdj;
}
bool AbstractTwoPointTool::isValid() const
{
return (m_points.first != m_points.second);
}
bool AbstractTwoPointTool::closeOnButtonPressed() const
{
return false;
}
bool AbstractTwoPointTool::isSelectable() const
{
return true;
}
bool AbstractTwoPointTool::showMousePreview() const
{
return true;
}
QRect AbstractTwoPointTool::mousePreviewRect(
const CaptureContext& context) const
{
QRect rect(0, 0, context.toolSize + 2, context.toolSize + 2);
rect.moveCenter(context.mousePos);
return rect;
}
QRect AbstractTwoPointTool::boundingRect() const
{
if (!isValid()) {
return {};
}
int offset =
m_thickness <= 1 ? 1 : static_cast<int>(round(m_thickness * 0.7 + 0.5));
QRect rect =
QRect(std::min(m_points.first.x(), m_points.second.x()) - offset,
std::min(m_points.first.y(), m_points.second.y()) - offset,
std::abs(m_points.first.x() - m_points.second.x()) + offset * 2,
std::abs(m_points.first.y() - m_points.second.y()) + offset * 2);
return rect.normalized();
}
void AbstractTwoPointTool::drawEnd(const QPoint& p)
{
Q_UNUSED(p)
}
void AbstractTwoPointTool::drawMove(const QPoint& p)
{
m_points.second = p;
}
void AbstractTwoPointTool::drawMoveWithAdjustment(const QPoint& p)
{
m_points.second = m_points.first + adjustedVector(p - m_points.first);
}
void AbstractTwoPointTool::onColorChanged(const QColor& c)
{
m_color = c;
}
void AbstractTwoPointTool::onSizeChanged(int size)
{
m_thickness = size;
}
void AbstractTwoPointTool::paintMousePreview(QPainter& painter,
const CaptureContext& context)
{
painter.setPen(QPen(context.color, context.toolSize));
painter.drawLine(context.mousePos, context.mousePos);
}
void AbstractTwoPointTool::drawStart(const CaptureContext& context)
{
onColorChanged(context.color);
m_points.first = context.mousePos;
m_points.second = context.mousePos;
onSizeChanged(context.toolSize);
}
QPoint AbstractTwoPointTool::adjustedVector(QPoint v) const
{
if (m_supportsOrthogonalAdj && m_supportsDiagonalAdj) {
int dir = (static_cast<int>(round(atan2(-v.y(), v.x()) / ADJ_UNIT)) +
DIRS_NUMBER) %
DIRS_NUMBER;
if (dir == UNIT::HORIZ_DIR) {
v.setY(0);
} else if (dir == UNIT::VERT_DIR) {
v.setX(0);
} else if (dir == UNIT::DIAG1_DIR) {
int newX = (v.x() - v.y()) / 2;
int newY = -newX;
v.setX(newX);
v.setY(newY);
} else {
int newX = (v.x() + v.y()) / 2;
int newY = newX;
v.setX(newX);
v.setY(newY);
}
} else if (m_supportsDiagonalAdj) {
int dir =
(static_cast<int>(round((atan2(-v.y(), v.x()) - ADJ_DIAG_UNIT / 2) /
ADJ_DIAG_UNIT)) +
DIAG_DIRS_NUMBER) %
DIAG_DIRS_NUMBER;
if (dir == DIAG_UNIT::DIR1) {
int newX = (v.x() - v.y()) / 2;
int newY = -newX;
v.setX(newX);
v.setY(newY);
} else {
int newX = (v.x() + v.y()) / 2;
int newY = newX;
v.setX(newX);
v.setY(newY);
}
}
return v;
}
void AbstractTwoPointTool::move(const QPoint& pos)
{
QPoint offset = m_points.second - m_points.first;
m_points.first = pos;
m_points.second = m_points.first + offset;
}
const QPoint* AbstractTwoPointTool::pos()
{
return &m_points.first;
}
| 4,696
|
C++
|
.cpp
| 160
| 23.70625
| 78
| 0.62439
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,636
|
toolfactory.cpp
|
flameshot-org_flameshot/src/tools/toolfactory.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "toolfactory.h"
#include "accept/accepttool.h"
#include "arrow/arrowtool.h"
#include "circle/circletool.h"
#include "circlecount/circlecounttool.h"
#include "copy/copytool.h"
#include "exit/exittool.h"
#include "imgupload/imguploadertool.h"
#include "invert/inverttool.h"
#include "launcher/applaunchertool.h"
#include "line/linetool.h"
#include "marker/markertool.h"
#include "move/movetool.h"
#include "pencil/penciltool.h"
#include "pin/pintool.h"
#include "pixelate/pixelatetool.h"
#include "rectangle/rectangletool.h"
#include "redo/redotool.h"
#include "save/savetool.h"
#include "selection/selectiontool.h"
#include "sizedecrease/sizedecreasetool.h"
#include "sizeincrease/sizeincreasetool.h"
#include "text/texttool.h"
#include "undo/undotool.h"
ToolFactory::ToolFactory(QObject* parent)
: QObject(parent)
{}
CaptureTool* ToolFactory::CreateTool(CaptureTool::Type t, QObject* parent)
{
#define if_TYPE_return_TOOL(TYPE, TOOL) \
case CaptureTool::TYPE: \
return new TOOL(parent)
switch (t) {
if_TYPE_return_TOOL(TYPE_PENCIL, PencilTool);
if_TYPE_return_TOOL(TYPE_DRAWER, LineTool);
if_TYPE_return_TOOL(TYPE_ARROW, ArrowTool);
if_TYPE_return_TOOL(TYPE_SELECTION, SelectionTool);
if_TYPE_return_TOOL(TYPE_RECTANGLE, RectangleTool);
if_TYPE_return_TOOL(TYPE_CIRCLE, CircleTool);
if_TYPE_return_TOOL(TYPE_MARKER, MarkerTool);
if_TYPE_return_TOOL(TYPE_MOVESELECTION, MoveTool);
if_TYPE_return_TOOL(TYPE_UNDO, UndoTool);
if_TYPE_return_TOOL(TYPE_COPY, CopyTool);
if_TYPE_return_TOOL(TYPE_SAVE, SaveTool);
if_TYPE_return_TOOL(TYPE_EXIT, ExitTool);
if_TYPE_return_TOOL(TYPE_IMAGEUPLOADER, ImgUploaderTool);
#if !defined(Q_OS_MACOS)
if_TYPE_return_TOOL(TYPE_OPEN_APP, AppLauncher);
#endif
if_TYPE_return_TOOL(TYPE_PIXELATE, PixelateTool);
if_TYPE_return_TOOL(TYPE_REDO, RedoTool);
if_TYPE_return_TOOL(TYPE_PIN, PinTool);
if_TYPE_return_TOOL(TYPE_TEXT, TextTool);
if_TYPE_return_TOOL(TYPE_CIRCLECOUNT, CircleCountTool);
if_TYPE_return_TOOL(TYPE_SIZEINCREASE, SizeIncreaseTool);
if_TYPE_return_TOOL(TYPE_SIZEDECREASE, SizeDecreaseTool);
if_TYPE_return_TOOL(TYPE_INVERT, InvertTool);
if_TYPE_return_TOOL(TYPE_ACCEPT, AcceptTool);
default:
return nullptr;
}
}
| 2,601
|
C++
|
.cpp
| 64
| 36.046875
| 80
| 0.70154
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,638
|
abstractactiontool.cpp
|
flameshot-org_flameshot/src/tools/abstractactiontool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "abstractactiontool.h"
AbstractActionTool::AbstractActionTool(QObject* parent)
: CaptureTool(parent)
{}
bool AbstractActionTool::isValid() const
{
return true;
}
bool AbstractActionTool::isSelectable() const
{
return false;
}
bool AbstractActionTool::showMousePreview() const
{
return false;
}
QRect AbstractActionTool::boundingRect() const
{
return {};
}
void AbstractActionTool::process(QPainter& painter, const QPixmap& pixmap)
{
Q_UNUSED(painter)
Q_UNUSED(pixmap)
}
void AbstractActionTool::paintMousePreview(QPainter& painter,
const CaptureContext& context)
{
Q_UNUSED(painter)
Q_UNUSED(context)
}
void AbstractActionTool::drawEnd(const QPoint& p)
{
Q_UNUSED(p)
}
void AbstractActionTool::drawMove(const QPoint& p)
{
Q_UNUSED(p)
}
void AbstractActionTool::drawStart(const CaptureContext& context)
{
Q_UNUSED(context)
}
void AbstractActionTool::onColorChanged(const QColor& c)
{
Q_UNUSED(c)
}
void AbstractActionTool::onSizeChanged(int size)
{
Q_UNUSED(size)
}
| 1,202
|
C++
|
.cpp
| 53
| 19.603774
| 74
| 0.751761
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,639
|
terminallauncher.cpp
|
flameshot-org_flameshot/src/tools/launcher/terminallauncher.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "terminallauncher.h"
#include <QDir>
#include <QProcess>
#include <QProcessEnvironment>
#include <QStandardPaths>
namespace {
static const TerminalApp terminalApps[] = {
{ "x-terminal-emulator", "-e" },
{ "xfce4-terminal", "-x" },
{ "konsole", "-e" },
{ "gnome-terminal", "--" },
{ "terminator", "-e" },
{ "terminology", "-e" },
{ "tilix", "-e" },
{ "xterm", "-e" },
{ "aterm", "-e" },
{ "Eterm", "-e" },
{ "rxvt", "-e" },
{ "urxvt", "-e" },
};
}
TerminalLauncher::TerminalLauncher(QObject* parent)
: QObject(parent)
{}
TerminalApp TerminalLauncher::getPreferedTerminal()
{
TerminalApp res;
for (const TerminalApp& app : terminalApps) {
QString path = QStandardPaths::findExecutable(app.name);
if (!path.isEmpty()) {
res = app;
break;
}
}
return res;
}
bool TerminalLauncher::launchDetached(const QString& command)
{
TerminalApp app = getPreferedTerminal();
return QProcess::startDetached(app.name, { app.arg, command });
}
| 1,178
|
C++
|
.cpp
| 43
| 23.44186
| 72
| 0.625664
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,640
|
applauncherwidget.cpp
|
flameshot-org_flameshot/src/tools/launcher/applauncherwidget.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "applauncherwidget.h"
#include "src/tools/launcher/launcheritemdelegate.h"
#include "src/utils/confighandler.h"
#include "src/utils/filenamehandler.h"
#include "src/utils/globalvalues.h"
#include "terminallauncher.h"
#include <QCheckBox>
#include <QDir>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLineEdit>
#include <QList>
#include <QListView>
#include <QListWidgetItem>
#include <QMessageBox>
#include <QPixmap>
#include <QProcess>
#include <QStandardPaths>
#include <QTabWidget>
namespace {
#if defined(Q_OS_WIN)
QMap<QString, QString> catIconNames({ { "Graphics", "image.svg" },
{ "Utility", "apps.svg" } });
}
#else
QMap<QString, QString> catIconNames(
{ { "Multimedia", "applications-multimedia" },
{ "Development", "applications-development" },
{ "Graphics", "applications-graphics" },
{ "Network", "preferences-system-network" },
{ "Office", "applications-office" },
{ "Science", "applications-science" },
{ "Settings", "preferences-desktop" },
{ "System", "preferences-system" },
{ "Utility", "applications-utilities" } });
}
#endif
AppLauncherWidget::AppLauncherWidget(const QPixmap& p, QWidget* parent)
: QWidget(parent)
, m_pixmap(p)
{
setAttribute(Qt::WA_DeleteOnClose);
setWindowIcon(QIcon(GlobalValues::iconPath()));
setWindowTitle(tr("Open With"));
m_keepOpen = ConfigHandler().keepOpenAppLauncher();
#if defined(Q_OS_WIN)
QDir userAppsFolder(
QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation)
.at(0));
m_parser.processDirectory(userAppsFolder);
QString dir(m_parser.getAllUsersStartMenuPath());
if (!dir.isEmpty()) {
QDir allUserAppsFolder(dir);
m_parser.processDirectory(allUserAppsFolder);
}
#else
QString dirLocal = QDir::homePath() + "/.local/share/applications/";
QDir appsDirLocal(dirLocal);
m_parser.processDirectory(appsDirLocal);
QString dir = QStringLiteral("/usr/share/applications/");
QDir appsDir(dir);
m_parser.processDirectory(appsDir);
#endif
initAppMap();
initListWidget();
m_terminalCheckbox = new QCheckBox(tr("Launch in terminal"), this);
m_keepOpenCheckbox = new QCheckBox(tr("Keep open after selection"), this);
m_keepOpenCheckbox->setChecked(ConfigHandler().keepOpenAppLauncher());
connect(m_keepOpenCheckbox,
&QCheckBox::clicked,
this,
&AppLauncherWidget::checkboxClicked);
// search items
m_lineEdit = new QLineEdit;
connect(m_lineEdit,
&QLineEdit::textChanged,
this,
&AppLauncherWidget::searchChanged);
m_filterList = new QListWidget;
m_filterList->hide();
configureListView(m_filterList);
connect(
m_filterList, &QListWidget::clicked, this, &AppLauncherWidget::launch);
m_layout = new QVBoxLayout(this);
m_layout->addWidget(m_filterList);
m_layout->addWidget(m_tabWidget);
m_layout->addWidget(m_lineEdit);
m_layout->addWidget(m_keepOpenCheckbox);
m_layout->addWidget(m_terminalCheckbox);
m_lineEdit->setFocus();
}
void AppLauncherWidget::launch(const QModelIndex& index)
{
if (!QFileInfo(m_tempFile).isReadable()) {
m_tempFile =
FileNameHandler().properScreenshotPath(QDir::tempPath(), "png");
bool ok = m_pixmap.save(m_tempFile);
if (!ok) {
QMessageBox::about(
this, tr("Error"), tr("Unable to write in") + QDir::tempPath());
return;
}
}
// Heuristically, if there is a % in the command we assume it is the file
// name slot
QString command = index.data(Qt::UserRole).toString();
#if defined(Q_OS_WIN)
// Do not split on Windows, since file path can contain spaces
// and % is not used in lnk files
QStringList prog_args;
prog_args << command;
#else
QStringList prog_args = command.split(" ");
#endif
// no quotes because it is going in an array!
if (command.contains("%")) {
// but that means we need to substitute IN the array not the string!
for (auto& i : prog_args) {
if (i.contains("%"))
i.replace(QRegExp("(\\%.)"), m_tempFile);
}
} else {
// we really should append the file name if there
prog_args.append(m_tempFile); // were no replacements
}
QString app_name = prog_args.at(0);
bool inTerminal =
index.data(Qt::UserRole + 1).toBool() || m_terminalCheckbox->isChecked();
if (inTerminal) {
bool ok = TerminalLauncher::launchDetached(command);
if (!ok) {
QMessageBox::about(
this, tr("Error"), tr("Unable to launch in terminal."));
}
} else {
QFileInfo fi(m_tempFile);
QString workingDir = fi.absolutePath();
prog_args.removeAt(0); // strip program name out
QProcess::startDetached(app_name, prog_args, workingDir);
}
if (!m_keepOpen) {
close();
}
}
void AppLauncherWidget::checkboxClicked(const bool enabled)
{
m_keepOpen = enabled;
ConfigHandler().setKeepOpenAppLauncher(enabled);
m_keepOpenCheckbox->setChecked(enabled);
}
void AppLauncherWidget::searchChanged(const QString& text)
{
if (text.isEmpty()) {
m_filterList->hide();
m_tabWidget->show();
} else {
m_tabWidget->hide();
m_filterList->show();
m_filterList->clear();
QRegExp regexp(text, Qt::CaseInsensitive, QRegExp::Wildcard);
QVector<DesktopAppData> apps;
for (auto const& i : catIconNames.toStdMap()) {
const QString& cat = i.first;
if (!m_appsMap.contains(cat)) {
continue;
}
const QVector<DesktopAppData>& appList = m_appsMap[cat];
for (const DesktopAppData& app : appList) {
if (!apps.contains(app) && (app.name.contains(regexp) ||
app.description.contains(regexp))) {
apps.append(app);
}
}
}
addAppsToListWidget(m_filterList, apps);
}
}
void AppLauncherWidget::initListWidget()
{
m_tabWidget = new QTabWidget;
const int size = GlobalValues::buttonBaseSize();
m_tabWidget->setIconSize(QSize(size, size));
for (auto const& i : catIconNames.toStdMap()) {
const QString& cat = i.first;
const QString& iconName = i.second;
if (!m_appsMap.contains(cat)) {
continue;
}
auto* itemsWidget = new QListWidget();
configureListView(itemsWidget);
const QVector<DesktopAppData>& appList = m_appsMap[cat];
addAppsToListWidget(itemsWidget, appList);
#if defined(Q_OS_WIN)
QColor background = this->palette().window().color();
bool isDark = ColorUtils::colorIsDark(background);
QString modifier =
isDark ? PathInfo::whiteIconPath() : PathInfo::blackIconPath();
m_tabWidget->addTab(
itemsWidget, QIcon(modifier + iconName), QLatin1String(""));
#else
m_tabWidget->addTab(
itemsWidget, QIcon::fromTheme(iconName), QLatin1String(""));
#endif
m_tabWidget->setTabToolTip(m_tabWidget->count(), cat);
if (cat == QLatin1String("Graphics")) {
m_tabWidget->setCurrentIndex(m_tabWidget->count() - 1);
}
}
}
void AppLauncherWidget::initAppMap()
{
QStringList categories({ "AudioVideo",
"Audio",
"Video",
"Development",
"Graphics",
"Network",
"Office",
"Science",
"Settings",
"System",
"Utility" });
m_appsMap = m_parser.getAppsByCategory(categories);
// Unify multimedia.
QVector<DesktopAppData> multimediaList;
QStringList multimediaNames;
multimediaNames << QStringLiteral("AudioVideo") << QStringLiteral("Audio")
<< QStringLiteral("Video");
for (const QString& name : qAsConst(multimediaNames)) {
if (!m_appsMap.contains(name)) {
continue;
}
for (const auto& i : m_appsMap[name]) {
if (!multimediaList.contains(i)) {
multimediaList.append(i);
}
}
m_appsMap.remove(name);
}
if (!multimediaList.isEmpty()) {
m_appsMap.insert(QStringLiteral("Multimedia"), multimediaList);
}
}
void AppLauncherWidget::configureListView(QListWidget* widget)
{
widget->setItemDelegate(new LauncherItemDelegate());
widget->setViewMode(QListWidget::IconMode);
widget->setResizeMode(QListView::Adjust);
widget->setSpacing(4);
widget->setFlow(QListView::LeftToRight);
widget->setDragEnabled(false);
widget->setMinimumWidth(GlobalValues::buttonBaseSize() * 11);
connect(widget, &QListWidget::clicked, this, &AppLauncherWidget::launch);
}
void AppLauncherWidget::addAppsToListWidget(
QListWidget* widget,
const QVector<DesktopAppData>& appList)
{
for (const DesktopAppData& app : appList) {
auto* buttonItem = new QListWidgetItem(widget);
buttonItem->setData(Qt::DecorationRole, app.icon);
buttonItem->setData(Qt::DisplayRole, app.name);
buttonItem->setData(Qt::UserRole, app.exec);
buttonItem->setData(Qt::UserRole + 1, app.showInTerminal);
QColor foregroundColor =
this->palette().color(QWidget::foregroundRole());
buttonItem->setForeground(foregroundColor);
buttonItem->setIcon(app.icon);
buttonItem->setText(app.name);
buttonItem->setToolTip(app.description);
}
}
void AppLauncherWidget::keyPressEvent(QKeyEvent* keyEvent)
{
if (keyEvent->key() == Qt::Key_Escape) {
close();
} else if (keyEvent->key() == Qt::Key_Return) {
auto* widget = (QListWidget*)m_tabWidget->currentWidget();
if (m_filterList->isVisible())
widget = m_filterList;
auto* item = widget->currentItem();
if (item == nullptr) {
item = widget->item(0);
widget->setCurrentItem(item);
}
QModelIndex const idx = widget->currentIndex();
AppLauncherWidget::launch(idx);
} else {
QWidget::keyPressEvent(keyEvent);
}
}
| 10,587
|
C++
|
.cpp
| 293
| 28.720137
| 80
| 0.631174
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,641
|
openwithprogram.cpp
|
flameshot-org_flameshot/src/tools/launcher/openwithprogram.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "openwithprogram.h"
#if defined(Q_OS_WIN)
#include "src/utils/filenamehandler.h"
#include <QDir>
#include <QMessageBox>
#include <windows.h>
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x601
#endif
#include <Shlobj.h>
#pragma comment(lib, "Shell32.lib")
#else
#include "src/tools/launcher/applauncherwidget.h"
#endif
void showOpenWithMenu(const QPixmap& capture)
{
#if defined(Q_OS_WIN)
QString tempFile =
FileNameHandler().properScreenshotPath(QDir::tempPath(), "png");
bool ok = capture.save(tempFile);
if (!ok) {
QMessageBox::about(nullptr,
QObject::tr("Error"),
QObject::tr("Unable to write in") +
QDir::tempPath());
return;
}
OPENASINFO info;
auto wStringFile = tempFile.replace("/", "\\").toStdWString();
info.pcszFile = wStringFile.c_str();
info.pcszClass = nullptr;
info.oaifInFlags = OAIF_ALLOW_REGISTRATION | OAIF_EXEC;
SHOpenWithDialog(nullptr, &info);
#else
auto* w = new AppLauncherWidget(capture);
w->show();
#endif
}
| 1,234
|
C++
|
.cpp
| 41
| 25.243902
| 72
| 0.671717
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,642
|
applaunchertool.cpp
|
flameshot-org_flameshot/src/tools/launcher/applaunchertool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "applaunchertool.h"
#include "applauncherwidget.h"
AppLauncher::AppLauncher(QObject* parent)
: AbstractActionTool(parent)
{}
bool AppLauncher::closeOnButtonPressed() const
{
return true;
}
QIcon AppLauncher::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "open_with.svg");
}
QString AppLauncher::name() const
{
return tr("App Launcher");
}
CaptureTool::Type AppLauncher::type() const
{
return CaptureTool::TYPE_OPEN_APP;
}
QString AppLauncher::description() const
{
return tr("Choose an app to open the capture");
}
QWidget* AppLauncher::widget()
{
return new AppLauncherWidget(capture);
}
CaptureTool* AppLauncher::copy(QObject* parent)
{
return new AppLauncher(parent);
}
void AppLauncher::pressed(CaptureContext& context)
{
capture = context.selectedScreenshotArea();
emit requestAction(REQ_CAPTURE_DONE_OK);
emit requestAction(REQ_ADD_EXTERNAL_WIDGETS);
emit requestAction(REQ_CLOSE_GUI);
}
| 1,143
|
C++
|
.cpp
| 43
| 24.209302
| 72
| 0.769936
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
2,643
|
launcheritemdelegate.cpp
|
flameshot-org_flameshot/src/tools/launcher/launcheritemdelegate.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "launcheritemdelegate.h"
#include "src/utils/globalvalues.h"
#include <QPainter>
LauncherItemDelegate::LauncherItemDelegate(QObject* parent)
: QStyledItemDelegate(parent)
{}
void LauncherItemDelegate::paint(QPainter* painter,
const QStyleOptionViewItem& option,
const QModelIndex& index) const
{
const QRect& rect = option.rect;
if (option.state & (QStyle::State_Selected | QStyle::State_MouseOver)) {
painter->save();
painter->setPen(Qt::transparent);
painter->setBrush(QPalette().highlight());
painter->drawRect(
rect.x(), rect.y(), rect.width() - 1, rect.height() - 1);
painter->restore();
}
auto icon = index.data(Qt::DecorationRole).value<QIcon>();
const int iconSide = static_cast<int>(GlobalValues::buttonBaseSize() * 1.3);
const int halfIcon = iconSide / 2;
const int halfWidth = rect.width() / 2;
const int halfHeight = rect.height() / 2;
QSize size(iconSide, iconSide);
QPixmap pixIcon = icon.pixmap(size).scaled(
size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
painter->drawPixmap(rect.x() + (halfWidth - halfIcon),
rect.y() + (halfHeight / 2 - halfIcon),
iconSide,
iconSide,
pixIcon);
const QRect textRect(
rect.x(), rect.y() + halfHeight, rect.width(), halfHeight);
painter->drawText(textRect,
Qt::TextWordWrap | Qt::AlignHCenter,
index.data(Qt::DisplayRole).toString());
}
QSize LauncherItemDelegate::sizeHint(const QStyleOptionViewItem& option,
const QModelIndex& index) const
{
Q_UNUSED(option)
Q_UNUSED(index)
const int size = GlobalValues::buttonBaseSize();
return { static_cast<int>(size * 3.2), static_cast<int>(size * 3.7) };
}
| 2,062
|
C++
|
.cpp
| 48
| 34.041667
| 80
| 0.622698
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,644
|
markertool.cpp
|
flameshot-org_flameshot/src/tools/marker/markertool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "markertool.h"
#include <QPainter>
#define PADDING_VALUE 14
MarkerTool::MarkerTool(QObject* parent)
: AbstractTwoPointTool(parent)
{
m_supportsOrthogonalAdj = true;
m_supportsDiagonalAdj = true;
}
QIcon MarkerTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "marker.svg");
}
QString MarkerTool::name() const
{
return tr("Marker");
}
CaptureTool::Type MarkerTool::type() const
{
return CaptureTool::TYPE_MARKER;
}
QString MarkerTool::description() const
{
return tr("Set the Marker as the paint tool");
}
QRect MarkerTool::mousePreviewRect(const CaptureContext& context) const
{
int width = PADDING_VALUE + context.toolSize;
QRect rect(0, 0, width + 2, width + 2);
rect.moveCenter(context.mousePos);
return rect;
}
CaptureTool* MarkerTool::copy(QObject* parent)
{
auto* tool = new MarkerTool(parent);
copyParams(this, tool);
return tool;
}
void MarkerTool::process(QPainter& painter, const QPixmap& pixmap)
{
Q_UNUSED(pixmap)
auto compositionMode = painter.compositionMode();
qreal opacity = painter.opacity();
auto pen = painter.pen();
painter.setCompositionMode(QPainter::CompositionMode_Multiply);
painter.setOpacity(0.35);
painter.setPen(QPen(color(), size()));
painter.drawLine(points().first, points().second);
painter.setPen(pen);
painter.setOpacity(opacity);
painter.setCompositionMode(compositionMode);
}
void MarkerTool::paintMousePreview(QPainter& painter,
const CaptureContext& context)
{
auto compositionMode = painter.compositionMode();
qreal opacity = painter.opacity();
auto pen = painter.pen();
painter.setCompositionMode(QPainter::CompositionMode_Multiply);
painter.setOpacity(0.35);
painter.setPen(QPen(context.color, PADDING_VALUE + context.toolSize));
painter.drawLine(context.mousePos, context.mousePos);
painter.setPen(pen);
painter.setOpacity(opacity);
painter.setCompositionMode(compositionMode);
}
void MarkerTool::drawStart(const CaptureContext& context)
{
AbstractTwoPointTool::drawStart(context);
onSizeChanged(context.toolSize + PADDING_VALUE);
}
void MarkerTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
}
| 2,442
|
C++
|
.cpp
| 78
| 27.730769
| 74
| 0.743622
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,645
|
sizedecreasetool.cpp
|
flameshot-org_flameshot/src/tools/sizedecrease/sizedecreasetool.cpp
|
// Copyright(c) 2017-2019 Alejandro Sirgo Rica & Contributors
//
// This file is part of Flameshot.
//
// Flameshot 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 3 of the License, or
// (at your option) any later version.
//
// Flameshot 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 Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "sizedecreasetool.h"
#include <QPainter>
SizeDecreaseTool::SizeDecreaseTool(QObject* parent)
: AbstractActionTool(parent)
{}
bool SizeDecreaseTool::closeOnButtonPressed() const
{
return false;
}
QIcon SizeDecreaseTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "minus.svg");
}
QString SizeDecreaseTool::name() const
{
return tr("Decrease Tool Size");
}
CaptureTool::Type SizeDecreaseTool::type() const
{
return CaptureTool::TYPE_SIZEDECREASE;
}
QString SizeDecreaseTool::description() const
{
return tr("Decrease the size of the other tools");
}
CaptureTool* SizeDecreaseTool::copy(QObject* parent)
{
return new SizeDecreaseTool(parent);
}
void SizeDecreaseTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
emit requestAction(REQ_DECREASE_TOOL_SIZE);
}
| 1,664
|
C++
|
.cpp
| 51
| 30.72549
| 75
| 0.754517
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
2,647
|
texttool.cpp
|
flameshot-org_flameshot/src/tools/text/texttool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "texttool.h"
#include "src/utils/confighandler.h"
#include "textconfig.h"
#include "textwidget.h"
#define BASE_POINT_SIZE 8
#define MAX_INFO_LENGTH 24
TextTool::TextTool(QObject* parent)
: CaptureTool(parent)
, m_size(1)
{
QString fontFamily = ConfigHandler().fontFamily();
if (!fontFamily.isEmpty()) {
m_font.setFamily(ConfigHandler().fontFamily());
}
m_alignment = Qt::AlignLeft;
}
TextTool::~TextTool()
{
closeEditor();
}
void TextTool::copyParams(const TextTool* from, TextTool* to)
{
CaptureTool::copyParams(from, to);
to->m_font = from->m_font;
to->m_alignment = from->m_alignment;
to->m_text = from->m_text;
to->m_size = from->m_size;
to->m_color = from->m_color;
to->m_textArea = from->m_textArea;
to->m_currentPos = from->m_currentPos;
}
bool TextTool::isValid() const
{
return !m_text.isEmpty();
}
bool TextTool::closeOnButtonPressed() const
{
return false;
}
bool TextTool::isSelectable() const
{
return true;
}
bool TextTool::showMousePreview() const
{
return false;
}
QRect TextTool::boundingRect() const
{
return m_textArea;
}
QIcon TextTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "text.svg");
}
QString TextTool::name() const
{
return tr("Text");
}
QString TextTool::info()
{
if (m_text.length() > 0) {
m_tempString = QString("%1 - %2").arg(name()).arg(m_text.trimmed());
m_tempString = m_tempString.split("\n").at(0);
if (m_tempString.length() > MAX_INFO_LENGTH) {
m_tempString.truncate(MAX_INFO_LENGTH);
m_tempString += "…";
}
return m_tempString;
}
return name();
}
CaptureTool::Type TextTool::type() const
{
return CaptureTool::TYPE_TEXT;
}
QString TextTool::description() const
{
return tr("Add text to your capture");
}
QWidget* TextTool::widget()
{
closeEditor();
m_widget = new TextWidget();
m_widget->setTextColor(m_color);
m_font.setPointSize(m_size + BASE_POINT_SIZE);
m_widget->setFont(m_font);
m_widget->setAlignment(m_alignment);
m_widget->setText(m_text);
m_widget->selectAll();
connect(m_widget, &TextWidget::textUpdated, this, &TextTool::updateText);
return m_widget;
}
void TextTool::closeEditor()
{
if (!m_widget.isNull()) {
m_widget->hide();
delete m_widget;
m_widget = nullptr;
}
if (!m_confW.isNull()) {
m_confW->hide();
delete m_confW;
m_confW = nullptr;
}
}
QWidget* TextTool::configurationWidget()
{
m_confW = new TextConfig();
connect(
m_confW, &TextConfig::fontFamilyChanged, this, &TextTool::updateFamily);
connect(m_confW,
&TextConfig::fontItalicChanged,
this,
&TextTool::updateFontItalic);
connect(m_confW,
&TextConfig::fontStrikeOutChanged,
this,
&TextTool::updateFontStrikeOut);
connect(m_confW,
&TextConfig::fontUnderlineChanged,
this,
&TextTool::updateFontUnderline);
connect(m_confW,
&TextConfig::fontWeightChanged,
this,
&TextTool::updateFontWeight);
connect(
m_confW, &TextConfig::alignmentChanged, this, &TextTool::updateAlignment);
m_confW->setFontFamily(m_font.family());
m_confW->setItalic(m_font.italic());
m_confW->setUnderline(m_font.underline());
m_confW->setStrikeOut(m_font.strikeOut());
m_confW->setWeight(m_font.weight());
m_confW->setTextAlignment(m_alignment);
return m_confW;
}
CaptureTool* TextTool::copy(QObject* parent)
{
auto* textTool = new TextTool(parent);
if (m_confW != nullptr) {
connect(m_confW,
&TextConfig::fontFamilyChanged,
textTool,
&TextTool::updateFamily);
connect(m_confW,
&TextConfig::fontItalicChanged,
textTool,
&TextTool::updateFontItalic);
connect(m_confW,
&TextConfig::fontStrikeOutChanged,
textTool,
&TextTool::updateFontStrikeOut);
connect(m_confW,
&TextConfig::fontUnderlineChanged,
textTool,
&TextTool::updateFontUnderline);
connect(m_confW,
&TextConfig::fontWeightChanged,
textTool,
&TextTool::updateFontWeight);
connect(m_confW,
&TextConfig::alignmentChanged,
textTool,
&TextTool::updateAlignment);
}
copyParams(this, textTool);
return textTool;
}
void TextTool::process(QPainter& painter, const QPixmap& pixmap)
{
Q_UNUSED(pixmap)
if (m_text.isEmpty()) {
return;
}
const int val = 5;
QFont orig_font = painter.font();
QPen orig_pen = painter.pen();
QFontMetrics fm(m_font);
QSize fontsize(fm.boundingRect(QRect(), 0, m_text).size());
fontsize.setWidth(fontsize.width() + val * 2);
fontsize.setHeight(fontsize.height() + val * 2);
m_textArea.setSize(fontsize);
// draw text
painter.setFont(m_font);
painter.setPen(m_color);
if (!editMode()) {
painter.drawText(
m_textArea + QMargins(-val, -val, val, val), m_alignment, m_text);
}
painter.setFont(orig_font);
painter.setPen(orig_pen);
if (m_widget != nullptr) {
m_widget->setAlignment(m_alignment);
}
}
void TextTool::drawObjectSelection(QPainter& painter)
{
if (m_text.isEmpty()) {
return;
}
drawObjectSelectionRect(painter, boundingRect());
}
void TextTool::paintMousePreview(QPainter& painter,
const CaptureContext& context)
{
Q_UNUSED(painter)
Q_UNUSED(context)
}
void TextTool::drawEnd(const QPoint& point)
{
m_textArea.moveTo(point);
}
void TextTool::drawMove(const QPoint& point)
{
m_widget->move(point);
}
void TextTool::drawStart(const CaptureContext& context)
{
m_color = context.color;
m_size = context.toolSize;
emit requestAction(REQ_ADD_CHILD_WIDGET);
}
void TextTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
}
void TextTool::onColorChanged(const QColor& color)
{
m_color = color;
if (m_widget != nullptr) {
m_widget->setTextColor(color);
}
}
void TextTool::onSizeChanged(int size)
{
m_size = size;
m_font.setPointSize(m_size + BASE_POINT_SIZE);
if (m_widget != nullptr) {
m_widget->setFont(m_font);
}
}
void TextTool::updateText(const QString& newText)
{
m_text = newText;
}
void TextTool::updateFamily(const QString& text)
{
m_font.setFamily(text);
if (m_textOld.isEmpty()) {
ConfigHandler().setFontFamily(m_font.family());
}
if (m_widget != nullptr) {
m_widget->setFont(m_font);
}
}
void TextTool::updateFontUnderline(const bool underlined)
{
m_font.setUnderline(underlined);
if (m_widget != nullptr) {
m_widget->setFont(m_font);
}
}
void TextTool::updateFontStrikeOut(const bool strikeout)
{
m_font.setStrikeOut(strikeout);
if (m_widget != nullptr) {
m_widget->setFont(m_font);
}
}
void TextTool::updateFontWeight(const QFont::Weight weight)
{
m_font.setWeight(weight);
if (m_widget != nullptr) {
m_widget->setFont(m_font);
}
}
void TextTool::updateFontItalic(const bool italic)
{
m_font.setItalic(italic);
if (m_widget != nullptr) {
m_widget->setFont(m_font);
}
}
void TextTool::move(const QPoint& pos)
{
m_textArea.moveTo(pos);
}
void TextTool::updateAlignment(Qt::AlignmentFlag alignment)
{
m_alignment = alignment;
if (m_widget != nullptr) {
m_widget->setAlignment(m_alignment);
}
}
const QPoint* TextTool::pos()
{
m_currentPos = m_textArea.topLeft();
return &m_currentPos;
}
void TextTool::setEditMode(bool editMode)
{
if (editMode) {
m_textOld = m_text;
}
CaptureTool::setEditMode(editMode);
}
bool TextTool::isChanged()
{
return QString::compare(m_text, m_textOld, Qt::CaseInsensitive) != 0;
}
| 8,293
|
C++
|
.cpp
| 314
| 21.226115
| 80
| 0.644783
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,648
|
textconfig.cpp
|
flameshot-org_flameshot/src/tools/text/textconfig.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "textconfig.h"
#include "src/utils/colorutils.h"
#include "src/utils/confighandler.h"
#include "src/utils/pathinfo.h"
#include <QComboBox>
#include <QFontDatabase>
#include <QHBoxLayout>
#include <QPushButton>
TextConfig::TextConfig(QWidget* parent)
: QWidget(parent)
, m_layout(new QVBoxLayout(this))
, m_fontsCB(new QComboBox())
, m_strikeOutButton(nullptr)
, m_underlineButton(nullptr)
, m_weightButton(nullptr)
, m_italicButton(nullptr)
, m_leftAlignButton(nullptr)
, m_centerAlignButton(nullptr)
, m_rightAlignButton(nullptr)
{
QFontDatabase fontDB;
connect(m_fontsCB,
&QComboBox::currentTextChanged,
this,
&TextConfig::fontFamilyChanged);
m_fontsCB->addItems(fontDB.families());
setFontFamily(ConfigHandler().fontFamily());
QString iconPrefix = ColorUtils::colorIsDark(palette().windowText().color())
? PathInfo::blackIconPath()
: PathInfo::whiteIconPath();
m_strikeOutButton = new QPushButton(
QIcon(iconPrefix + "format_strikethrough.svg"), QLatin1String(""));
m_strikeOutButton->setCheckable(true);
connect(m_strikeOutButton,
&QPushButton::clicked,
this,
&TextConfig::fontStrikeOutChanged);
m_strikeOutButton->setToolTip(tr("StrikeOut"));
m_underlineButton = new QPushButton(
QIcon(iconPrefix + "format_underlined.svg"), QLatin1String(""));
m_underlineButton->setCheckable(true);
connect(m_underlineButton,
&QPushButton::clicked,
this,
&TextConfig::fontUnderlineChanged);
m_underlineButton->setToolTip(tr("Underline"));
m_weightButton =
new QPushButton(QIcon(iconPrefix + "format_bold.svg"), QLatin1String(""));
m_weightButton->setCheckable(true);
connect(m_weightButton,
&QPushButton::clicked,
this,
&TextConfig::weightButtonPressed);
m_weightButton->setToolTip(tr("Bold"));
m_italicButton = new QPushButton(QIcon(iconPrefix + "format_italic.svg"),
QLatin1String(""));
m_italicButton->setCheckable(true);
connect(m_italicButton,
&QPushButton::clicked,
this,
&TextConfig::fontItalicChanged);
m_italicButton->setToolTip(tr("Italic"));
auto* modifiersLayout = new QHBoxLayout();
m_leftAlignButton =
new QPushButton(QIcon(iconPrefix + "leftalign.svg"), QLatin1String(""));
m_leftAlignButton->setCheckable(true);
m_leftAlignButton->setAutoExclusive(true);
connect(m_leftAlignButton, &QPushButton::clicked, this, [this] {
alignmentChanged(Qt::AlignLeft);
});
m_leftAlignButton->setToolTip(tr("Left Align"));
m_centerAlignButton =
new QPushButton(QIcon(iconPrefix + "centeralign.svg"), QLatin1String(""));
m_centerAlignButton->setCheckable(true);
m_centerAlignButton->setAutoExclusive(true);
connect(m_centerAlignButton, &QPushButton::clicked, this, [this] {
alignmentChanged(Qt::AlignCenter);
});
m_centerAlignButton->setToolTip(tr("Center Align"));
m_rightAlignButton =
new QPushButton(QIcon(iconPrefix + "rightalign.svg"), QLatin1String(""));
m_rightAlignButton->setCheckable(true);
m_rightAlignButton->setAutoExclusive(true);
connect(m_rightAlignButton, &QPushButton::clicked, this, [this] {
alignmentChanged(Qt::AlignRight);
});
m_rightAlignButton->setToolTip(tr("Right Align"));
auto* alignmentLayout = new QHBoxLayout();
alignmentLayout->addWidget(m_leftAlignButton);
alignmentLayout->addWidget(m_centerAlignButton);
alignmentLayout->addWidget(m_rightAlignButton);
m_layout->addWidget(m_fontsCB);
modifiersLayout->addWidget(m_strikeOutButton);
modifiersLayout->addWidget(m_underlineButton);
modifiersLayout->addWidget(m_weightButton);
modifiersLayout->addWidget(m_italicButton);
m_layout->addLayout(modifiersLayout);
m_layout->addLayout(alignmentLayout);
}
void TextConfig::setFontFamily(const QString& fontFamily)
{
m_fontsCB->setCurrentIndex(
m_fontsCB->findText(fontFamily.isEmpty() ? font().family() : fontFamily));
}
void TextConfig::setUnderline(const bool underline)
{
m_underlineButton->setChecked(underline);
}
void TextConfig::setStrikeOut(const bool strikeout)
{
m_strikeOutButton->setChecked(strikeout);
}
void TextConfig::setWeight(const int weight)
{
m_weightButton->setChecked(static_cast<QFont::Weight>(weight) ==
QFont::Bold);
}
void TextConfig::setItalic(const bool italic)
{
m_italicButton->setChecked(italic);
}
void TextConfig::weightButtonPressed(const bool weight)
{
if (weight) {
emit fontWeightChanged(QFont::Bold);
} else {
emit fontWeightChanged(QFont::Normal);
}
}
void TextConfig::setTextAlignment(Qt::AlignmentFlag alignment)
{
switch (alignment) {
case (Qt::AlignCenter):
m_leftAlignButton->setChecked(false);
m_centerAlignButton->setChecked(true);
m_rightAlignButton->setChecked(false);
break;
case (Qt::AlignRight):
m_leftAlignButton->setChecked(false);
m_centerAlignButton->setChecked(false);
m_rightAlignButton->setChecked(true);
break;
case (Qt::AlignLeft):
default:
m_leftAlignButton->setChecked(true);
m_centerAlignButton->setChecked(false);
m_rightAlignButton->setChecked(false);
break;
}
emit alignmentChanged(alignment);
}
| 5,750
|
C++
|
.cpp
| 153
| 31.03268
| 80
| 0.688307
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,649
|
savetool.cpp
|
flameshot-org_flameshot/src/tools/save/savetool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "savetool.h"
#include "src/utils/screenshotsaver.h"
#include <QPainter>
SaveTool::SaveTool(QObject* parent)
: AbstractActionTool(parent)
{}
bool SaveTool::closeOnButtonPressed() const
{
return true;
}
QIcon SaveTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "content-save.svg");
}
QString SaveTool::name() const
{
return tr("Save");
}
CaptureTool::Type SaveTool::type() const
{
return CaptureTool::TYPE_SAVE;
}
QString SaveTool::description() const
{
return tr("Save screenshot to a file");
}
CaptureTool* SaveTool::copy(QObject* parent)
{
return new SaveTool(parent);
}
void SaveTool::pressed(CaptureContext& context)
{
emit requestAction(REQ_CLEAR_SELECTION);
context.request.addSaveTask();
emit requestAction(REQ_CAPTURE_DONE_OK);
emit requestAction(REQ_CLOSE_GUI);
}
| 1,020
|
C++
|
.cpp
| 40
| 23.15
| 72
| 0.760288
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,650
|
exittool.cpp
|
flameshot-org_flameshot/src/tools/exit/exittool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "exittool.h"
#include <QPainter>
ExitTool::ExitTool(QObject* parent)
: AbstractActionTool(parent)
{}
bool ExitTool::closeOnButtonPressed() const
{
return true;
}
QIcon ExitTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "close.svg");
}
QString ExitTool::name() const
{
return tr("Exit");
}
CaptureTool::Type ExitTool::type() const
{
return CaptureTool::TYPE_EXIT;
}
QString ExitTool::description() const
{
return tr("Leave the capture screen");
}
CaptureTool* ExitTool::copy(QObject* parent)
{
return new ExitTool(parent);
}
void ExitTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
emit requestAction(REQ_CLOSE_GUI);
}
| 870
|
C++
|
.cpp
| 37
| 21.27027
| 72
| 0.756364
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
2,651
|
sizeincreasetool.cpp
|
flameshot-org_flameshot/src/tools/sizeincrease/sizeincreasetool.cpp
|
// Copyright(c) 2017-2019 Alejandro Sirgo Rica & Contributors
//
// This file is part of Flameshot.
//
// Flameshot 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 3 of the License, or
// (at your option) any later version.
//
// Flameshot 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 Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "sizeincreasetool.h"
#include <QPainter>
SizeIncreaseTool::SizeIncreaseTool(QObject* parent)
: AbstractActionTool(parent)
{}
bool SizeIncreaseTool::closeOnButtonPressed() const
{
return false;
}
QIcon SizeIncreaseTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "plus.svg");
}
QString SizeIncreaseTool::name() const
{
return tr("Increase Tool Size");
}
CaptureTool::Type SizeIncreaseTool::type() const
{
return CaptureTool::TYPE_SIZEINCREASE;
}
QString SizeIncreaseTool::description() const
{
return tr("Increase the size of the other tools");
}
CaptureTool* SizeIncreaseTool::copy(QObject* parent)
{
return new SizeIncreaseTool(parent);
}
void SizeIncreaseTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
emit requestAction(REQ_INCREASE_TOOL_SIZE);
}
| 1,663
|
C++
|
.cpp
| 51
| 30.705882
| 75
| 0.754364
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
2,652
|
accepttool.cpp
|
flameshot-org_flameshot/src/tools/accept/accepttool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "accepttool.h"
#include "src/utils/screenshotsaver.h"
#include <QApplication>
#include <QPainter>
#include <QStyle>
#if defined(Q_OS_MACOS)
#include "src/widgets/capture/capturewidget.h"
#include <QWidget>
#endif
AcceptTool::AcceptTool(QObject* parent)
: AbstractActionTool(parent)
{}
bool AcceptTool::closeOnButtonPressed() const
{
return true;
}
QIcon AcceptTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "accept.svg");
}
QString AcceptTool::name() const
{
return tr("Accept");
}
CaptureTool::Type AcceptTool::type() const
{
return CaptureTool::TYPE_ACCEPT;
}
QString AcceptTool::description() const
{
return tr("Accept the capture");
}
CaptureTool* AcceptTool::copy(QObject* parent)
{
return new AcceptTool(parent);
}
void AcceptTool::pressed(CaptureContext& context)
{
emit requestAction(REQ_CAPTURE_DONE_OK);
if (context.request.tasks() & CaptureRequest::PIN) {
QRect geometry = context.selection;
geometry.moveTopLeft(geometry.topLeft() + context.widgetOffset);
context.request.addTask(CaptureRequest::PIN);
}
emit requestAction(REQ_CLOSE_GUI);
}
| 1,327
|
C++
|
.cpp
| 49
| 24.469388
| 72
| 0.756501
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,653
|
circletool.cpp
|
flameshot-org_flameshot/src/tools/circle/circletool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "circletool.h"
#include <QPainter>
CircleTool::CircleTool(QObject* parent)
: AbstractTwoPointTool(parent)
{
m_supportsDiagonalAdj = true;
}
QIcon CircleTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "circle-outline.svg");
}
QString CircleTool::name() const
{
return tr("Circle");
}
CaptureTool::Type CircleTool::type() const
{
return CaptureTool::TYPE_CIRCLE;
}
QString CircleTool::description() const
{
return tr("Set the Circle as the paint tool");
}
CaptureTool* CircleTool::copy(QObject* parent)
{
auto* tool = new CircleTool(parent);
copyParams(this, tool);
return tool;
}
void CircleTool::process(QPainter& painter, const QPixmap& pixmap)
{
Q_UNUSED(pixmap)
painter.setPen(QPen(color(), size()));
painter.drawEllipse(QRect(points().first, points().second));
}
void CircleTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
}
| 1,095
|
C++
|
.cpp
| 42
| 23.595238
| 72
| 0.747368
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,654
|
copytool.cpp
|
flameshot-org_flameshot/src/tools/copy/copytool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "copytool.h"
#include "src/utils/screenshotsaver.h"
#include <QPainter>
CopyTool::CopyTool(QObject* parent)
: AbstractActionTool(parent)
{}
bool CopyTool::closeOnButtonPressed() const
{
return true;
}
QIcon CopyTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "content-copy.svg");
}
QString CopyTool::name() const
{
return tr("Copy");
}
CaptureTool::Type CopyTool::type() const
{
return CaptureTool::TYPE_COPY;
}
QString CopyTool::description() const
{
return tr("Copy selection to clipboard");
}
CaptureTool* CopyTool::copy(QObject* parent)
{
return new CopyTool(parent);
}
void CopyTool::pressed(CaptureContext& context)
{
emit requestAction(REQ_CLEAR_SELECTION);
context.request.addTask(CaptureRequest::COPY);
emit requestAction(REQ_CAPTURE_DONE_OK);
emit requestAction(REQ_CLOSE_GUI);
}
| 1,038
|
C++
|
.cpp
| 40
| 23.6
| 72
| 0.763636
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,655
|
pixelatetool.cpp
|
flameshot-org_flameshot/src/tools/pixelate/pixelatetool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "pixelatetool.h"
#include <QApplication>
#include <QGraphicsBlurEffect>
#include <QGraphicsPixmapItem>
#include <QGraphicsScene>
#include <QImage>
#include <QPainter>
PixelateTool::PixelateTool(QObject* parent)
: AbstractTwoPointTool(parent)
{}
QIcon PixelateTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "pixelate.svg");
}
QString PixelateTool::name() const
{
return tr("Pixelate");
}
CaptureTool::Type PixelateTool::type() const
{
return CaptureTool::TYPE_PIXELATE;
}
QString PixelateTool::description() const
{
return tr("Set Pixelate as the paint tool."
" Warning: pixelation is not a security tool!"
" Secrets - especially text - can be recovered from pixelated "
"areas in some situations."
" To securely hide contents from the screenshot use a black box "
"instead.");
}
QRect PixelateTool::boundingRect() const
{
return QRect(points().first, points().second).normalized();
}
CaptureTool* PixelateTool::copy(QObject* parent)
{
auto* tool = new PixelateTool(parent);
copyParams(this, tool);
return tool;
}
void PixelateTool::process(QPainter& painter, const QPixmap& pixmap)
{
QRect selection = boundingRect().intersected(pixmap.rect());
auto pixelRatio = pixmap.devicePixelRatio();
QRect selectionScaled = QRect(selection.topLeft() * pixelRatio,
selection.bottomRight() * pixelRatio);
// If thickness is less than 1, use old blur process
if (size() <= 1) {
auto* blur = new QGraphicsBlurEffect;
blur->setBlurRadius(10);
auto* item = new QGraphicsPixmapItem(pixmap.copy(selectionScaled));
item->setGraphicsEffect(blur);
QGraphicsScene scene;
scene.addItem(item);
scene.render(&painter, selection, QRectF());
blur->setBlurRadius(12);
// multiple repeat for make blur effect stronger
scene.render(&painter, selection, QRectF());
} else {
int width =
static_cast<int>(selection.width() * (0.5 / qMax(1, size() + 1)));
int height =
static_cast<int>(selection.height() * (0.5 / qMax(1, size() + 1)));
QSize size = QSize(qMax(width, 1), qMax(height, 1));
QPixmap t = pixmap.copy(selectionScaled);
t = t.scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
t = t.scaled(selection.width(), selection.height());
painter.drawImage(selection, t.toImage());
}
}
void PixelateTool::drawSearchArea(QPainter& painter, const QPixmap& pixmap)
{
Q_UNUSED(pixmap)
painter.fillRect(boundingRect(), QBrush(Qt::black));
}
void PixelateTool::paintMousePreview(QPainter& painter,
const CaptureContext& context)
{
Q_UNUSED(context)
Q_UNUSED(painter)
}
void PixelateTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
}
| 3,113
|
C++
|
.cpp
| 89
| 29.483146
| 79
| 0.679747
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,658
|
linetool.cpp
|
flameshot-org_flameshot/src/tools/line/linetool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "linetool.h"
#include <QPainter>
LineTool::LineTool(QObject* parent)
: AbstractTwoPointTool(parent)
{
m_supportsOrthogonalAdj = true;
m_supportsDiagonalAdj = true;
}
QIcon LineTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "line.svg");
}
QString LineTool::name() const
{
return tr("Line");
}
CaptureTool::Type LineTool::type() const
{
return CaptureTool::TYPE_DRAWER;
}
QString LineTool::description() const
{
return tr("Set the Line as the paint tool");
}
CaptureTool* LineTool::copy(QObject* parent)
{
auto* tool = new LineTool(parent);
copyParams(this, tool);
return tool;
}
void LineTool::process(QPainter& painter, const QPixmap& pixmap)
{
Q_UNUSED(pixmap)
painter.setPen(QPen(color(), size()));
painter.drawLine(points().first, points().second);
}
void LineTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
}
| 1,086
|
C++
|
.cpp
| 43
| 22.697674
| 72
| 0.738878
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,659
|
penciltool.cpp
|
flameshot-org_flameshot/src/tools/pencil/penciltool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "penciltool.h"
#include <QPainter>
PencilTool::PencilTool(QObject* parent)
: AbstractPathTool(parent)
{}
QIcon PencilTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "pencil.svg");
}
QString PencilTool::name() const
{
return tr("Pencil");
}
CaptureTool::Type PencilTool::type() const
{
return CaptureTool::TYPE_PENCIL;
}
QString PencilTool::description() const
{
return tr("Set the Pencil as the paint tool");
}
CaptureTool* PencilTool::copy(QObject* parent)
{
auto* tool = new PencilTool(parent);
copyParams(this, tool);
return tool;
}
void PencilTool::process(QPainter& painter, const QPixmap& pixmap)
{
Q_UNUSED(pixmap)
painter.setPen(QPen(m_color, size()));
painter.drawPolyline(m_points.data(), m_points.size());
}
void PencilTool::paintMousePreview(QPainter& painter,
const CaptureContext& context)
{
painter.setPen(QPen(context.color, context.toolSize + 2));
painter.drawLine(context.mousePos, context.mousePos);
}
void PencilTool::drawStart(const CaptureContext& context)
{
m_color = context.color;
onSizeChanged(context.toolSize);
m_points.append(context.mousePos);
m_pathArea.setTopLeft(context.mousePos);
m_pathArea.setBottomRight(context.mousePos);
}
void PencilTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
}
| 1,551
|
C++
|
.cpp
| 54
| 25.444444
| 72
| 0.739072
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,660
|
inverttool.cpp
|
flameshot-org_flameshot/src/tools/invert/inverttool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "inverttool.h"
#include <QApplication>
#include <QGraphicsBlurEffect>
#include <QGraphicsPixmapItem>
#include <QGraphicsScene>
#include <QImage>
#include <QPainter>
#include <QPixmap>
InvertTool::InvertTool(QObject* parent)
: AbstractTwoPointTool(parent)
{}
QIcon InvertTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "invert.svg");
}
QString InvertTool::name() const
{
return tr("Invert");
}
CaptureTool::Type InvertTool::type() const
{
return CaptureTool::TYPE_INVERT;
}
QString InvertTool::description() const
{
return tr("Set Inverter as the paint tool");
}
QRect InvertTool::boundingRect() const
{
return QRect(points().first, points().second).normalized();
}
CaptureTool* InvertTool::copy(QObject* parent)
{
auto* tool = new InvertTool(parent);
copyParams(this, tool);
return tool;
}
void InvertTool::process(QPainter& painter, const QPixmap& pixmap)
{
QRect selection = boundingRect().intersected(pixmap.rect());
auto pixelRatio = pixmap.devicePixelRatio();
QRect selectionScaled = QRect(selection.topLeft() * pixelRatio,
selection.bottomRight() * pixelRatio);
// Invert selection
QPixmap inv = pixmap.copy(selectionScaled);
QImage img = inv.toImage();
img.invertPixels();
painter.drawImage(selection, img);
}
void InvertTool::drawSearchArea(QPainter& painter, const QPixmap& pixmap)
{
Q_UNUSED(pixmap)
painter.fillRect(boundingRect(), QBrush(Qt::black));
}
void InvertTool::paintMousePreview(QPainter& painter,
const CaptureContext& context)
{
Q_UNUSED(context)
Q_UNUSED(painter)
}
void InvertTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
}
| 1,929
|
C++
|
.cpp
| 67
| 25.208955
| 73
| 0.729978
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,661
|
selectiontool.cpp
|
flameshot-org_flameshot/src/tools/selection/selectiontool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "selectiontool.h"
#include <QPainter>
SelectionTool::SelectionTool(QObject* parent)
: AbstractTwoPointTool(parent)
{
m_supportsDiagonalAdj = true;
}
bool SelectionTool::closeOnButtonPressed() const
{
return false;
}
QIcon SelectionTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "square-outline.svg");
}
QString SelectionTool::name() const
{
return tr("Rectangular Selection");
}
CaptureTool::Type SelectionTool::type() const
{
return CaptureTool::TYPE_SELECTION;
}
QString SelectionTool::description() const
{
return tr("Set Selection as the paint tool");
}
CaptureTool* SelectionTool::copy(QObject* parent)
{
auto* tool = new SelectionTool(parent);
copyParams(this, tool);
return tool;
}
void SelectionTool::process(QPainter& painter, const QPixmap& pixmap)
{
Q_UNUSED(pixmap)
painter.setPen(
QPen(color(), size(), Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin));
painter.drawRect(QRect(points().first, points().second));
}
void SelectionTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
}
| 1,266
|
C++
|
.cpp
| 47
| 24.382979
| 74
| 0.755372
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,662
|
circlecounttool.cpp
|
flameshot-org_flameshot/src/tools/circlecount/circlecounttool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "circlecounttool.h"
#include "colorutils.h"
#include <QPainter>
#include <QPainterPath>
namespace {
#define PADDING_VALUE 2
#define THICKNESS_OFFSET 15
}
CircleCountTool::CircleCountTool(QObject* parent)
: AbstractTwoPointTool(parent)
, m_valid(false)
{}
QIcon CircleCountTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "circlecount-outline.svg");
}
QString CircleCountTool::info()
{
m_tempString = QString("%1 - %2").arg(name()).arg(count());
return m_tempString;
}
bool CircleCountTool::isValid() const
{
return m_valid;
}
QRect CircleCountTool::mousePreviewRect(const CaptureContext& context) const
{
int width = (context.toolSize + THICKNESS_OFFSET) * 2;
QRect rect(0, 0, width, width);
rect.moveCenter(context.mousePos);
return rect;
}
QRect CircleCountTool::boundingRect() const
{
if (!isValid()) {
return {};
}
int bubble_size = size() + THICKNESS_OFFSET + PADDING_VALUE;
int line_pos_min_x =
std::min(points().first.x() - bubble_size, points().second.x());
int line_pos_min_y =
std::min(points().first.y() - bubble_size, points().second.y());
int line_pos_max_x =
std::max(points().first.x() + bubble_size, points().second.x());
int line_pos_max_y =
std::max(points().first.y() + bubble_size, points().second.y());
return { line_pos_min_x,
line_pos_min_y,
line_pos_max_x - line_pos_min_x,
line_pos_max_y - line_pos_min_y };
}
QString CircleCountTool::name() const
{
return tr("Circle Counter");
}
CaptureTool::Type CircleCountTool::type() const
{
return CaptureTool::TYPE_CIRCLECOUNT;
}
void CircleCountTool::copyParams(const CircleCountTool* from,
CircleCountTool* to)
{
AbstractTwoPointTool::copyParams(from, to);
to->setCount(from->count());
to->m_valid = from->m_valid;
}
QString CircleCountTool::description() const
{
return tr("Add an autoincrementing counter bubble");
}
CaptureTool* CircleCountTool::copy(QObject* parent)
{
auto* tool = new CircleCountTool(parent);
copyParams(this, tool);
return tool;
}
void CircleCountTool::process(QPainter& painter, const QPixmap& pixmap)
{
Q_UNUSED(pixmap)
// save current pen, brush, and font state
auto orig_pen = painter.pen();
auto orig_brush = painter.brush();
auto orig_font = painter.font();
QColor contrastColor =
ColorUtils::colorIsDark(color()) ? Qt::white : Qt::black;
QColor antiContrastColor =
ColorUtils::colorIsDark(color()) ? Qt::black : Qt::white;
int bubble_size = size() + THICKNESS_OFFSET;
QLineF line(points().first, points().second);
// if the mouse is outside of the bubble, draw the pointer
if (line.length() > bubble_size) {
painter.setPen(QPen(color(), 0));
painter.setBrush(color());
int middleX = points().first.x();
int middleY = points().first.y();
QLineF normal = line.normalVector();
normal.setLength(bubble_size);
QPoint p1 = normal.p2().toPoint();
QPoint p2(middleX - (p1.x() - middleX), middleY - (p1.y() - middleY));
QPainterPath path;
path.moveTo(points().first);
path.lineTo(p1);
path.lineTo(points().second);
path.lineTo(p2);
path.lineTo(points().first);
painter.drawPath(path);
}
painter.setPen(contrastColor);
painter.setBrush(antiContrastColor);
painter.drawEllipse(
points().first, bubble_size + PADDING_VALUE, bubble_size + PADDING_VALUE);
painter.setBrush(color());
painter.drawEllipse(points().first, bubble_size, bubble_size);
QRect textRect = QRect(points().first.x() - bubble_size / 2,
points().first.y() - bubble_size / 2,
bubble_size,
bubble_size);
auto new_font = orig_font;
auto fontSize = bubble_size;
new_font.setPixelSize(fontSize);
new_font.setBold(true);
painter.setFont(new_font);
// Draw bounding circle
QRect bRect =
painter.boundingRect(textRect, Qt::AlignCenter, QString::number(count()));
// Calculate font size
while (bRect.width() > textRect.width()) {
fontSize--;
if (fontSize == 0) {
break;
}
new_font.setPixelSize(fontSize);
painter.setFont(new_font);
bRect = painter.boundingRect(
textRect, Qt::AlignCenter, QString::number(count()));
}
// Draw text
painter.setPen(contrastColor);
painter.drawText(textRect, Qt::AlignCenter, QString::number(count()));
// restore original font, brush, and pen
painter.setFont(orig_font);
painter.setBrush(orig_brush);
painter.setPen(orig_pen);
}
void CircleCountTool::paintMousePreview(QPainter& painter,
const CaptureContext& context)
{
onSizeChanged(context.toolSize + PADDING_VALUE);
// Thickness for pen is *2 to range from radius to diameter to match the
// ellipse draw function
auto orig_pen = painter.pen();
auto orig_opacity = painter.opacity();
painter.setOpacity(0.35);
painter.setPen(QPen(context.color,
(size() + THICKNESS_OFFSET) * 2,
Qt::SolidLine,
Qt::RoundCap));
painter.drawLine(context.mousePos,
{ context.mousePos.x() + 1, context.mousePos.y() + 1 });
painter.setOpacity(orig_opacity);
painter.setPen(orig_pen);
}
void CircleCountTool::drawStart(const CaptureContext& context)
{
AbstractTwoPointTool::drawStart(context);
m_valid = true;
}
void CircleCountTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
}
| 5,953
|
C++
|
.cpp
| 174
| 28.241379
| 80
| 0.652106
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,663
|
imguploadermanager.cpp
|
flameshot-org_flameshot/src/tools/imgupload/imguploadermanager.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Yurii Puchkov & Contributors
//
#include "imguploadermanager.h"
#include <QPixmap>
#include <QWidget>
// TODO - remove this hard-code and create plugin manager in the future, you may
// include other storage headers here
#include "storages/imgur/imguruploader.h"
ImgUploaderManager::ImgUploaderManager(QObject* parent)
: QObject(parent)
, m_imgUploaderBase(nullptr)
{
// TODO - implement ImgUploader for other Storages and selection among them
m_imgUploaderPlugin = IMG_UPLOADER_STORAGE_DEFAULT;
init();
}
void ImgUploaderManager::init()
{
// TODO - implement ImgUploader for other Storages and selection among them,
// example:
// if (uploaderPlugin().compare("s3") == 0) {
// m_qstrUrl = ImgS3Settings().value("S3", "S3_URL").toString();
//} else {
// m_qstrUrl = "https://imgur.com/";
// m_imgUploaderPlugin = "imgur";
//}
m_urlString = "https://imgur.com/";
m_imgUploaderPlugin = "imgur";
}
ImgUploaderBase* ImgUploaderManager::uploader(const QPixmap& capture,
QWidget* parent)
{
// TODO - implement ImgUploader for other Storages and selection among them,
// example:
// if (uploaderPlugin().compare("s3") == 0) {
// m_imgUploaderBase =
// (ImgUploaderBase*)(new ImgS3Uploader(capture, parent));
//} else {
// m_imgUploaderBase =
// (ImgUploaderBase*)(new ImgurUploader(capture, parent));
//}
m_imgUploaderBase = (ImgUploaderBase*)(new ImgurUploader(capture, parent));
if (m_imgUploaderBase && !capture.isNull()) {
m_imgUploaderBase->upload();
}
return m_imgUploaderBase;
}
ImgUploaderBase* ImgUploaderManager::uploader(const QString& imgUploaderPlugin)
{
m_imgUploaderPlugin = imgUploaderPlugin;
init();
return uploader(QPixmap());
}
const QString& ImgUploaderManager::uploaderPlugin()
{
return m_imgUploaderPlugin;
}
const QString& ImgUploaderManager::url()
{
return m_urlString;
}
| 2,076
|
C++
|
.cpp
| 62
| 29.419355
| 80
| 0.686939
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,664
|
imguploadertool.cpp
|
flameshot-org_flameshot/src/tools/imgupload/imguploadertool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "imguploadertool.h"
ImgUploaderTool::ImgUploaderTool(QObject* parent)
: AbstractActionTool(parent)
{}
bool ImgUploaderTool::closeOnButtonPressed() const
{
return true;
}
QIcon ImgUploaderTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "cloud-upload.svg");
}
QString ImgUploaderTool::name() const
{
return tr("Image Uploader");
}
CaptureTool::Type ImgUploaderTool::type() const
{
return CaptureTool::TYPE_IMAGEUPLOADER;
}
QString ImgUploaderTool::description() const
{
return tr("Upload the selection");
}
CaptureTool* ImgUploaderTool::copy(QObject* parent)
{
return new ImgUploaderTool(parent);
}
void ImgUploaderTool::pressed(CaptureContext& context)
{
emit requestAction(REQ_CLEAR_SELECTION);
emit requestAction(REQ_CAPTURE_DONE_OK);
context.request.addTask(CaptureRequest::UPLOAD);
emit requestAction(REQ_CLOSE_GUI);
}
| 1,072
|
C++
|
.cpp
| 38
| 25.763158
| 74
| 0.781463
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,665
|
imguploaderbase.cpp
|
flameshot-org_flameshot/src/tools/imgupload/storages/imguploaderbase.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "imguploaderbase.h"
#include "src/core/flameshotdaemon.h"
#include "src/utils/confighandler.h"
#include "src/utils/globalvalues.h"
#include "src/utils/history.h"
#include "src/utils/screenshotsaver.h"
#include "src/widgets/imagelabel.h"
#include "src/widgets/loadspinner.h"
#include "src/widgets/notificationwidget.h"
#include <QApplication>
// FIXME #include <QBuffer>
#include <QClipboard>
#include <QCursor>
#include <QDesktopServices>
#include <QDrag>
#include <QGuiApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
#include <QMimeData>
#include <QNetworkAccessManager>
#include <QPushButton>
#include <QRect>
#include <QScreen>
#include <QShortcut>
#include <QTimer>
#include <QUrlQuery>
#include <QVBoxLayout>
ImgUploaderBase::ImgUploaderBase(const QPixmap& capture, QWidget* parent)
: QWidget(parent)
, m_pixmap(capture)
{
setWindowTitle(tr("Upload image"));
setWindowIcon(QIcon(GlobalValues::iconPath()));
QRect position = frameGeometry();
QScreen* screen = QGuiApplication::screenAt(QCursor::pos());
position.moveCenter(screen->availableGeometry().center());
move(position.topLeft());
m_spinner = new LoadSpinner(this);
m_spinner->setColor(ConfigHandler().uiColor());
m_spinner->start();
m_infoLabel = new QLabel(tr("Uploading Image"));
m_infoLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
m_infoLabel->setCursor(QCursor(Qt::IBeamCursor));
m_vLayout = new QVBoxLayout();
setLayout(m_vLayout);
m_vLayout->addWidget(m_spinner, 0, Qt::AlignHCenter);
m_vLayout->addWidget(m_infoLabel);
setAttribute(Qt::WA_DeleteOnClose);
}
LoadSpinner* ImgUploaderBase::spinner()
{
return m_spinner;
}
const QUrl& ImgUploaderBase::imageURL()
{
return m_imageURL;
}
void ImgUploaderBase::setImageURL(const QUrl& imageURL)
{
m_imageURL = imageURL;
}
const QPixmap& ImgUploaderBase::pixmap()
{
return m_pixmap;
}
void ImgUploaderBase::setPixmap(const QPixmap& pixmap)
{
m_pixmap = pixmap;
}
NotificationWidget* ImgUploaderBase::notification()
{
return m_notification;
}
void ImgUploaderBase::setInfoLabelText(const QString& text)
{
m_infoLabel->setText(text);
}
void ImgUploaderBase::startDrag()
{
auto* mimeData = new QMimeData;
mimeData->setUrls(QList<QUrl>{ m_imageURL });
mimeData->setImageData(m_pixmap);
auto* dragHandler = new QDrag(this);
dragHandler->setMimeData(mimeData);
dragHandler->setPixmap(m_pixmap.scaled(
256, 256, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
dragHandler->exec();
}
void ImgUploaderBase::showPostUploadDialog()
{
m_infoLabel->deleteLater();
m_notification = new NotificationWidget();
m_vLayout->addWidget(m_notification);
auto* imageLabel = new ImageLabel();
imageLabel->setScreenshot(m_pixmap);
imageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
connect(imageLabel,
&ImageLabel::dragInitiated,
this,
&ImgUploaderBase::startDrag);
m_vLayout->addWidget(imageLabel);
m_hLayout = new QHBoxLayout();
m_vLayout->addLayout(m_hLayout);
m_copyUrlButton = new QPushButton(tr("Copy URL"));
m_openUrlButton = new QPushButton(tr("Open URL"));
m_openDeleteUrlButton = new QPushButton(tr("Delete image"));
m_toClipboardButton = new QPushButton(tr("Image to Clipboard."));
m_saveToFilesystemButton = new QPushButton(tr("Save image"));
m_hLayout->addWidget(m_copyUrlButton);
m_hLayout->addWidget(m_openUrlButton);
m_hLayout->addWidget(m_openDeleteUrlButton);
m_hLayout->addWidget(m_toClipboardButton);
m_hLayout->addWidget(m_saveToFilesystemButton);
connect(
m_copyUrlButton, &QPushButton::clicked, this, &ImgUploaderBase::copyURL);
connect(
m_openUrlButton, &QPushButton::clicked, this, &ImgUploaderBase::openURL);
connect(m_openDeleteUrlButton,
&QPushButton::clicked,
this,
&ImgUploaderBase::deleteCurrentImage);
connect(m_toClipboardButton,
&QPushButton::clicked,
this,
&ImgUploaderBase::copyImage);
QObject::connect(m_saveToFilesystemButton,
&QPushButton::clicked,
this,
&ImgUploaderBase::saveScreenshotToFilesystem);
}
void ImgUploaderBase::openURL()
{
bool successful = QDesktopServices::openUrl(m_imageURL);
if (!successful) {
m_notification->showMessage(tr("Unable to open the URL."));
}
}
void ImgUploaderBase::copyURL()
{
FlameshotDaemon::copyToClipboard(m_imageURL.toString());
m_notification->showMessage(tr("URL copied to clipboard."));
}
void ImgUploaderBase::copyImage()
{
FlameshotDaemon::copyToClipboard(m_pixmap);
m_notification->showMessage(tr("Screenshot copied to clipboard."));
}
void ImgUploaderBase::deleteCurrentImage()
{
History history;
HistoryFileName unpackFileName = history.unpackFileName(m_currentImageName);
deleteImage(unpackFileName.file, unpackFileName.token);
}
void ImgUploaderBase::saveScreenshotToFilesystem()
{
if (!saveToFilesystemGUI(m_pixmap)) {
m_notification->showMessage(
tr("Unable to save the screenshot to disk."));
return;
}
m_notification->showMessage(tr("Screenshot saved."));
}
| 5,475
|
C++
|
.cpp
| 165
| 28.963636
| 80
| 0.72908
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,666
|
imguruploader.cpp
|
flameshot-org_flameshot/src/tools/imgupload/storages/imgur/imguruploader.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "imguruploader.h"
#include "src/utils/confighandler.h"
#include "src/utils/filenamehandler.h"
#include "src/utils/history.h"
#include "src/widgets/loadspinner.h"
#include "src/widgets/notificationwidget.h"
#include <QBuffer>
#include <QDesktopServices>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QShortcut>
#include <QUrlQuery>
ImgurUploader::ImgurUploader(const QPixmap& capture, QWidget* parent)
: ImgUploaderBase(capture, parent)
{
m_NetworkAM = new QNetworkAccessManager(this);
connect(m_NetworkAM,
&QNetworkAccessManager::finished,
this,
&ImgurUploader::handleReply);
}
void ImgurUploader::handleReply(QNetworkReply* reply)
{
spinner()->deleteLater();
m_currentImageName.clear();
if (reply->error() == QNetworkReply::NoError) {
QJsonDocument response = QJsonDocument::fromJson(reply->readAll());
QJsonObject json = response.object();
QJsonObject data = json[QStringLiteral("data")].toObject();
setImageURL(data[QStringLiteral("link")].toString());
auto deleteToken = data[QStringLiteral("deletehash")].toString();
// save history
m_currentImageName = imageURL().toString();
int lastSlash = m_currentImageName.lastIndexOf("/");
if (lastSlash >= 0) {
m_currentImageName = m_currentImageName.mid(lastSlash + 1);
}
// save image to history
History history;
m_currentImageName =
history.packFileName("imgur", deleteToken, m_currentImageName);
history.save(pixmap(), m_currentImageName);
emit uploadOk(imageURL());
} else {
setInfoLabelText(reply->errorString());
}
new QShortcut(Qt::Key_Escape, this, SLOT(close()));
}
void ImgurUploader::upload()
{
QByteArray byteArray;
QBuffer buffer(&byteArray);
pixmap().save(&buffer, "PNG");
QUrlQuery urlQuery;
urlQuery.addQueryItem(QStringLiteral("title"), QStringLiteral(""));
QString description = FileNameHandler().parsedPattern();
urlQuery.addQueryItem(QStringLiteral("description"), description);
QUrl url(QStringLiteral("https://api.imgur.com/3/image"));
url.setQuery(urlQuery);
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,
"application/application/x-www-form-urlencoded");
request.setRawHeader("Authorization",
QStringLiteral("Client-ID %1")
.arg(ConfigHandler().uploadClientSecret())
.toUtf8());
m_NetworkAM->post(request, byteArray);
}
void ImgurUploader::deleteImage(const QString& fileName,
const QString& deleteToken)
{
Q_UNUSED(fileName)
bool successful = QDesktopServices::openUrl(
QUrl(QStringLiteral("https://imgur.com/delete/%1").arg(deleteToken)));
if (!successful) {
notification()->showMessage(tr("Unable to open the URL."));
}
emit deleteOk();
}
| 3,226
|
C++
|
.cpp
| 84
| 32.02381
| 76
| 0.684244
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,667
|
pinwidget.cpp
|
flameshot-org_flameshot/src/tools/pin/pinwidget.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include <QGraphicsDropShadowEffect>
#include <QGraphicsOpacityEffect>
#include <QPinchGesture>
#include "pinwidget.h"
#include "qguiappcurrentscreen.h"
#include "screenshotsaver.h"
#include "src/utils/confighandler.h"
#include "src/utils/globalvalues.h"
#include <QLabel>
#include <QMenu>
#include <QScreen>
#include <QShortcut>
#include <QVBoxLayout>
#include <QWheelEvent>
namespace {
constexpr int MARGIN = 7;
constexpr int BLUR_RADIUS = 2 * MARGIN;
constexpr qreal STEP = 0.03;
constexpr qreal MIN_SIZE = 100.0;
}
PinWidget::PinWidget(const QPixmap& pixmap,
const QRect& geometry,
QWidget* parent)
: QWidget(parent)
, m_pixmap(pixmap)
, m_layout(new QVBoxLayout(this))
, m_label(new QLabel())
, m_shadowEffect(new QGraphicsDropShadowEffect(this))
{
setWindowIcon(QIcon(GlobalValues::iconPath()));
setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
setFocusPolicy(Qt::StrongFocus);
// set the bottom widget background transparent
setAttribute(Qt::WA_TranslucentBackground);
setAttribute(Qt::WA_DeleteOnClose);
ConfigHandler conf;
m_baseColor = conf.uiColor();
m_hoverColor = conf.contrastUiColor();
m_layout->setContentsMargins(MARGIN, MARGIN, MARGIN, MARGIN);
m_shadowEffect->setColor(m_baseColor);
m_shadowEffect->setBlurRadius(BLUR_RADIUS);
m_shadowEffect->setOffset(0, 0);
setGraphicsEffect(m_shadowEffect);
setWindowOpacity(m_opacity);
m_label->setPixmap(m_pixmap);
m_layout->addWidget(m_label);
new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this, SLOT(close()));
new QShortcut(Qt::Key_Escape, this, SLOT(close()));
qreal devicePixelRatio = 1;
#if defined(Q_OS_MACOS) || defined(Q_OS_LINUX)
QScreen* currentScreen = QGuiAppCurrentScreen().currentScreen();
if (currentScreen != nullptr) {
devicePixelRatio = currentScreen->devicePixelRatio();
}
#endif
const int margin =
static_cast<int>(static_cast<double>(MARGIN) * devicePixelRatio);
QRect adjusted_pos = geometry + QMargins(margin, margin, margin, margin);
setGeometry(adjusted_pos);
#if defined(Q_OS_LINUX)
setWindowFlags(Qt::X11BypassWindowManagerHint);
#endif
#if defined(Q_OS_MACOS) || defined(Q_OS_LINUX)
if (currentScreen != nullptr) {
QPoint topLeft = currentScreen->geometry().topLeft();
adjusted_pos.setX((adjusted_pos.x() - topLeft.x()) / devicePixelRatio +
topLeft.x());
adjusted_pos.setY((adjusted_pos.y() - topLeft.y()) / devicePixelRatio +
topLeft.y());
adjusted_pos.setWidth(adjusted_pos.size().width() / devicePixelRatio);
adjusted_pos.setHeight(adjusted_pos.size().height() / devicePixelRatio);
resize(0, 0);
move(adjusted_pos.x(), adjusted_pos.y());
}
#endif
grabGesture(Qt::PinchGesture);
this->setContextMenuPolicy(Qt::CustomContextMenu);
connect(this,
&QWidget::customContextMenuRequested,
this,
&PinWidget::showContextMenu);
}
void PinWidget::closePin()
{
update();
close();
}
bool PinWidget::scrollEvent(QWheelEvent* event)
{
const auto phase = event->phase();
if (phase == Qt::ScrollPhase::ScrollUpdate
#if defined(Q_OS_LINUX) || defined(Q_OS_WINDOWS)
// Linux is getting only NoScrollPhase events.
|| phase == Qt::ScrollPhase::NoScrollPhase
#endif
) {
const auto angle = event->angleDelta();
if (angle.y() == 0) {
return true;
}
m_currentStepScaleFactor = angle.y() > 0
? m_currentStepScaleFactor + STEP
: m_currentStepScaleFactor - STEP;
m_expanding = m_currentStepScaleFactor >= 1.0;
}
#if defined(Q_OS_MACOS)
// ScrollEnd is currently supported only on Mac OSX
if (phase == Qt::ScrollPhase::ScrollEnd) {
#else
else {
#endif
m_scaleFactor *= m_currentStepScaleFactor;
m_currentStepScaleFactor = 1.0;
m_expanding = false;
}
m_sizeChanged = true;
update();
return true;
}
void PinWidget::enterEvent(QEvent*)
{
m_shadowEffect->setColor(m_hoverColor);
}
void PinWidget::leaveEvent(QEvent*)
{
m_shadowEffect->setColor(m_baseColor);
}
void PinWidget::mouseDoubleClickEvent(QMouseEvent*)
{
closePin();
}
void PinWidget::mousePressEvent(QMouseEvent* e)
{
m_dragStart = e->globalPos();
m_offsetX = e->localPos().x() / width();
m_offsetY = e->localPos().y() / height();
}
void PinWidget::mouseMoveEvent(QMouseEvent* e)
{
const QPoint delta = e->globalPos() - m_dragStart;
const int offsetW = width() * m_offsetX;
const int offsetH = height() * m_offsetY;
move(m_dragStart.x() + delta.x() - offsetW,
m_dragStart.y() + delta.y() - offsetH);
}
void PinWidget::keyPressEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_0) {
m_opacity = 1.0;
} else if (event->key() == Qt::Key_9) {
m_opacity = 0.9;
} else if (event->key() == Qt::Key_8) {
m_opacity = 0.8;
} else if (event->key() == Qt::Key_7) {
m_opacity = 0.7;
} else if (event->key() == Qt::Key_6) {
m_opacity = 0.6;
} else if (event->key() == Qt::Key_5) {
m_opacity = 0.5;
} else if (event->key() == Qt::Key_4) {
m_opacity = 0.4;
} else if (event->key() == Qt::Key_3) {
m_opacity = 0.3;
} else if (event->key() == Qt::Key_2) {
m_opacity = 0.2;
} else if (event->key() == Qt::Key_1) {
m_opacity = 0.1;
}
setWindowOpacity(m_opacity);
}
bool PinWidget::gestureEvent(QGestureEvent* event)
{
if (QGesture* pinch = event->gesture(Qt::PinchGesture)) {
pinchTriggered(static_cast<QPinchGesture*>(pinch));
}
return true;
}
void PinWidget::rotateLeft()
{
m_sizeChanged = true;
auto rotateTransform = QTransform().rotate(270);
m_pixmap = m_pixmap.transformed(rotateTransform);
}
void PinWidget::rotateRight()
{
m_sizeChanged = true;
auto rotateTransform = QTransform().rotate(90);
m_pixmap = m_pixmap.transformed(rotateTransform);
}
void PinWidget::increaseOpacity()
{
m_opacity += 0.1;
if (m_opacity > 1.0) {
m_opacity = 1.0;
}
setWindowOpacity(m_opacity);
}
void PinWidget::decreaseOpacity()
{
m_opacity -= 0.1;
if (m_opacity < 0.0) {
m_opacity = 0.0;
}
setWindowOpacity(m_opacity);
}
bool PinWidget::event(QEvent* event)
{
if (event->type() == QEvent::Gesture) {
return gestureEvent(static_cast<QGestureEvent*>(event));
} else if (event->type() == QEvent::Wheel) {
return scrollEvent(static_cast<QWheelEvent*>(event));
}
return QWidget::event(event);
}
void PinWidget::paintEvent(QPaintEvent* event)
{
if (m_sizeChanged) {
const auto aspectRatio =
m_expanding ? Qt::KeepAspectRatioByExpanding : Qt::KeepAspectRatio;
const auto transformType = ConfigHandler().antialiasingPinZoom()
? Qt::SmoothTransformation
: Qt::FastTransformation;
const qreal iw = m_pixmap.width();
const qreal ih = m_pixmap.height();
const qreal nw = qBound(MIN_SIZE,
iw * m_currentStepScaleFactor * m_scaleFactor,
static_cast<qreal>(maximumWidth()));
const qreal nh = qBound(MIN_SIZE,
ih * m_currentStepScaleFactor * m_scaleFactor,
static_cast<qreal>(maximumHeight()));
const QPixmap pix = m_pixmap.scaled(nw, nh, aspectRatio, transformType);
m_label->setPixmap(pix);
adjustSize();
m_sizeChanged = false;
}
}
void PinWidget::pinchTriggered(QPinchGesture* gesture)
{
const QPinchGesture::ChangeFlags changeFlags = gesture->changeFlags();
if (changeFlags & QPinchGesture::ScaleFactorChanged) {
m_currentStepScaleFactor = gesture->totalScaleFactor();
m_expanding = m_currentStepScaleFactor > gesture->lastScaleFactor();
}
if (gesture->state() == Qt::GestureFinished) {
m_scaleFactor *= m_currentStepScaleFactor;
m_currentStepScaleFactor = 1;
m_expanding = false;
}
m_sizeChanged = true;
update();
}
void PinWidget::showContextMenu(const QPoint& pos)
{
QMenu contextMenu(tr("Context menu"), this);
QAction copyToClipboardAction(tr("Copy to clipboard"), this);
connect(©ToClipboardAction,
&QAction::triggered,
this,
&PinWidget::copyToClipboard);
contextMenu.addAction(©ToClipboardAction);
QAction saveToFileAction(tr("Save to file"), this);
connect(
&saveToFileAction, &QAction::triggered, this, &PinWidget::saveToFile);
contextMenu.addAction(&saveToFileAction);
contextMenu.addSeparator();
QAction rotateRightAction(tr("Rotate Right"), this);
connect(
&rotateRightAction, &QAction::triggered, this, &PinWidget::rotateRight);
contextMenu.addAction(&rotateRightAction);
QAction rotateLeftAction(tr("Rotate Left"), this);
connect(
&rotateLeftAction, &QAction::triggered, this, &PinWidget::rotateLeft);
contextMenu.addAction(&rotateLeftAction);
QAction increaseOpacityAction(tr("Increase Opacity"), this);
connect(&increaseOpacityAction,
&QAction::triggered,
this,
&PinWidget::increaseOpacity);
contextMenu.addAction(&increaseOpacityAction);
QAction decreaseOpacityAction(tr("Decrease Opacity"), this);
connect(&decreaseOpacityAction,
&QAction::triggered,
this,
&PinWidget::decreaseOpacity);
contextMenu.addAction(&decreaseOpacityAction);
QAction closePinAction(tr("Close"), this);
connect(&closePinAction, &QAction::triggered, this, &PinWidget::closePin);
contextMenu.addSeparator();
contextMenu.addAction(&closePinAction);
contextMenu.exec(mapToGlobal(pos));
}
void PinWidget::copyToClipboard()
{
saveToClipboard(m_pixmap);
}
void PinWidget::saveToFile()
{
hide();
saveToFilesystemGUI(m_pixmap);
show();
}
| 10,355
|
C++
|
.cpp
| 303
| 28.184818
| 80
| 0.655141
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,668
|
pintool.cpp
|
flameshot-org_flameshot/src/tools/pin/pintool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "pintool.h"
#include "src/core/qguiappcurrentscreen.h"
#include "src/tools/pin/pinwidget.h"
#include <QScreen>
PinTool::PinTool(QObject* parent)
: AbstractActionTool(parent)
{}
bool PinTool::closeOnButtonPressed() const
{
return true;
}
QIcon PinTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "pin.svg");
}
QString PinTool::name() const
{
return tr("Pin Tool");
}
CaptureTool::Type PinTool::type() const
{
return CaptureTool::TYPE_PIN;
}
QString PinTool::description() const
{
return tr("Pin image on the desktop");
}
CaptureTool* PinTool::copy(QObject* parent)
{
return new PinTool(parent);
}
void PinTool::pressed(CaptureContext& context)
{
emit requestAction(REQ_CLEAR_SELECTION);
emit requestAction(REQ_CAPTURE_DONE_OK);
context.request.addTask(CaptureRequest::PIN);
emit requestAction(REQ_CLOSE_GUI);
}
| 1,057
|
C++
|
.cpp
| 41
| 23.463415
| 72
| 0.758929
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,669
|
movetool.cpp
|
flameshot-org_flameshot/src/tools/move/movetool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "movetool.h"
#include <QPainter>
MoveTool::MoveTool(QObject* parent)
: AbstractActionTool(parent)
{}
bool MoveTool::closeOnButtonPressed() const
{
return false;
}
QIcon MoveTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "cursor-move.svg");
}
QString MoveTool::name() const
{
return tr("Move");
}
CaptureTool::Type MoveTool::type() const
{
return CaptureTool::TYPE_MOVESELECTION;
}
QString MoveTool::description() const
{
return tr("Move the selection area");
}
CaptureTool* MoveTool::copy(QObject* parent)
{
return new MoveTool(parent);
}
void MoveTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
}
bool MoveTool::isSelectable() const
{
return true;
}
| 904
|
C++
|
.cpp
| 40
| 20.425
| 72
| 0.759064
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
2,670
|
arrowtool.cpp
|
flameshot-org_flameshot/src/tools/arrow/arrowtool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "arrowtool.h"
#include <cmath>
namespace {
const int ArrowWidth = 10;
const int ArrowHeight = 18;
QPainterPath getArrowHead(QPoint p1, QPoint p2, const int thickness)
{
QLineF base(p1, p2);
// Create the vector for the position of the base of the arrowhead
QLineF temp(QPoint(0, 0), p2 - p1);
int val = ArrowHeight + thickness * 4;
if (base.length() < (val - thickness * 2)) {
val = static_cast<int>(base.length() + thickness * 2);
}
temp.setLength(base.length() + thickness * 2 - val);
// Move across the line up to the head
QPointF bottomTranslation(temp.p2());
// Rotate base of the arrowhead
base.setLength(ArrowWidth + thickness * 2);
base.setAngle(base.angle() + 90);
// Move to the correct point
QPointF temp2 = p1 - base.p2();
// Center it
QPointF centerTranslation((temp2.x() / 2), (temp2.y() / 2));
base.translate(bottomTranslation);
base.translate(centerTranslation);
QPainterPath path;
path.moveTo(p2);
path.lineTo(base.p1());
path.lineTo(base.p2());
path.lineTo(p2);
return path;
}
// gets a shorter line to prevent overlap in the point of the arrow
QLine getShorterLine(QPoint p1, QPoint p2, const int thickness)
{
QLineF l(p1, p2);
int val = ArrowHeight + thickness * 4;
if (l.length() < (val - thickness * 2)) {
// here should be 0, but then we lose "angle", so this is hack, but
// looks not very bad
val = thickness / 4;
l.setLength(val);
} else {
l.setLength(l.length() + thickness * 2 - val);
}
return l.toLine();
}
} // unnamed namespace
ArrowTool::ArrowTool(QObject* parent)
: AbstractTwoPointTool(parent)
{
setPadding(ArrowWidth / 2);
m_supportsOrthogonalAdj = true;
m_supportsDiagonalAdj = true;
}
QIcon ArrowTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "arrow-bottom-left.svg");
}
QString ArrowTool::name() const
{
return tr("Arrow");
}
CaptureTool::Type ArrowTool::type() const
{
return CaptureTool::TYPE_ARROW;
}
QString ArrowTool::description() const
{
return tr("Set the Arrow as the paint tool");
}
QRect ArrowTool::boundingRect() const
{
if (!isValid()) {
return {};
}
int offset = size() <= 1 ? 1 : static_cast<int>(round(size() / 2 + 0.5));
// get min and max arrow pos
int min_x = points().first.x();
int min_y = points().first.y();
int max_x = points().first.x();
int max_y = points().first.y();
for (int i = 0; i < m_arrowPath.elementCount(); i++) {
QPointF pt = m_arrowPath.elementAt(i);
if (static_cast<int>(pt.x()) < min_x) {
min_x = static_cast<int>(pt.x());
}
if (static_cast<int>(pt.y()) < min_y) {
min_y = static_cast<int>(pt.y());
}
if (static_cast<int>(pt.x()) > max_x) {
max_x = static_cast<int>(pt.x());
}
if (static_cast<int>(pt.y()) > max_y) {
max_y = static_cast<int>(pt.y());
}
}
// get min and max line pos
int line_pos_min_x =
std::min(std::min(points().first.x(), points().second.x()), min_x);
int line_pos_min_y =
std::min(std::min(points().first.y(), points().second.y()), min_y);
int line_pos_max_x =
std::max(std::max(points().first.x(), points().second.x()), max_x);
int line_pos_max_y =
std::max(std::max(points().first.y(), points().second.y()), max_y);
QRect rect = QRect(line_pos_min_x - offset,
line_pos_min_y - offset,
line_pos_max_x - line_pos_min_x + offset * 2,
line_pos_max_y - line_pos_min_y + offset * 2);
return rect.normalized();
}
CaptureTool* ArrowTool::copy(QObject* parent)
{
auto* tool = new ArrowTool(parent);
copyParams(this, tool);
return tool;
}
void ArrowTool::copyParams(const ArrowTool* from, ArrowTool* to)
{
AbstractTwoPointTool::copyParams(from, to);
to->m_arrowPath = this->m_arrowPath;
}
void ArrowTool::process(QPainter& painter, const QPixmap& pixmap)
{
Q_UNUSED(pixmap)
painter.setPen(QPen(color(), size()));
painter.drawLine(getShorterLine(points().first, points().second, size()));
m_arrowPath = getArrowHead(points().first, points().second, size());
painter.fillPath(m_arrowPath, QBrush(color()));
}
void ArrowTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
}
| 4,622
|
C++
|
.cpp
| 139
| 28.244604
| 78
| 0.627214
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,671
|
rectangletool.cpp
|
flameshot-org_flameshot/src/tools/rectangle/rectangletool.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "rectangletool.h"
#include <QPainter>
#include <QPainterPath>
#include <cmath>
RectangleTool::RectangleTool(QObject* parent)
: AbstractTwoPointTool(parent)
{
m_supportsDiagonalAdj = true;
}
QIcon RectangleTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor)
return QIcon(iconPath(background) + "square.svg");
}
QString RectangleTool::name() const
{
return tr("Rectangle");
}
CaptureTool::Type RectangleTool::type() const
{
return CaptureTool::TYPE_RECTANGLE;
}
QString RectangleTool::description() const
{
return tr("Set the Rectangle as the paint tool");
}
CaptureTool* RectangleTool::copy(QObject* parent)
{
auto* tool = new RectangleTool(parent);
copyParams(this, tool);
return tool;
}
void RectangleTool::process(QPainter& painter, const QPixmap& pixmap)
{
Q_UNUSED(pixmap)
QPen orig_pen = painter.pen();
QBrush orig_brush = painter.brush();
painter.setPen(
QPen(color(), size(), Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin));
painter.setBrush(QBrush(color()));
if (size() == 0) {
painter.drawRect(QRect(points().first, points().second));
} else {
QPainterPath path;
int offset =
size() <= 1 ? 1 : static_cast<int>(round(size() / 2 + 0.5));
path.addRoundedRect(
QRectF(
std::min(points().first.x(), points().second.x()) - offset,
std::min(points().first.y(), points().second.y()) - offset,
std::abs(points().first.x() - points().second.x()) + offset * 2,
std::abs(points().first.y() - points().second.y()) + offset * 2),
size(),
size());
painter.fillPath(path, color());
}
painter.setPen(orig_pen);
painter.setBrush(orig_brush);
}
void RectangleTool::drawStart(const CaptureContext& context)
{
AbstractTwoPointTool::drawStart(context);
onSizeChanged(context.toolSize);
}
void RectangleTool::pressed(CaptureContext& context)
{
Q_UNUSED(context)
}
| 2,136
|
C++
|
.cpp
| 70
| 26.185714
| 77
| 0.672825
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,672
|
colorpickerwidget.cpp
|
flameshot-org_flameshot/src/widgets/colorpickerwidget.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2022 Dearsh Oberoi
#include "colorpickerwidget.h"
#include "src/utils/confighandler.h"
#include "src/utils/globalvalues.h"
#include <QMouseEvent>
#include <QPainter>
ColorPickerWidget::ColorPickerWidget(QWidget* parent)
: QWidget(parent)
, m_selectedIndex(1)
, m_lastIndex(1)
{
initColorPicker();
}
const QVector<QColor>& ColorPickerWidget::getDefaultSmallColorPalette()
{
return defaultSmallColorPalette;
}
const QVector<QColor>& ColorPickerWidget::getDefaultLargeColorPalette()
{
return defaultLargeColorPalette;
}
void ColorPickerWidget::paintEvent(QPaintEvent* e)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(QColor(Qt::black));
for (int i = 0; i < m_colorAreaList.size(); ++i) {
if (e->region().contains(m_colorAreaList.at(i))) {
painter.setClipRegion(e->region());
repaint(i, painter);
}
}
}
void ColorPickerWidget::repaint(int i, QPainter& painter)
{
// draw the highlight when we have to draw the selected color
if (i == m_selectedIndex) {
auto c = QColor(m_uiColor);
c.setAlpha(155);
painter.setBrush(c);
c.setAlpha(100);
painter.setPen(c);
QRect highlight = m_colorAreaList.at(i);
const int highlightThickness = 6;
// makes the highlight and color circles concentric
highlight.moveTo(highlight.x() - (highlightThickness / 2),
highlight.y() - (highlightThickness / 2));
highlight.setHeight(highlight.height() + highlightThickness);
highlight.setWidth(highlight.width() + highlightThickness);
painter.drawRoundedRect(highlight, 100, 100);
painter.setPen(QColor(Qt::black));
}
// draw available colors
if (m_colorList.at(i).isValid()) {
// draw preset color
painter.setBrush(QColor(m_colorList.at(i)));
painter.drawRoundedRect(m_colorAreaList.at(i), 100, 100);
} else {
// draw rainbow (part) for custom color
QRect lastRect = m_colorAreaList.at(i);
int nStep = 1;
int nSteps = lastRect.height() / nStep;
// 0.02 - start rainbow color, 0.33 - end rainbow color from range:
// 0.0 - 1.0
float h = 0.02;
for (int radius = nSteps; radius > 0; radius -= nStep * 2) {
// calculate color
float fHStep = (0.33 - h) / (nSteps / nStep / 2);
QColor color = QColor::fromHslF(h, 0.95, 0.5);
// set color and draw circle
painter.setPen(color);
painter.setBrush(color);
painter.drawRoundedRect(lastRect, 100, 100);
// set next color, circle geometry
h += fHStep;
lastRect.setX(lastRect.x() + nStep);
lastRect.setY(lastRect.y() + nStep);
lastRect.setHeight(lastRect.height() - nStep);
lastRect.setWidth(lastRect.width() - nStep);
painter.setPen(QColor(Qt::black));
}
}
}
void ColorPickerWidget::updateSelection(int index)
{
m_selectedIndex = index;
update(m_colorAreaList.at(index) + QMargins(10, 10, 10, 10));
update(m_colorAreaList.at(m_lastIndex) + QMargins(10, 10, 10, 10));
m_lastIndex = index;
}
void ColorPickerWidget::updateWidget()
{
m_colorAreaList.clear();
initColorPicker();
update();
}
void ColorPickerWidget::initColorPicker()
{
ConfigHandler config;
m_colorList = config.userColors();
m_colorAreaSize = GlobalValues::buttonBaseSize() * 0.6;
// save the color values in member variables for faster access
m_uiColor = config.uiColor();
// extraSize represents the extra space needed for the highlight of the
// selected color.
const int extraSize = 6;
const double slope = 3;
double radius = slope * m_colorList.size() + GlobalValues::buttonBaseSize();
setMinimumSize(radius * 2 + m_colorAreaSize + extraSize,
radius * 2 + m_colorAreaSize + extraSize);
resize(radius * 2 + m_colorAreaSize + extraSize,
radius * 2 + m_colorAreaSize + extraSize);
double degree = (double)360 / m_colorList.size();
double degreeAcum = 90;
// this line is the radius of the circle which will be rotated to add
// the color components.
QLineF baseLine =
QLineF(QPoint(radius + extraSize / 2, radius + extraSize / 2),
QPoint(radius + extraSize / 2, extraSize / 2));
for (int i = 0; i < m_colorList.size(); ++i) {
m_colorAreaList.append(QRect(
baseLine.x2(), baseLine.y2(), m_colorAreaSize, m_colorAreaSize));
degreeAcum += degree;
baseLine.setAngle(degreeAcum);
}
}
QVector<QColor> ColorPickerWidget::defaultSmallColorPalette = {
QColor(), Qt::darkRed, Qt::red, Qt::yellow, Qt::green,
Qt::darkGreen, Qt::cyan, Qt::blue, Qt::magenta, Qt::darkMagenta
};
QVector<QColor> ColorPickerWidget::defaultLargeColorPalette = {
QColor(), Qt::white, Qt::red, Qt::green, Qt::blue,
Qt::black, Qt::darkRed, Qt::darkGreen, Qt::darkBlue, Qt::darkGray,
Qt::cyan, Qt::magenta, Qt::yellow, Qt::lightGray, Qt::darkCyan,
Qt::darkMagenta, Qt::darkYellow
};
| 5,312
|
C++
|
.cpp
| 137
| 32.445255
| 80
| 0.645975
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,673
|
orientablepushbutton.cpp
|
flameshot-org_flameshot/src/widgets/orientablepushbutton.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
// Based on https://stackoverflow.com/a/53135675/964478
#include "orientablepushbutton.h"
#include <QPainter>
#include <QStyleOptionButton>
#include <QStylePainter>
OrientablePushButton::OrientablePushButton(QWidget* parent)
: CaptureButton(parent)
{}
OrientablePushButton::OrientablePushButton(const QString& text, QWidget* parent)
: CaptureButton(text, parent)
{}
OrientablePushButton::OrientablePushButton(const QIcon& icon,
const QString& text,
QWidget* parent)
: CaptureButton(icon, text, parent)
{}
QSize OrientablePushButton::sizeHint() const
{
QSize sh = QPushButton::sizeHint();
if (m_orientation != OrientablePushButton::Horizontal) {
sh.transpose();
}
return sh;
}
void OrientablePushButton::paintEvent(QPaintEvent* event)
{
Q_UNUSED(event)
QStylePainter painter(this);
QStyleOptionButton option;
initStyleOption(&option);
if (m_orientation == OrientablePushButton::VerticalTopToBottom) {
painter.rotate(90);
painter.translate(0, -1 * width());
option.rect = option.rect.transposed();
}
else if (m_orientation == OrientablePushButton::VerticalBottomToTop) {
painter.rotate(-90);
painter.translate(-1 * height(), 0);
option.rect = option.rect.transposed();
}
painter.drawControl(QStyle::CE_PushButton, option);
}
OrientablePushButton::Orientation OrientablePushButton::orientation() const
{
return m_orientation;
}
void OrientablePushButton::setOrientation(
OrientablePushButton::Orientation orientation)
{
m_orientation = orientation;
}
| 1,791
|
C++
|
.cpp
| 53
| 28.54717
| 80
| 0.715032
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,674
|
uploadlineitem.cpp
|
flameshot-org_flameshot/src/widgets/uploadlineitem.cpp
|
#include "uploadlineitem.h"
#include "./ui_uploadlineitem.h"
#include "src/core/flameshotdaemon.h"
#include "src/tools/imgupload/imguploadermanager.h"
#include "src/utils/confighandler.h"
#include "src/utils/history.h"
#include "src/widgets/notificationwidget.h"
#include <QDesktopServices>
#include <QFileInfo>
#include <QMessageBox>
#include <QUrl>
#include <QWidget>
void removeCacheFile(QString const& fullFileName)
{
QFile file(fullFileName);
if (file.exists()) {
file.remove();
}
}
UploadLineItem::UploadLineItem(QWidget* parent,
QPixmap const& preview,
QString const& timestamp,
QString const& url,
QString const& fullFileName,
HistoryFileName const& unpackFileName)
: QWidget(parent)
, ui(new Ui::UploadLineItem)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
ui->imagePreview->setPixmap(preview);
ui->uploadTimestamp->setText(timestamp);
connect(ui->copyUrl, &QPushButton::clicked, this, [=]() {
FlameshotDaemon::copyToClipboard(url);
});
connect(ui->openBrowser, &QPushButton::clicked, this, [=]() {
QDesktopServices::openUrl(QUrl(url));
});
connect(ui->deleteImage, &QPushButton::clicked, this, [=]() {
if (ConfigHandler().historyConfirmationToDelete() &&
QMessageBox::No ==
QMessageBox::question(
this,
tr("Confirm to delete"),
tr("Are you sure you want to delete a screenshot from the "
"latest uploads and server?"),
QMessageBox::Yes | QMessageBox::No)) {
return;
}
ImgUploaderBase* imgUploaderBase =
ImgUploaderManager(this).uploader(unpackFileName.type);
imgUploaderBase->deleteImage(unpackFileName.file, unpackFileName.token);
removeCacheFile(fullFileName);
emit requestedDeletion();
});
}
UploadLineItem::~UploadLineItem()
{
delete ui;
}
| 2,092
|
C++
|
.cpp
| 60
| 26.766667
| 80
| 0.628953
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,675
|
trayicon.cpp
|
flameshot-org_flameshot/src/widgets/trayicon.cpp
|
#include "trayicon.h"
#include "src/core/flameshot.h"
#include "src/core/flameshotdaemon.h"
#include "src/utils/globalvalues.h"
#include "src/utils/confighandler.h"
#include <QApplication>
#include <QMenu>
#include <QTimer>
#include <QUrl>
#include <QVersionNumber>
#if defined(Q_OS_MACOS)
#include <QOperatingSystemVersion>
#endif
TrayIcon::TrayIcon(QObject* parent)
: QSystemTrayIcon(parent)
{
initMenu();
setToolTip(QStringLiteral("Flameshot"));
#if defined(Q_OS_MACOS)
// Because of the following issues on MacOS "Catalina":
// https://bugreports.qt.io/browse/QTBUG-86393
// https://developer.apple.com/forums/thread/126072
auto currentMacOsVersion = QOperatingSystemVersion::current();
if (currentMacOsVersion >= currentMacOsVersion.MacOSBigSur) {
setContextMenu(m_menu);
}
#else
setContextMenu(m_menu);
#endif
QIcon icon =
QIcon::fromTheme("flameshot-tray", QIcon(GlobalValues::iconPathPNG()));
setIcon(icon);
#if defined(Q_OS_MACOS)
if (currentMacOsVersion < currentMacOsVersion.MacOSBigSur) {
// Because of the following issues on MacOS "Catalina":
// https://bugreports.qt.io/browse/QTBUG-86393
// https://developer.apple.com/forums/thread/126072
auto trayIconActivated = [this](QSystemTrayIcon::ActivationReason r) {
if (m_menu->isVisible()) {
m_menu->hide();
} else {
m_menu->popup(QCursor::pos());
}
};
connect(this, &QSystemTrayIcon::activated, this, trayIconActivated);
}
#else
connect(this, &TrayIcon::activated, this, [this](ActivationReason r) {
if (r == Trigger) {
startGuiCapture();
}
});
#endif
#ifdef Q_OS_WIN
// Ensure proper removal of tray icon when program quits on Windows.
connect(qApp, &QCoreApplication::aboutToQuit, this, &TrayIcon::hide);
#endif
show(); // TODO needed?
if (ConfigHandler().showStartupLaunchMessage()) {
showMessage(
"Flameshot",
QObject::tr(
"Hello, I'm here! Click icon in the tray to take a screenshot or "
"click with a right button to see more options."),
icon,
3000);
}
connect(ConfigHandler::getInstance(),
&ConfigHandler::fileChanged,
this,
[this]() {});
}
TrayIcon::~TrayIcon()
{
delete m_menu;
}
#if !defined(DISABLE_UPDATE_CHECKER)
QAction* TrayIcon::appUpdates()
{
return m_appUpdates;
}
#endif
void TrayIcon::initMenu()
{
m_menu = new QMenu();
auto* captureAction = new QAction(tr("&Take Screenshot"), this);
connect(captureAction, &QAction::triggered, this, [this]() {
#if defined(Q_OS_MACOS)
auto currentMacOsVersion = QOperatingSystemVersion::current();
if (currentMacOsVersion >= currentMacOsVersion.MacOSBigSur) {
startGuiCapture();
} else {
// It seems it is not relevant for MacOS BigSur (Wait 400 ms to hide
// the QMenu)
QTimer::singleShot(400, this, [this]() { startGuiCapture(); });
}
#else
// Wait 400 ms to hide the QMenu
QTimer::singleShot(400, this, [this]() {
startGuiCapture();
});
#endif
});
auto* launcherAction = new QAction(tr("&Open Launcher"), this);
connect(launcherAction,
&QAction::triggered,
Flameshot::instance(),
&Flameshot::launcher);
auto* configAction = new QAction(tr("&Configuration"), this);
connect(configAction,
&QAction::triggered,
Flameshot::instance(),
&Flameshot::config);
auto* infoAction = new QAction(tr("&About"), this);
connect(
infoAction, &QAction::triggered, Flameshot::instance(), &Flameshot::info);
#if !defined(DISABLE_UPDATE_CHECKER)
m_appUpdates = new QAction(tr("Check for updates"), this);
connect(m_appUpdates,
&QAction::triggered,
FlameshotDaemon::instance(),
&FlameshotDaemon::checkForUpdates);
connect(FlameshotDaemon::instance(),
&FlameshotDaemon::newVersionAvailable,
this,
[this](const QVersionNumber& version) {
QString newVersion =
tr("New version %1 is available").arg(version.toString());
m_appUpdates->setText(newVersion);
});
#endif
QAction* quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
// recent screenshots
QAction* recentAction = new QAction(tr("&Latest Uploads"), this);
connect(recentAction,
&QAction::triggered,
Flameshot::instance(),
&Flameshot::history);
auto* openSavePathAction = new QAction(tr("&Open Save Path"), this);
connect(openSavePathAction,
&QAction::triggered,
Flameshot::instance(),
&Flameshot::openSavePath);
m_menu->addAction(captureAction);
m_menu->addAction(launcherAction);
m_menu->addSeparator();
m_menu->addAction(recentAction);
m_menu->addAction(openSavePathAction);
m_menu->addSeparator();
m_menu->addAction(configAction);
m_menu->addSeparator();
#if !defined(DISABLE_UPDATE_CHECKER)
m_menu->addAction(m_appUpdates);
#endif
m_menu->addAction(infoAction);
m_menu->addSeparator();
m_menu->addAction(quitAction);
}
#if !defined(DISABLE_UPDATE_CHECKER)
void TrayIcon::enableCheckUpdatesAction(bool enable)
{
if (m_appUpdates != nullptr) {
m_appUpdates->setVisible(enable);
m_appUpdates->setEnabled(enable);
}
if (enable) {
FlameshotDaemon::instance()->getLatestAvailableVersion();
}
}
#endif
void TrayIcon::startGuiCapture()
{
auto* widget = Flameshot::instance()->gui();
#if !defined(DISABLE_UPDATE_CHECKER)
FlameshotDaemon::instance()->showUpdateNotificationIfAvailable(widget);
#endif
}
| 5,960
|
C++
|
.cpp
| 178
| 27.191011
| 80
| 0.651389
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,676
|
imguploaddialog.cpp
|
flameshot-org_flameshot/src/widgets/imguploaddialog.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "imguploaddialog.h"
#include "src/utils/confighandler.h"
#include "src/utils/globalvalues.h"
#include <QCheckBox>
#include <QDialogButtonBox>
#include <QLabel>
#include <QVBoxLayout>
ImgUploadDialog::ImgUploadDialog(QDialog* parent)
: QDialog(parent)
{
setAttribute(Qt::WA_DeleteOnClose);
setMinimumSize(400, 120);
setWindowIcon(QIcon(GlobalValues::iconPath()));
setWindowTitle(tr("Upload Confirmation"));
layout = new QVBoxLayout(this);
m_uploadLabel = new QLabel(tr("Do you want to upload this capture?"), this);
layout->addWidget(m_uploadLabel);
buttonBox =
new QDialogButtonBox(QDialogButtonBox::Yes | QDialogButtonBox::No);
connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
layout->addWidget(buttonBox);
m_uploadWithoutConfirmation =
new QCheckBox(tr("Upload without confirmation"), this);
m_uploadWithoutConfirmation->setToolTip(tr("Upload without confirmation"));
connect(m_uploadWithoutConfirmation, &QCheckBox::clicked, [](bool checked) {
ConfigHandler().setUploadWithoutConfirmation(checked);
});
layout->addWidget(m_uploadWithoutConfirmation);
}
| 1,375
|
C++
|
.cpp
| 32
| 39
| 80
| 0.756372
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,677
|
updatenotificationwidget.cpp
|
flameshot-org_flameshot/src/widgets/updatenotificationwidget.cpp
|
//
// Created by yuriypuchkov on 09.12.2020.
//
#include "updatenotificationwidget.h"
#include "src/utils/confighandler.h"
#include <QDesktopServices>
#include <QLabel>
#include <QPropertyAnimation>
#include <QPushButton>
#include <QScrollArea>
#include <QTimer>
#include <QVBoxLayout>
#include <QWheelEvent>
#include <utility>
UpdateNotificationWidget::UpdateNotificationWidget(
QWidget* parent,
const QString& appLatestVersion,
QString appLatestUrl)
: QWidget(parent)
, m_appLatestVersion(appLatestVersion)
, m_appLatestUrl(std::move(appLatestUrl))
, m_layout(nullptr)
{
setMinimumSize(400, 100);
initInternalPanel();
setAttribute(Qt::WA_TransparentForMouseEvents);
setCursor(Qt::ArrowCursor);
m_showAnimation = new QPropertyAnimation(m_internalPanel, "geometry", this);
m_showAnimation->setEasingCurve(QEasingCurve::InOutQuad);
m_showAnimation->setDuration(300);
m_hideAnimation = new QPropertyAnimation(m_internalPanel, "geometry", this);
m_hideAnimation->setEasingCurve(QEasingCurve::InOutQuad);
m_hideAnimation->setDuration(300);
connect(m_hideAnimation,
&QPropertyAnimation::finished,
m_internalPanel,
&QWidget::hide);
setAppLatestVersion(appLatestVersion);
}
void UpdateNotificationWidget::show()
{
setAttribute(Qt::WA_TransparentForMouseEvents, false);
m_showAnimation->setStartValue(QRect(0, -height(), width(), height()));
m_showAnimation->setEndValue(QRect(0, 0, width(), height()));
m_internalPanel->show();
m_showAnimation->start();
QWidget::show();
}
void UpdateNotificationWidget::hide()
{
setAttribute(Qt::WA_TransparentForMouseEvents);
m_hideAnimation->setStartValue(QRect(0, 0, width(), height()));
m_hideAnimation->setEndValue(QRect(0, -height(), 0, height()));
m_hideAnimation->start();
m_internalPanel->hide();
QWidget::hide();
}
void UpdateNotificationWidget::setAppLatestVersion(const QString& latestVersion)
{
m_appLatestVersion = latestVersion;
QString newVersion =
tr("New Flameshot version %1 is available").arg(latestVersion);
m_notification->setText(newVersion);
}
void UpdateNotificationWidget::laterButton()
{
hide();
}
void UpdateNotificationWidget::ignoreButton()
{
ConfigHandler().setIgnoreUpdateToVersion(m_appLatestVersion);
hide();
}
void UpdateNotificationWidget::updateButton()
{
QDesktopServices::openUrl(m_appLatestUrl);
hide();
if (parentWidget()) {
parentWidget()->close();
}
}
void UpdateNotificationWidget::initInternalPanel()
{
m_internalPanel = new QScrollArea(this);
m_internalPanel->setAttribute(Qt::WA_NoMousePropagation);
auto* widget = new QWidget();
m_internalPanel->setWidget(widget);
m_internalPanel->setWidgetResizable(true);
QColor bgColor = palette().window().color();
bgColor.setAlphaF(0.0);
m_internalPanel->setStyleSheet(
QStringLiteral("QScrollArea {background-color: %1}").arg(bgColor.name()));
m_internalPanel->hide();
//
m_layout = new QVBoxLayout();
widget->setLayout(m_layout);
// caption
m_notification = new QLabel(m_appLatestVersion, this);
m_layout->addWidget(m_notification);
// buttons layout
auto* buttonsLayout = new QHBoxLayout();
auto* bottonsSpacer = new QSpacerItem(1, 1, QSizePolicy::Expanding);
buttonsLayout->addSpacerItem(bottonsSpacer);
m_layout->addLayout(buttonsLayout);
// ignore
auto* ignoreBtn = new QPushButton(tr("Ignore"), this);
buttonsLayout->addWidget(ignoreBtn);
connect(ignoreBtn,
&QPushButton::clicked,
this,
&UpdateNotificationWidget::ignoreButton);
// later
auto* laterBtn = new QPushButton(tr("Later"), this);
buttonsLayout->addWidget(laterBtn);
connect(laterBtn,
&QPushButton::clicked,
this,
&UpdateNotificationWidget::laterButton);
// update
auto* updateBtn = new QPushButton(tr("Update"), this);
buttonsLayout->addWidget(updateBtn);
connect(updateBtn,
&QPushButton::clicked,
this,
&UpdateNotificationWidget::updateButton);
}
| 4,191
|
C++
|
.cpp
| 126
| 28.603175
| 80
| 0.717746
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,679
|
uploadhistory.cpp
|
flameshot-org_flameshot/src/widgets/uploadhistory.cpp
|
#include "uploadhistory.h"
#include "./ui_uploadhistory.h"
#include "src/tools/imgupload/imguploadermanager.h"
#include "src/utils/confighandler.h"
#include "src/utils/history.h"
#include "uploadlineitem.h"
#include <QDateTime>
#include <QDesktopWidget>
#include <QFileInfo>
#include <QPixmap>
void scaleThumbnail(QPixmap& pixmap)
{
if (pixmap.height() / HISTORYPIXMAP_MAX_PREVIEW_HEIGHT >=
pixmap.width() / HISTORYPIXMAP_MAX_PREVIEW_WIDTH) {
pixmap = pixmap.scaledToHeight(HISTORYPIXMAP_MAX_PREVIEW_HEIGHT,
Qt::SmoothTransformation);
} else {
pixmap = pixmap.scaledToWidth(HISTORYPIXMAP_MAX_PREVIEW_WIDTH,
Qt::SmoothTransformation);
}
}
void clearHistoryLayout(QLayout* layout)
{
while (layout->count() != 0) {
delete layout->takeAt(0);
}
}
UploadHistory::UploadHistory(QWidget* parent)
: QWidget(parent)
, ui(new Ui::UploadHistory)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
resize(QDesktopWidget().availableGeometry(this).size() * 0.5);
}
void UploadHistory::loadHistory()
{
clearHistoryLayout(ui->historyContainer);
History history = History();
QList<QString> historyFiles = history.history();
if (historyFiles.isEmpty()) {
setEmptyMessage();
} else {
foreach (QString fileName, historyFiles) {
addLine(history.path(), fileName);
}
}
}
void UploadHistory::setEmptyMessage()
{
auto* buttonEmpty = new QPushButton;
buttonEmpty->setText(tr("Screenshots history is empty"));
buttonEmpty->setMinimumSize(1, HISTORYPIXMAP_MAX_PREVIEW_HEIGHT);
connect(buttonEmpty, &QPushButton::clicked, this, [=]() { this->close(); });
ui->historyContainer->addWidget(buttonEmpty);
}
void UploadHistory::addLine(const QString& path, const QString& fileName)
{
QString fullFileName = path + fileName;
History history;
HistoryFileName unpackFileName = history.unpackFileName(fileName);
QString url = ImgUploaderManager(this).url() + unpackFileName.file;
// load pixmap
QPixmap pixmap;
pixmap.load(fullFileName, "png");
scaleThumbnail(pixmap);
// get file info
auto fileInfo = QFileInfo(fullFileName);
QString lastModified =
fileInfo.lastModified().toString("yyyy-MM-dd\nhh:mm:ss");
auto* line = new UploadLineItem(
this, pixmap, lastModified, url, fullFileName, unpackFileName);
connect(line, &UploadLineItem::requestedDeletion, this, [=]() {
if (ui->historyContainer->count() <= 1) {
setEmptyMessage();
}
delete line;
});
ui->historyContainer->addWidget(line);
}
UploadHistory::~UploadHistory()
{
delete ui;
}
| 2,830
|
C++
|
.cpp
| 85
| 28.070588
| 80
| 0.690136
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,680
|
infowindow.cpp
|
flameshot-org_flameshot/src/widgets/infowindow.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2021-2022 Jeremy Borgman & Contributors
#include "infowindow.h"
#include "./ui_infowindow.h"
#include "src/core/flameshotdaemon.h"
#include "src/core/qguiappcurrentscreen.h"
#include "src/utils/globalvalues.h"
#include <QKeyEvent>
#include <QScreen>
InfoWindow::InfoWindow(QWidget* parent)
: QWidget(parent)
, ui(new Ui::InfoWindow)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
ui->IconSVG->setPixmap(QPixmap(GlobalValues::iconPath()));
ui->VersionDetails->setText(GlobalValues::versionInfo());
ui->OperatingSystemDetails->setText(generateKernelString());
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
QRect position = frameGeometry();
QScreen* screen = QGuiAppCurrentScreen().currentScreen();
position.moveCenter(screen->availableGeometry().center());
move(position.topLeft());
#endif
show();
}
InfoWindow::~InfoWindow()
{
delete ui;
}
void InfoWindow::keyPressEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_Escape) {
close();
}
}
QString generateKernelString()
{
QString kernelVersion =
QSysInfo::kernelType() + ": " + QSysInfo::kernelVersion() + "\n" +
QSysInfo::productType() + ": " + QSysInfo::productVersion();
return kernelVersion;
}
void InfoWindow::on_CopyInfoButton_clicked()
{
FlameshotDaemon::copyToClipboard(GlobalValues::versionInfo() + "\n" +
generateKernelString());
}
| 1,511
|
C++
|
.cpp
| 48
| 27.6875
| 73
| 0.704264
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,681
|
notificationwidget.cpp
|
flameshot-org_flameshot/src/widgets/notificationwidget.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "notificationwidget.h"
#include <QFrame>
#include <QIcon>
#include <QLabel>
#include <QPropertyAnimation>
#include <QTimer>
#include <QVBoxLayout>
NotificationWidget::NotificationWidget(QWidget* parent)
: QWidget(parent)
{
m_timer = new QTimer(this);
m_timer->setSingleShot(true);
m_timer->setInterval(7000);
connect(m_timer, &QTimer::timeout, this, &NotificationWidget::animatedHide);
m_content = new QFrame();
m_layout = new QVBoxLayout();
m_label = new QLabel(m_content);
m_label->hide();
m_showAnimation = new QPropertyAnimation(m_content, "geometry", this);
m_showAnimation->setDuration(300);
m_hideAnimation = new QPropertyAnimation(m_content, "geometry", this);
m_hideAnimation->setDuration(300);
connect(
m_hideAnimation, &QPropertyAnimation::finished, m_label, &QLabel::hide);
auto* mainLayout = new QVBoxLayout();
setLayout(mainLayout);
mainLayout->addWidget(m_content);
m_layout->addWidget(m_label, 0, Qt::AlignHCenter);
m_content->setLayout(m_layout);
setFixedHeight(40);
}
void NotificationWidget::showMessage(const QString& msg)
{
m_label->setText(msg);
m_label->show();
animatedShow();
}
void NotificationWidget::animatedShow()
{
m_showAnimation->setStartValue(QRect(0, 0, width(), 0));
m_showAnimation->setEndValue(QRect(0, 0, width(), height()));
m_showAnimation->start();
m_timer->start();
}
void NotificationWidget::animatedHide()
{
m_hideAnimation->setStartValue(QRect(0, 0, width(), height()));
m_hideAnimation->setEndValue(QRect(0, 0, width(), 0));
m_hideAnimation->start();
}
| 1,761
|
C++
|
.cpp
| 52
| 30.269231
| 80
| 0.716726
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,682
|
loadspinner.cpp
|
flameshot-org_flameshot/src/widgets/loadspinner.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "loadspinner.h"
#include <QApplication>
#include <QPaintEvent>
#include <QPainter>
#include <QTimer>
#define OFFSET 5
LoadSpinner::LoadSpinner(QWidget* parent)
: QWidget(parent)
, m_span(0)
, m_growing(true)
{
setAttribute(Qt::WA_TranslucentBackground);
const int size = QApplication::fontMetrics().height() * 8;
setFixedSize(size, size);
updateFrame();
// init timer
m_timer = new QTimer(this);
connect(m_timer, &QTimer::timeout, this, &LoadSpinner::rotate);
m_timer->setInterval(30);
}
void LoadSpinner::setColor(const QColor& c)
{
m_color = c;
}
void LoadSpinner::setWidth(int w)
{
setFixedSize(w, w);
updateFrame();
}
void LoadSpinner::setHeight(int h)
{
setFixedSize(h, h);
updateFrame();
}
void LoadSpinner::start()
{
m_timer->start();
}
void LoadSpinner::stop()
{
m_timer->stop();
}
void LoadSpinner::paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
auto pen = QPen(m_color);
pen.setWidth(height() / 10);
painter.setPen(pen);
painter.setOpacity(0.2);
painter.drawArc(m_frame, 0, 5760);
painter.setOpacity(1.0);
painter.drawArc(m_frame, (m_startAngle * 16), (m_span * 16));
}
void LoadSpinner::rotate()
{
const int advance = 3;
const int grow = 8;
if (m_growing) {
m_startAngle = (m_startAngle + advance) % 360;
m_span += grow;
if (m_span > 260) {
m_growing = false;
}
} else {
m_startAngle = (m_startAngle + grow) % 360;
m_span = m_span + advance - grow;
if (m_span < 10) {
m_growing = true;
}
}
update();
}
void LoadSpinner::updateFrame()
{
m_frame =
QRect(OFFSET, OFFSET, width() - OFFSET * 2, height() - OFFSET * 2);
}
| 1,947
|
C++
|
.cpp
| 80
| 20.3875
| 73
| 0.646361
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,683
|
capturelauncher.cpp
|
flameshot-org_flameshot/src/widgets/capturelauncher.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2018 Alejandro Sirgo Rica & Contributors
#include "capturelauncher.h"
#include "./ui_capturelauncher.h"
#include "src/config/cacheutils.h"
#include "src/core/flameshot.h"
#include "src/utils/globalvalues.h"
#include "src/utils/screengrabber.h"
#include "src/utils/screenshotsaver.h"
#include "src/widgets/imagelabel.h"
#include <QMimeData>
// https://github.com/KDE/spectacle/blob/941c1a517be82bed25d1254ebd735c29b0d2951c/src/Gui/KSWidget.cpp
// https://github.com/KDE/spectacle/blob/941c1a517be82bed25d1254ebd735c29b0d2951c/src/Gui/KSMainWindow.cpp
CaptureLauncher::CaptureLauncher(QDialog* parent)
: QDialog(parent)
, ui(new Ui::CaptureLauncher)
{
qApp->installEventFilter(this); // see eventFilter()
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
setWindowIcon(QIcon(GlobalValues::iconPath()));
bool ok;
ui->imagePreview->setScreenshot(ScreenGrabber().grabEntireDesktop(ok));
ui->imagePreview->setSizePolicy(QSizePolicy::Expanding,
QSizePolicy::Expanding);
ui->captureType->insertItem(
1, tr("Rectangular Region"), CaptureRequest::GRAPHICAL_MODE);
#if defined(Q_OS_MACOS)
// Following to MacOS philosophy (one application cannot be displayed on
// more than one display)
ui->captureType->insertItem(
2, tr("Full Screen (Current Display)"), CaptureRequest::FULLSCREEN_MODE);
#else
ui->captureType->insertItem(
2, tr("Full Screen (All Monitors)"), CaptureRequest::FULLSCREEN_MODE);
#endif
ui->delayTime->setSpecialValueText(tr("No Delay"));
ui->launchButton->setFocus();
// Function to add or remove plural to seconds
connect(ui->delayTime,
static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
this,
[this](int val) {
QString suffix = val == 1 ? tr(" second") : tr(" seconds");
this->ui->delayTime->setSuffix(suffix);
});
connect(ui->launchButton,
&QPushButton::clicked,
this,
&CaptureLauncher::startCapture);
connect(ui->captureType,
QOverload<int>::of(&QComboBox::currentIndexChanged),
this,
[this]() {
auto mode = static_cast<CaptureRequest::CaptureMode>(
ui->captureType->currentData().toInt());
if (mode == CaptureRequest::CaptureMode::GRAPHICAL_MODE) {
ui->sizeLabel->show();
ui->screenshotX->show();
ui->screenshotY->show();
ui->screenshotWidth->show();
ui->screenshotHeight->show();
} else {
ui->sizeLabel->hide();
ui->screenshotX->hide();
ui->screenshotY->hide();
ui->screenshotWidth->hide();
ui->screenshotHeight->hide();
}
});
auto lastRegion = getLastRegion();
ui->screenshotX->setText(QString::number(lastRegion.x()));
ui->screenshotY->setText(QString::number(lastRegion.y()));
ui->screenshotWidth->setText(QString::number(lastRegion.width()));
ui->screenshotHeight->setText(QString::number(lastRegion.height()));
show();
}
// HACK:
// https://github.com/KDE/spectacle/blob/fa1e780b8bf3df3ac36c410b9ece4ace041f401b/src/Gui/KSMainWindow.cpp#L70
void CaptureLauncher::startCapture()
{
ui->launchButton->setEnabled(false);
hide();
auto const additionalDelayToHideUI = 600;
auto const secondsToMilliseconds = 1000;
auto mode = static_cast<CaptureRequest::CaptureMode>(
ui->captureType->currentData().toInt());
CaptureRequest req(mode,
additionalDelayToHideUI +
ui->delayTime->value() * secondsToMilliseconds);
if (mode == CaptureRequest::CaptureMode::GRAPHICAL_MODE) {
req.setInitialSelection(QRect(ui->screenshotX->text().toInt(),
ui->screenshotY->text().toInt(),
ui->screenshotWidth->text().toInt(),
ui->screenshotHeight->text().toInt()));
}
connectCaptureSlots();
Flameshot::instance()->requestCapture(req);
}
void CaptureLauncher::connectCaptureSlots() const
{
connect(Flameshot::instance(),
&Flameshot::captureTaken,
this,
&CaptureLauncher::onCaptureTaken);
connect(Flameshot::instance(),
&Flameshot::captureFailed,
this,
&CaptureLauncher::onCaptureFailed);
}
void CaptureLauncher::disconnectCaptureSlots() const
{
// Hack for MacOS
// for some strange reasons MacOS sends multiple "captureTaken" signals
// (random number, usually from 1 up to 20).
// So now it enables signal on "Capture new screenshot" button and disables
// on first success of fail.
disconnect(Flameshot::instance(),
&Flameshot::captureTaken,
this,
&CaptureLauncher::onCaptureTaken);
disconnect(Flameshot::instance(),
&Flameshot::captureFailed,
this,
&CaptureLauncher::onCaptureFailed);
}
void CaptureLauncher::onCaptureTaken(QPixmap const& screenshot)
{
// MacOS specific, more details in the function disconnectCaptureSlots()
disconnectCaptureSlots();
ui->imagePreview->setScreenshot(screenshot);
show();
auto mode = static_cast<CaptureRequest::CaptureMode>(
ui->captureType->currentData().toInt());
if (mode == CaptureRequest::FULLSCREEN_MODE) {
saveToFilesystemGUI(screenshot);
}
ui->launchButton->setEnabled(true);
}
void CaptureLauncher::onCaptureFailed()
{
// MacOS specific, more details in the function disconnectCaptureSlots()
disconnectCaptureSlots();
show();
ui->launchButton->setEnabled(true);
}
CaptureLauncher::~CaptureLauncher()
{
delete ui;
}
| 6,045
|
C++
|
.cpp
| 150
| 31.946667
| 110
| 0.644414
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,684
|
draggablewidgetmaker.cpp
|
flameshot-org_flameshot/src/widgets/draggablewidgetmaker.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "draggablewidgetmaker.h"
#include <QMouseEvent>
DraggableWidgetMaker::DraggableWidgetMaker(QObject* parent)
: QObject(parent)
{}
void DraggableWidgetMaker::makeDraggable(QWidget* widget)
{
widget->installEventFilter(this);
}
bool DraggableWidgetMaker::eventFilter(QObject* obj, QEvent* event)
{
auto* widget = static_cast<QWidget*>(obj);
// based on https://stackoverflow.com/a/12221360/964478
switch (event->type()) {
case QEvent::MouseButtonPress: {
auto* mouseEvent = static_cast<QMouseEvent*>(event);
m_isPressing = false;
m_isDragging = false;
if (mouseEvent->button() == Qt::LeftButton) {
m_isPressing = true;
m_mousePressPos = mouseEvent->globalPos();
m_mouseMovePos = m_mousePressPos;
}
} break;
case QEvent::MouseMove: {
auto* mouseEvent = static_cast<QMouseEvent*>(event);
if (m_isPressing) {
QPoint widgetPos = widget->mapToGlobal(widget->pos());
QPoint eventPos = mouseEvent->globalPos();
QPoint diff = eventPos - m_mouseMovePos;
QPoint newPos = widgetPos + diff;
widget->move(widget->mapFromGlobal(newPos));
if (!m_isDragging) {
QPoint totalMovedDiff = eventPos - m_mousePressPos;
if (totalMovedDiff.manhattanLength() > 3) {
m_isDragging = true;
}
}
m_mouseMovePos = eventPos;
}
} break;
case QEvent::MouseButtonRelease: {
m_isPressing = false;
if (m_isDragging) {
m_isDragging = false;
event->ignore();
return true;
}
} break;
default:
break;
}
return QObject::eventFilter(obj, event);
}
| 2,074
|
C++
|
.cpp
| 56
| 26.303571
| 72
| 0.569008
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,685
|
sidepanelwidget.cpp
|
flameshot-org_flameshot/src/widgets/panel/sidepanelwidget.cpp
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#include "sidepanelwidget.h"
#include "colorgrabwidget.h"
#include "src/core/qguiappcurrentscreen.h"
#include "src/utils/colorutils.h"
#include "src/utils/pathinfo.h"
#include "utilitypanel.h"
#include <QApplication>
#include <QCheckBox>
#include <QKeyEvent>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QShortcut>
#include <QSlider>
#include <QVBoxLayout>
#if defined(Q_OS_MACOS)
#include <QScreen>
#endif
SidePanelWidget::SidePanelWidget(QPixmap* p, QWidget* parent)
: QWidget(parent)
, m_layout(new QVBoxLayout(this))
, m_pixmap(p)
{
if (parent != nullptr) {
parent->installEventFilter(this);
}
auto* colorLayout = new QGridLayout();
// Create Active Tool Size
auto* toolSizeHBox = new QHBoxLayout();
auto* activeToolSizeText = new QLabel(tr("Active tool size: "));
m_toolSizeSpin = new QSpinBox(this);
m_toolSizeSpin->setRange(1, maxToolSize);
m_toolSizeSpin->setSingleStep(1);
m_toolSizeSpin->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
toolSizeHBox->addWidget(activeToolSizeText);
toolSizeHBox->addWidget(m_toolSizeSpin);
m_toolSizeSlider = new QSlider(Qt::Horizontal);
m_toolSizeSlider->setRange(1, maxToolSize);
m_toolSizeSlider->setValue(m_toolSize);
m_toolSizeSlider->setMinimumWidth(minSliderWidth);
colorLayout->addLayout(toolSizeHBox, 0, 0);
colorLayout->addWidget(m_toolSizeSlider, 1, 0);
// Create Active Color
auto* colorHBox = new QHBoxLayout();
auto* colorText = new QLabel(tr("Active Color: "));
m_colorLabel = new QLabel();
m_colorLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
colorHBox->addWidget(colorText);
colorHBox->addWidget(m_colorLabel);
colorLayout->addLayout(colorHBox, 2, 0);
m_layout->addLayout(colorLayout);
m_colorWheel = new color_widgets::ColorWheel(this);
m_colorWheel->setColor(m_color);
m_colorHex = new QLineEdit(this);
m_colorHex->setAlignment(Qt::AlignCenter);
QColor background = this->palette().window().color();
bool isDark = ColorUtils::colorIsDark(background);
QString modifier =
isDark ? PathInfo::whiteIconPath() : PathInfo::blackIconPath();
QIcon grabIcon(modifier + "colorize.svg");
m_colorGrabButton = new QPushButton(grabIcon, tr("Grab Color"));
m_layout->addWidget(m_colorGrabButton);
m_layout->addWidget(m_colorWheel);
m_layout->addWidget(m_colorHex);
QHBoxLayout* gridHBoxLayout = new QHBoxLayout(this);
m_gridCheck = new QCheckBox(tr("Display grid"), this);
m_gridSizeSpin = new QSpinBox(this);
m_gridSizeSpin->setRange(5, 50);
m_gridSizeSpin->setSingleStep(5);
m_gridSizeSpin->setValue(10);
m_gridSizeSpin->setDisabled(true);
m_gridSizeSpin->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
gridHBoxLayout->addWidget(m_gridCheck);
gridHBoxLayout->addWidget(m_gridSizeSpin);
m_layout->addLayout(gridHBoxLayout);
// tool size sigslots
connect(m_toolSizeSpin,
static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
this,
&SidePanelWidget::toolSizeChanged);
connect(m_toolSizeSlider,
&QSlider::valueChanged,
this,
&SidePanelWidget::toolSizeChanged);
connect(this,
&SidePanelWidget::toolSizeChanged,
this,
&SidePanelWidget::onToolSizeChanged);
// color hex editor sigslots
connect(m_colorHex, &QLineEdit::editingFinished, this, [=]() {
if (!QColor::isValidColor(m_colorHex->text())) {
m_colorHex->setText(m_color.name(QColor::HexRgb));
} else {
emit colorChanged(m_colorHex->text());
}
});
// color grab button sigslots
connect(m_colorGrabButton,
&QPushButton::pressed,
this,
&SidePanelWidget::startColorGrab);
// color wheel sigslots
// re-emit ColorWheel::colorSelected as SidePanelWidget::colorChanged
connect(m_colorWheel,
&color_widgets::ColorWheel::colorSelected,
this,
&SidePanelWidget::colorChanged);
// Grid feature
connect(m_gridCheck, &QCheckBox::clicked, this, [=](bool b) {
this->m_gridSizeSpin->setEnabled(b);
emit this->displayGridChanged(b);
});
connect(m_gridSizeSpin,
qOverload<int>(&QSpinBox::valueChanged),
this,
&SidePanelWidget::gridSizeChanged);
}
void SidePanelWidget::onColorChanged(const QColor& color)
{
m_color = color;
updateColorNoWheel(color);
m_colorWheel->setColor(color);
}
void SidePanelWidget::onToolSizeChanged(int t)
{
m_toolSize = qBound(0, t, maxToolSize);
m_toolSizeSlider->setValue(m_toolSize);
m_toolSizeSpin->setValue(m_toolSize);
}
void SidePanelWidget::startColorGrab()
{
m_revertColor = m_color;
m_colorGrabber = new ColorGrabWidget(m_pixmap);
connect(m_colorGrabber,
&ColorGrabWidget::colorUpdated,
this,
&SidePanelWidget::onTemporaryColorUpdated);
connect(m_colorGrabber,
&ColorGrabWidget::colorGrabbed,
this,
&SidePanelWidget::onColorGrabFinished);
connect(m_colorGrabber,
&ColorGrabWidget::grabAborted,
this,
&SidePanelWidget::onColorGrabAborted);
emit togglePanel();
m_colorGrabber->startGrabbing();
}
void SidePanelWidget::onColorGrabFinished()
{
finalizeGrab();
m_color = m_colorGrabber->color();
emit colorChanged(m_color);
}
void SidePanelWidget::onColorGrabAborted()
{
finalizeGrab();
// Restore color that was selected before we started grabbing
onColorChanged(m_revertColor);
}
void SidePanelWidget::onTemporaryColorUpdated(const QColor& color)
{
updateColorNoWheel(color);
}
void SidePanelWidget::finalizeGrab()
{
emit togglePanel();
}
void SidePanelWidget::updateColorNoWheel(const QColor& c)
{
m_colorLabel->setStyleSheet(
QStringLiteral("QLabel { background-color : %1; }").arg(c.name()));
m_colorHex->setText(c.name(QColor::HexRgb));
}
bool SidePanelWidget::eventFilter(QObject* obj, QEvent* event)
{
if (event->type() == QEvent::ShortcutOverride) {
// Override Escape shortcut from CaptureWidget
auto* e = static_cast<QKeyEvent*>(event);
if (e->key() == Qt::Key_Escape && m_colorHex->hasFocus()) {
m_colorHex->clearFocus();
e->accept();
return true;
}
} else if (event->type() == QEvent::MouseButtonPress) {
// Clicks outside of the Color Hex editor
m_colorHex->clearFocus();
}
return QWidget::eventFilter(obj, event);
}
void SidePanelWidget::hideEvent(QHideEvent* event)
{
QWidget::hideEvent(event);
m_colorHex->clearFocus();
}
| 6,946
|
C++
|
.cpp
| 197
| 29.654822
| 76
| 0.69003
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| 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.