Datasets:
Dataset Viewer
text
stringlengths 558
4.54k
| prefix
stringlengths 100
2k
| middle
stringlengths 10
500
| suffix
stringlengths 100
2k
| type
stringclasses 2
values |
|---|---|---|---|---|
<|fim_prefix|>P_SPACE && word->word->space() > 0 &&
!word->word->flag(W_FUZZY_NON) && !word->word->flag(W_FUZZY_SP)))) {
if (!word->word->flag(W_BOL) && word->word->space() > 0 && !word->word->flag(W_FUZZY_NON) &&
!word->word->flag(W_FUZZY_SP)) {
/* Write a space to separate from preceding good text */
*ptr++ = ' ';
last_char_was_tilde = false;
}
if (!last_char_was_tilde) {
// Write a reject char.
last_char_was_tilde = true;
*ptr++ = kUNLVReject;
tilde_crunch_written = true;
last_char_was_newline = false;
}
}
} else {
// NORMAL PROCESSING of non tilde crunched words.
tilde_crunch_written = false;
tesseract_->set_unlv_suspects(word);
const char *wordstr = word->best_choice->unichar_string().c_str();
const auto &lengths = word->best_choice->unichar_lengths();
int length = lengths.length();
int i = 0;
int offset = 0;
if (last_char_was_tilde && word->word->space() == 0 && wordstr[offset] == ' ') {
// Prevent adjacent tilde across words - we know that adjacent tildes
// within words have been removed.
// Skip the first character.
offset = lengths[i++];
}
if (i < length && wordstr[offset] != 0) {
if (!last_char_was_newline) {
*ptr++ = ' ';
} else {
last_char_was_newline = false;
}
for (; i < length; offset += lengths[i++]) {
if (wordstr[offset] == ' ' || wordstr[offset] == kTesseractReject) {
*ptr++ = kUNLVReject;
last_char_was_tilde = true;
} else {
if (word->reject_map[i].rejected()) {
*ptr++ = kUNLVSuspect;
}
UNICHAR ch(wordstr + offset, lengths[i]);
int uni_ch = ch.first_uni();
for (int j = 0; kUniChs[j] != 0; ++j) {
if (kUniChs[j] == uni_ch) {
<|fim_suffix|>
break;
}
}
if (uni_ch <= 0xff) {
*ptr++ = static_cast<char>(uni_ch);
last_char_was_tilde = false;
} else {
*ptr++ = kUNLVReject;
last_char_was_tilde = true;
}
}
}
}
}
if (word->word->flag(W_EOL) && !last_char_was_newline) {
/* Add a new line output */
*ptr++ = '\n';
tilde_crunch_written = false;
last_char_was_newline = true;
last_char_was_tilde = false;
}
}
*ptr++ = '\n';
*ptr = '\0';
return result;
}
#ifndef DISABLED_LEGACY_ENGINE
/**
* Detect the orientation of the input image and apparent script (alphabet).
* orient_deg is the detected clockwise rotation of the input image in degrees
* (0, 90, 180, 270)
* orient_conf is the confidence (15.0 is reasonably confident)
* script_name is an ASCII string, the name of the script, e.g. "Latin"
* script_conf is confidence level in the script
* Returns true on success and writes values to each parameter as an output
*/
bool TessBaseAPI::DetectOrientationScript(int *orient_deg, float *orient_conf,
const char **script_name, float *script_conf) {
OSResults osr;
bool osd = DetectOS(&osr);
if (!osd) {
return false;
}
int orient_id = osr.best_result.orientation_id;
int script_id = osr.get_best_script(orient_id);
if (orient_conf) {
*orient_conf = osr.best_result.oconfidence;
}
if (orient_deg) {
*orient_deg = orient_id * 90; // convert quadrant to degrees
}
if (script_name) {
const char *script = osr.unicharset->get_script_from_script_id(script_id);
*script_name = script;
}
if (script_conf) {
*script_conf = osr.best_result.sconfidence;
}
return true;
}
/**
* The recognized text is returned as a char* which is coded
* as UTF8 and must be freed with the delete [] operator.
* page_number is a 0-based page index that<|fim_middle|>uni_ch = kLatinChs[j];
|
P_SPACE && word->word->space() > 0 &&
!word->word->flag(W_FUZZY_NON) && !word->word->flag(W_FUZZY_SP)))) {
if (!word->word->flag(W_BOL) && word->word->space() > 0 && !word->word->flag(W_FUZZY_NON) &&
!word->word->flag(W_FUZZY_SP)) {
/* Write a space to separate from preceding good text */
*ptr++ = ' ';
last_char_was_tilde = false;
}
if (!last_char_was_tilde) {
// Write a reject char.
last_char_was_tilde = true;
*ptr++ = kUNLVReject;
tilde_crunch_written = true;
last_char_was_newline = false;
}
}
} else {
// NORMAL PROCESSING of non tilde crunched words.
tilde_crunch_written = false;
tesseract_->set_unlv_suspects(word);
const char *wordstr = word->best_choice->unichar_string().c_str();
const auto &lengths = word->best_choice->unichar_lengths();
int length = lengths.length();
int i = 0;
int offset = 0;
if (last_char_was_tilde && word->word->space() == 0 && wordstr[offset] == ' ') {
// Prevent adjacent tilde across words - we know that adjacent tildes
// within words have been removed.
// Skip the first character.
offset = lengths[i++];
}
if (i < length && wordstr[offset] != 0) {
if (!last_char_was_newline) {
*ptr++ = ' ';
} else {
last_char_was_newline = false;
}
for (; i < length; offset += lengths[i++]) {
if (wordstr[offset] == ' ' || wordstr[offset] == kTesseractReject) {
*ptr++ = kUNLVReject;
last_char_was_tilde = true;
} else {
if (word->reject_map[i].rejected()) {
*ptr++ = kUNLVSuspect;
}
UNICHAR ch(wordstr + offset, lengths[i]);
int uni_ch = ch.first_uni();
for (int j = 0; kUniChs[j] != 0; ++j) {
if (kUniChs[j] == uni_ch) {
|
uni_ch = kLatinChs[j];
|
break;
}
}
if (uni_ch <= 0xff) {
*ptr++ = static_cast<char>(uni_ch);
last_char_was_tilde = false;
} else {
*ptr++ = kUNLVReject;
last_char_was_tilde = true;
}
}
}
}
}
if (word->word->flag(W_EOL) && !last_char_was_newline) {
/* Add a new line output */
*ptr++ = '\n';
tilde_crunch_written = false;
last_char_was_newline = true;
last_char_was_tilde = false;
}
}
*ptr++ = '\n';
*ptr = '\0';
return result;
}
#ifndef DISABLED_LEGACY_ENGINE
/**
* Detect the orientation of the input image and apparent script (alphabet).
* orient_deg is the detected clockwise rotation of the input image in degrees
* (0, 90, 180, 270)
* orient_conf is the confidence (15.0 is reasonably confident)
* script_name is an ASCII string, the name of the script, e.g. "Latin"
* script_conf is confidence level in the script
* Returns true on success and writes values to each parameter as an output
*/
bool TessBaseAPI::DetectOrientationScript(int *orient_deg, float *orient_conf,
const char **script_name, float *script_conf) {
OSResults osr;
bool osd = DetectOS(&osr);
if (!osd) {
return false;
}
int orient_id = osr.best_result.orientation_id;
int script_id = osr.get_best_script(orient_id);
if (orient_conf) {
*orient_conf = osr.best_result.oconfidence;
}
if (orient_deg) {
*orient_deg = orient_id * 90; // convert quadrant to degrees
}
if (script_name) {
const char *script = osr.unicharset->get_script_from_script_id(script_id);
*script_name = script;
}
if (script_conf) {
*script_conf = osr.best_result.sconfidence;
}
return true;
}
/**
* The recognized text is returned as a char* which is coded
* as UTF8 and must be freed with the delete [] operator.
* page_number is a 0-based page index that
|
ast_based
|
<|fim_prefix|>_key_frame");
undo_redo->add_undo_method(ape, "_animation_update_key_frame");
}
undo_redo->commit_action();
//selection.clear();
}
}
void AnimationBezierTrackEdit::_bezier_track_insert_key_at_anim(const Ref<Animation> &p_anim, int p_track, double p_time, real_t p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle, const Animation::HandleMode p_handle_mode, Animation::HandleSetMode p_handle_set_mode) {
int idx = p_anim->bezier_track_insert_key(p_track, p_time, p_value, p_in_handle, p_out_handle);
p_anim->bezier_track_set_key_handle_mode(p_track, idx, p_handle_mode, p_handle_set_mode);
}
void AnimationBezierTrackEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("_clear_selection"), &AnimationBezierTrackEdit::_clear_selection);
ClassDB::bind_method(D_METHOD("_clear_selection_for_anim"), &AnimationBezierTrackEdit::_clear_selection_for_anim);
ClassDB::bind_method(D_METHOD("_select_at_anim"), &AnimationBezierTrackEdit::_select_at_anim);
ClassDB::bind_method(D_METHOD("_update_hidden_tracks_after"), &AnimationBezierTrackEdit::_update_hidden_tracks_after);
ClassDB::bind_method(D_METHOD("_update_locked_tracks_after"), &AnimationBezierTrackEdit::_update_locked_tracks_after);
ClassDB::bind_method(D_METHOD("_bezier_track_insert_key_at_anim"), &AnimationBezierTrackEdit::_bezier_track_insert_key_at_anim, DEFVAL(Animation::HANDLE_SET_MODE_NONE));
ADD_SIGNAL(MethodInfo("select_key", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "single"), PropertyInfo(Variant::INT, "track")));
ADD_SIGNAL(MethodInfo("deselect_key", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::INT, "track")));
ADD_SIGNAL(MethodInfo("clear_selection"));
ADD_SIGNAL(MethodInfo("timeline_changed", PropertyInfo(Variant::FLOAT, "position"), PropertyInfo(Variant::BOOL, "timeline_only")));
}
AnimationBezierTrackEdit::AnimationBezierTrackEdit() {
panner.instantiate();
panner->set_callbacks(callable_mp(this, &AnimationBezierTrackEdit::_pan_callback), <|fim_suffix|>);
play_position = memnew(Control);
play_position->set_mouse_filter(MOUSE_FILTER_PASS);
add_child(play_position);
play_position->set_anchors_and_offsets_preset(PRESET_FULL_RECT);
play_position->connect(SceneStringName(draw), callable_mp(this, &AnimationBezierTrackEdit::_play_position_draw));
set_focus_mode(FOCUS_CLICK);
set_clip_contents(true);
ED_SHORTCUT("animation_bezier_editor/focus", TTRC("Focus"), Key::F);
ED_SHORTCUT("animation_bezier_editor/select_all_keys", TTRC("Select All Keys"), KeyModifierMask::CMD_OR_CTRL | Key::A);
ED_SHORTCUT("animation_bezier_editor/deselect_all_keys", TTRC("Deselect All Keys"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::A);
menu = memnew(PopupMenu);
add_child(menu);
menu->connect(SceneStringName(id_pressed), callable_mp(this, &AnimationBezierTrackEdit::_menu_selected));
}
<|fim_middle|>callable_mp(this, &AnimationBezierTrackEdit::_zoom_callback)
|
_key_frame");
undo_redo->add_undo_method(ape, "_animation_update_key_frame");
}
undo_redo->commit_action();
//selection.clear();
}
}
void AnimationBezierTrackEdit::_bezier_track_insert_key_at_anim(const Ref<Animation> &p_anim, int p_track, double p_time, real_t p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle, const Animation::HandleMode p_handle_mode, Animation::HandleSetMode p_handle_set_mode) {
int idx = p_anim->bezier_track_insert_key(p_track, p_time, p_value, p_in_handle, p_out_handle);
p_anim->bezier_track_set_key_handle_mode(p_track, idx, p_handle_mode, p_handle_set_mode);
}
void AnimationBezierTrackEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("_clear_selection"), &AnimationBezierTrackEdit::_clear_selection);
ClassDB::bind_method(D_METHOD("_clear_selection_for_anim"), &AnimationBezierTrackEdit::_clear_selection_for_anim);
ClassDB::bind_method(D_METHOD("_select_at_anim"), &AnimationBezierTrackEdit::_select_at_anim);
ClassDB::bind_method(D_METHOD("_update_hidden_tracks_after"), &AnimationBezierTrackEdit::_update_hidden_tracks_after);
ClassDB::bind_method(D_METHOD("_update_locked_tracks_after"), &AnimationBezierTrackEdit::_update_locked_tracks_after);
ClassDB::bind_method(D_METHOD("_bezier_track_insert_key_at_anim"), &AnimationBezierTrackEdit::_bezier_track_insert_key_at_anim, DEFVAL(Animation::HANDLE_SET_MODE_NONE));
ADD_SIGNAL(MethodInfo("select_key", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "single"), PropertyInfo(Variant::INT, "track")));
ADD_SIGNAL(MethodInfo("deselect_key", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::INT, "track")));
ADD_SIGNAL(MethodInfo("clear_selection"));
ADD_SIGNAL(MethodInfo("timeline_changed", PropertyInfo(Variant::FLOAT, "position"), PropertyInfo(Variant::BOOL, "timeline_only")));
}
AnimationBezierTrackEdit::AnimationBezierTrackEdit() {
panner.instantiate();
panner->set_callbacks(callable_mp(this, &AnimationBezierTrackEdit::_pan_callback),
|
callable_mp(this, &AnimationBezierTrackEdit::_zoom_callback)
|
);
play_position = memnew(Control);
play_position->set_mouse_filter(MOUSE_FILTER_PASS);
add_child(play_position);
play_position->set_anchors_and_offsets_preset(PRESET_FULL_RECT);
play_position->connect(SceneStringName(draw), callable_mp(this, &AnimationBezierTrackEdit::_play_position_draw));
set_focus_mode(FOCUS_CLICK);
set_clip_contents(true);
ED_SHORTCUT("animation_bezier_editor/focus", TTRC("Focus"), Key::F);
ED_SHORTCUT("animation_bezier_editor/select_all_keys", TTRC("Select All Keys"), KeyModifierMask::CMD_OR_CTRL | Key::A);
ED_SHORTCUT("animation_bezier_editor/deselect_all_keys", TTRC("Deselect All Keys"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::A);
menu = memnew(PopupMenu);
add_child(menu);
menu->connect(SceneStringName(id_pressed), callable_mp(this, &AnimationBezierTrackEdit::_menu_selected));
}
|
ast_based
|
<|fim_prefix|>s 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. */
/**************************************************************************/
#include "image_compress_astcenc.h"
#include "core/os/os.h"
#include "core/string/print_string.h"
#include <astcenc.h>
#ifdef TOOLS_ENABLED
void _compress_astc(Image *r_img, Image::ASTCFormat p_format) {
const uint64_t start_time = OS::get_singleton()->get_ticks_msec();
if (r_img->is_compressed()) {
return; // Do not compress, already compressed.
}
const Image::Format src_format = r_img->get_format();
const bool is_hdr = src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995;
if (src_format >= Image::FORMAT_RH && src_format <= Image::FORMAT_RGBAH) {
r_img->convert(Image::FORMAT_RGBAH);
} else if (src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995) {
r_img->convert(Image::FORMAT_RGBAF);
} else {
r_img->convert(Image::FORMAT_RGBA8);
}
// Determine encoder output format from our enum.
const astcenc_profile profile = is_hdr ? ASTCENC_PRF_HDR : ASTCENC_PRF_LDR;
Image::Format target_format = Image::FORMAT_MAX;
unsigned int block_x = 4;
unsigned int block_y = 4;
if (p_format == Image::ASTCFormat::ASTC_FORMAT_4x4) {
if (is_hdr) {
target_format = Image::FORMAT_ASTC_4x4_HDR;
} else {
target_format = Image::FORMAT_ASTC_4x4;
}
} else if (p_format == Image::ASTCFormat::ASTC_FORMAT_8x8) {
<|fim_suffix|> else {
target_format = Image::FORMAT_ASTC_8x8;
}
block_x = 8;
block_y = 8;
}
// Compress image data and (if required) mipmaps.
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
int required_width = (width % block_x) != 0 ? width + (block_x - (width % block_x)) : width;
int required_height = (height % block_y) != 0 ? height + (block_y - (height % block_y)) : height;
if (width != required_width || height != required_height) {
// Resize texture to fit block size.
r_img->resize(required_width, required_height);
width = required_width;
height = required_height;
}
print_verbose(vformat("astcenc: Encoding image size %dx%d to format %s%s.", width, height, Image::get_format_name(target_format), has_mipmaps ? ", with mipmaps" : ""));
// Initialize astcenc.
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
astcenc_config config;
config.block_x = block_x;
config.block_y = block_y;
config.profile = profile;
const float quality = ASTCENC_PRE_MEDIUM;
astcenc_error status = astcenc_config_init(profile, block_x, block_y, 1, quality, 0, &config);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Configuration initialization failed: %s.", astcenc_get_error_string(status)));
// Context allocation.
astcenc_context *context;
const unsigned int thread_count = 1; // Godot compresses multiple images each on a thread, which is more efficient for large amount of images imported.
status = astcenc_context_alloc(&config, thread_count, &context);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Context allocation failed: %s.", astcenc_get_error_string(status)));
const int mip_count = has_mipmaps ? Image::get_image_required_mipmaps(width, height, target_format) : 0;
const uint8_t *src_data = r_img->ptr();
f<|fim_middle|>if (is_hdr) {
target_format = Image::FORMAT_ASTC_8x8_HDR;
}
|
s 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. */
/**************************************************************************/
#include "image_compress_astcenc.h"
#include "core/os/os.h"
#include "core/string/print_string.h"
#include <astcenc.h>
#ifdef TOOLS_ENABLED
void _compress_astc(Image *r_img, Image::ASTCFormat p_format) {
const uint64_t start_time = OS::get_singleton()->get_ticks_msec();
if (r_img->is_compressed()) {
return; // Do not compress, already compressed.
}
const Image::Format src_format = r_img->get_format();
const bool is_hdr = src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995;
if (src_format >= Image::FORMAT_RH && src_format <= Image::FORMAT_RGBAH) {
r_img->convert(Image::FORMAT_RGBAH);
} else if (src_format >= Image::FORMAT_RF && src_format <= Image::FORMAT_RGBE9995) {
r_img->convert(Image::FORMAT_RGBAF);
} else {
r_img->convert(Image::FORMAT_RGBA8);
}
// Determine encoder output format from our enum.
const astcenc_profile profile = is_hdr ? ASTCENC_PRF_HDR : ASTCENC_PRF_LDR;
Image::Format target_format = Image::FORMAT_MAX;
unsigned int block_x = 4;
unsigned int block_y = 4;
if (p_format == Image::ASTCFormat::ASTC_FORMAT_4x4) {
if (is_hdr) {
target_format = Image::FORMAT_ASTC_4x4_HDR;
} else {
target_format = Image::FORMAT_ASTC_4x4;
}
} else if (p_format == Image::ASTCFormat::ASTC_FORMAT_8x8) {
|
if (is_hdr) {
target_format = Image::FORMAT_ASTC_8x8_HDR;
}
|
else {
target_format = Image::FORMAT_ASTC_8x8;
}
block_x = 8;
block_y = 8;
}
// Compress image data and (if required) mipmaps.
const bool has_mipmaps = r_img->has_mipmaps();
int width = r_img->get_width();
int height = r_img->get_height();
int required_width = (width % block_x) != 0 ? width + (block_x - (width % block_x)) : width;
int required_height = (height % block_y) != 0 ? height + (block_y - (height % block_y)) : height;
if (width != required_width || height != required_height) {
// Resize texture to fit block size.
r_img->resize(required_width, required_height);
width = required_width;
height = required_height;
}
print_verbose(vformat("astcenc: Encoding image size %dx%d to format %s%s.", width, height, Image::get_format_name(target_format), has_mipmaps ? ", with mipmaps" : ""));
// Initialize astcenc.
const int64_t dest_size = Image::get_image_data_size(width, height, target_format, has_mipmaps);
Vector<uint8_t> dest_data;
dest_data.resize(dest_size);
uint8_t *dest_write = dest_data.ptrw();
astcenc_config config;
config.block_x = block_x;
config.block_y = block_y;
config.profile = profile;
const float quality = ASTCENC_PRE_MEDIUM;
astcenc_error status = astcenc_config_init(profile, block_x, block_y, 1, quality, 0, &config);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Configuration initialization failed: %s.", astcenc_get_error_string(status)));
// Context allocation.
astcenc_context *context;
const unsigned int thread_count = 1; // Godot compresses multiple images each on a thread, which is more efficient for large amount of images imported.
status = astcenc_context_alloc(&config, thread_count, &context);
ERR_FAIL_COND_MSG(status != ASTCENC_SUCCESS,
vformat("astcenc: Context allocation failed: %s.", astcenc_get_error_string(status)));
const int mip_count = has_mipmaps ? Image::get_image_required_mipmaps(width, height, target_format) : 0;
const uint8_t *src_data = r_img->ptr();
f
|
ast_based
|
<|fim_prefix|>
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_group_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_member_of(ae->node, (accesskit_node_id)p_group_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_in_page_link_target(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_in_page_link_target(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_error_message(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_error_message(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_live(const RID &p_id, DisplayServer::AccessibilityLiveMode p_live) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);<|fim_suffix|> } break;
}
}
void AccessibilityDriverAccessKit::accessibility_update_add_action(const RID &p_id, DisplayServer::AccessibilityAction p_action, const Callable &p_callable) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
ae->actions[_accessibility_action(p_action)] = p_callable;
accesskit_node_add_action(ae->node, _accessibility_action(p_action));
}
void AccessibilityDriverAccessKit::accessibility_update_add_custom_action(const RID &p_id, int p_action_id, const String &p_action_description) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_action_description.is_empty()) {
accesskit_custom_action ca = accesskit_custom_action_new(p_action_id, p_action_description.utf8().ptr());
accesskit_node_push_custom_action(ae->node, ca);
} else {
String cs_name = vformat("Custom Action %d", p_action_id);
accesskit_custom_action ca = accesskit_custom_action_new(p_action_id, cs_name.utf8().ptr());
accesskit_node_push_custom_action(ae->node, ca);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_row_count(const RID &p_id, int p_count) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_count(ae->node, p_count);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_column_count(const RID &p_id, int p_count) {<|fim_middle|>
switch (p_live) {
case DisplayServer::AccessibilityLiveMode::LIVE_OFF: {
accesskit_node_set_live(ae->node, ACCESSKIT_LIVE_OFF);
} break;
case DisplayServer::AccessibilityLiveMode::LIVE_POLITE: {
accesskit_node_set_live(ae->node, ACCESSKIT_LIVE_POLITE);
} break;
case DisplayServer::AccessibilityLiveMode::LIVE_ASSERTIVE: {
accesskit_node_set_live(ae->node, ACCESSKIT_LIVE_ASSERTIVE);
|
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_group_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_member_of(ae->node, (accesskit_node_id)p_group_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_in_page_link_target(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_in_page_link_target(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_error_message(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_error_message(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_live(const RID &p_id, DisplayServer::AccessibilityLiveMode p_live) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
|
switch (p_live) {
case DisplayServer::AccessibilityLiveMode::LIVE_OFF: {
accesskit_node_set_live(ae->node, ACCESSKIT_LIVE_OFF);
} break;
case DisplayServer::AccessibilityLiveMode::LIVE_POLITE: {
accesskit_node_set_live(ae->node, ACCESSKIT_LIVE_POLITE);
} break;
case DisplayServer::AccessibilityLiveMode::LIVE_ASSERTIVE: {
accesskit_node_set_live(ae->node, ACCESSKIT_LIVE_ASSERTIVE);
|
} break;
}
}
void AccessibilityDriverAccessKit::accessibility_update_add_action(const RID &p_id, DisplayServer::AccessibilityAction p_action, const Callable &p_callable) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
ae->actions[_accessibility_action(p_action)] = p_callable;
accesskit_node_add_action(ae->node, _accessibility_action(p_action));
}
void AccessibilityDriverAccessKit::accessibility_update_add_custom_action(const RID &p_id, int p_action_id, const String &p_action_description) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
if (!p_action_description.is_empty()) {
accesskit_custom_action ca = accesskit_custom_action_new(p_action_id, p_action_description.utf8().ptr());
accesskit_node_push_custom_action(ae->node, ca);
} else {
String cs_name = vformat("Custom Action %d", p_action_id);
accesskit_custom_action ca = accesskit_custom_action_new(p_action_id, cs_name.utf8().ptr());
accesskit_node_push_custom_action(ae->node, ca);
}
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_row_count(const RID &p_id, int p_count) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
_ensure_node(p_id, ae);
accesskit_node_set_row_count(ae->node, p_count);
}
void AccessibilityDriverAccessKit::accessibility_update_set_table_column_count(const RID &p_id, int p_count) {
|
random
|
<|fim_prefix|>>GetScaledYResolution(), rect_left_, rect_top_,
rect_width_, rect_height_);
}
/**
* Get a reading-order iterator to the results of LayoutAnalysis and/or
* Recognize. The returned iterator must be deleted after use.
* WARNING! This class points to data held within the TessBaseAPI class, and
* therefore can only be used while the TessBaseAPI class still exists and
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
ResultIterator *TessBaseAPI::GetIterator() {
if (tesseract_ == nullptr || page_res_ == nullptr) {
return nullptr;
}
return ResultIterator::StartOfParagraph(LTRResultIterator(
page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(),
rect_left_, rect_top_, rect_width_, rect_height_));
}
/**
* Get a mutable iterator to the results of LayoutAnalysis and/or Recognize.
* The returned iterator must be deleted after use.
* WARNING! This class points to data held within the TessBaseAPI class, and
* therefore can only be used while the TessBaseAPI class still exists and
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
MutableIterator *TessBaseAPI::GetMutableIterator() {
if (tesseract_ == nullptr || page_res_ == nullptr) {
return nullptr;
}
return new MutableIterator(page_res_, tesseract_, thresholder_->GetScaleFactor(),
thresholder_->GetScaledYResolution(), rect_left_, rect_top_,
rect_width_, rect_height_);
}
/** Make a text string from the internal data structures. */
char *TessBaseAPI::GetUTF8Text() {
if (tesseract_ == nullptr || (!recognition_done_ && Recognize(nullptr) < 0)) {
return nullptr;
}
std::string text("");
const std::unique_ptr</*non-const*/ ResultIterator> it(GetIterator());
do {
<|fim_suffix|>
auto block_type = it->BlockType();
switch (block_type) {
case PT_FLOWING_IMAGE:
case PT_HEADING_IMAGE:
case PT_PULLOUT_IMAGE:
case PT_HORZ_LINE:
case PT_VERT_LINE:
// Ignore images and lines for text output.
continue;
case PT_NOISE:
tprintf("TODO: Please report image which triggers the noise case.\n");
ASSERT_HOST(false);
default:
break;
}
const std::unique_ptr<const char[]> para_text(it->GetUTF8Text(RIL_PARA));
text += para_text.get();
} while (it->Next(RIL_PARA));
return copy_string(text);
}
static void AddBoxToTSV(const PageIterator *it, PageIteratorLevel level, std::string &text) {
int left, top, right, bottom;
it->BoundingBox(level, &left, &top, &right, &bottom);
text += "\t" + std::to_string(left);
text += "\t" + std::to_string(top);
text += "\t" + std::to_string(right - left);
text += "\t" + std::to_string(bottom - top);
}
/**
* Make a TSV-formatted string from the internal data structures.
* page_number is 0-based but will appear in the output as 1-based.
* Returned string must be freed with the delete [] operator.
*/
char *TessBaseAPI::GetTSVText(int page_number) {
if (tesseract_ == nullptr || (page_res_ == nullptr && Recognize(nullptr) < 0)) {
return nullptr;
}
#if !defined(NDEBUG)
int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
#endif
int page_id = page_number + 1; // we use 1-based page numbers.
int page_num = page_id;
int block_num = 0;
int par_num = 0;
int line_num = 0;
int word_num = 0;
std::string tsv_str;
tsv_str += "1\t" + std::to_string(page_num); // level 1 - page
tsv_str += "\t" + std::to_string(block_num);
tsv_str += "\t" + std::to_string(par_num);
tsv_str += "\t" + std::to_string(line_num);
tsv_str += "\t" + std::to_string(word_num);
tsv_str += "\t" + std::to_string(rect_left_);
tsv_str += "\t" + std::to_string(rect_top_);
tsv_str += "\t" + std::to_string(rect_width_);
tsv_str +=<|fim_middle|>if (it->Empty(RIL_PARA)) {
continue;
}
|
>GetScaledYResolution(), rect_left_, rect_top_,
rect_width_, rect_height_);
}
/**
* Get a reading-order iterator to the results of LayoutAnalysis and/or
* Recognize. The returned iterator must be deleted after use.
* WARNING! This class points to data held within the TessBaseAPI class, and
* therefore can only be used while the TessBaseAPI class still exists and
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
ResultIterator *TessBaseAPI::GetIterator() {
if (tesseract_ == nullptr || page_res_ == nullptr) {
return nullptr;
}
return ResultIterator::StartOfParagraph(LTRResultIterator(
page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(),
rect_left_, rect_top_, rect_width_, rect_height_));
}
/**
* Get a mutable iterator to the results of LayoutAnalysis and/or Recognize.
* The returned iterator must be deleted after use.
* WARNING! This class points to data held within the TessBaseAPI class, and
* therefore can only be used while the TessBaseAPI class still exists and
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
MutableIterator *TessBaseAPI::GetMutableIterator() {
if (tesseract_ == nullptr || page_res_ == nullptr) {
return nullptr;
}
return new MutableIterator(page_res_, tesseract_, thresholder_->GetScaleFactor(),
thresholder_->GetScaledYResolution(), rect_left_, rect_top_,
rect_width_, rect_height_);
}
/** Make a text string from the internal data structures. */
char *TessBaseAPI::GetUTF8Text() {
if (tesseract_ == nullptr || (!recognition_done_ && Recognize(nullptr) < 0)) {
return nullptr;
}
std::string text("");
const std::unique_ptr</*non-const*/ ResultIterator> it(GetIterator());
do {
|
if (it->Empty(RIL_PARA)) {
continue;
}
|
auto block_type = it->BlockType();
switch (block_type) {
case PT_FLOWING_IMAGE:
case PT_HEADING_IMAGE:
case PT_PULLOUT_IMAGE:
case PT_HORZ_LINE:
case PT_VERT_LINE:
// Ignore images and lines for text output.
continue;
case PT_NOISE:
tprintf("TODO: Please report image which triggers the noise case.\n");
ASSERT_HOST(false);
default:
break;
}
const std::unique_ptr<const char[]> para_text(it->GetUTF8Text(RIL_PARA));
text += para_text.get();
} while (it->Next(RIL_PARA));
return copy_string(text);
}
static void AddBoxToTSV(const PageIterator *it, PageIteratorLevel level, std::string &text) {
int left, top, right, bottom;
it->BoundingBox(level, &left, &top, &right, &bottom);
text += "\t" + std::to_string(left);
text += "\t" + std::to_string(top);
text += "\t" + std::to_string(right - left);
text += "\t" + std::to_string(bottom - top);
}
/**
* Make a TSV-formatted string from the internal data structures.
* page_number is 0-based but will appear in the output as 1-based.
* Returned string must be freed with the delete [] operator.
*/
char *TessBaseAPI::GetTSVText(int page_number) {
if (tesseract_ == nullptr || (page_res_ == nullptr && Recognize(nullptr) < 0)) {
return nullptr;
}
#if !defined(NDEBUG)
int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
#endif
int page_id = page_number + 1; // we use 1-based page numbers.
int page_num = page_id;
int block_num = 0;
int par_num = 0;
int line_num = 0;
int word_num = 0;
std::string tsv_str;
tsv_str += "1\t" + std::to_string(page_num); // level 1 - page
tsv_str += "\t" + std::to_string(block_num);
tsv_str += "\t" + std::to_string(par_num);
tsv_str += "\t" + std::to_string(line_num);
tsv_str += "\t" + std::to_string(word_num);
tsv_str += "\t" + std::to_string(rect_left_);
tsv_str += "\t" + std::to_string(rect_top_);
tsv_str += "\t" + std::to_string(rect_width_);
tsv_str +=
|
ast_based
|
<|fim_prefix|> (fgets(pagename, sizeof(pagename), flist) == nullptr) {
break;
}
} else {
if (page >= lines.size()) {
break;
}
snprintf(pagename, sizeof(pagename), "%s", lines[page].c_str());
}
chomp_string(pagename);
Pix *pix = pixRead(pagename);
if (pix == nullptr) {
tprintf("Image file %s cannot be read!\n", pagename);
return false;
}
tprintf("Page %u : %s\n", page, pagename);
bool r = ProcessPage(pix, page, pagename, retry_config, timeout_millisec, renderer);
pixDestroy(&pix);
if (!r) {
return false;
}
if (tessedit_page_number >= 0) {
break;
}
++page;
}
// Finish producing output
if (renderer && !renderer->EndDocument()) {
return false;
}
return true;
}
bool TessBaseAPI::ProcessPagesMultipageTiff(const l_uint8 *data, size_t size, const char *filename,
const char *retry_config, int timeout_millisec,
TessResultRenderer *renderer,
int tessedit_page_number) {
Pix *pix = nullptr;
int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
size_t offset = 0;
for (;; ++page) {
if (tessedit_page_number >= 0) {
page = tessedit_page_number;
pix = (data) ? pixReadMemTiff(data, size, page) : pixReadTiff(filename, page);
} else {
pix = (data) ? pixReadMemFromMultipageTiff(data, size, &offset)
: pixReadFromMultipageTiff(filename, &offset);
}
if (pix == nullptr) {
break;
}
if (offset || page > 0) {
// Only print page number for multipage TIFF file.
tprintf("Page %d\n", page + 1);
}
auto page_string = std::to_string(page);
SetVariable("applybox_page", page_string.c_str());
bool r = ProcessPage(pix, page, filename, retry_config, timeout_millisec, renderer);
pixDestroy(&pix);
if (!r) {
return false;
}
<|fim_suffix|>
if (!offset) {
break;
}
}
return true;
}
// Master ProcessPages calls ProcessPagesInternal and then does any post-
// processing required due to being in a training mode.
bool TessBaseAPI::ProcessPages(const char *filename, const char *retry_config, int timeout_millisec,
TessResultRenderer *renderer) {
bool result = ProcessPagesInternal(filename, retry_config, timeout_millisec, renderer);
#ifndef DISABLED_LEGACY_ENGINE
if (result) {
if (tesseract_->tessedit_train_from_boxes && !tesseract_->WriteTRFile(output_file_.c_str())) {
tprintf("Write of TR file failed: %s\n", output_file_.c_str());
return false;
}
}
#endif // ndef DISABLED_LEGACY_ENGINE
return result;
}
#ifdef HAVE_LIBCURL
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size = size * nmemb;
auto *buf = reinterpret_cast<std::string *>(userp);
buf->append(reinterpret_cast<const char *>(contents), size);
return size;
}
#endif
// In the ideal scenario, Tesseract will start working on data as soon
// as it can. For example, if you stream a filelist through stdin, we
// should start the OCR process as soon as the first filename is
// available. This is particularly useful when hooking Tesseract up to
// slow hardware such as a book scanning machine.
//
// Unfortunately there are tradeoffs. You can't seek on stdin. That
// makes automatic detection of datatype (TIFF? filelist? PNG?)
// impractical. So we support a command line flag to explicitly
// identify the scenario that really matters: filelists on
// stdin. We'll still do our best if the user likes pipes.
bool TessBaseAPI::ProcessPagesInternal(const char *filename, const char *retry_config,
int timeout_millisec, TessResultRenderer *renderer) {
bool stdInput = !strcmp(filename, "stdin") || !strcmp(filename, "-");
if (stdInput) {
#ifdef WIN32
if (_setmode(_fileno(stdin), _O_BINARY) ==<|fim_middle|>if (tessedit_page_number >= 0) {
break;
}
|
(fgets(pagename, sizeof(pagename), flist) == nullptr) {
break;
}
} else {
if (page >= lines.size()) {
break;
}
snprintf(pagename, sizeof(pagename), "%s", lines[page].c_str());
}
chomp_string(pagename);
Pix *pix = pixRead(pagename);
if (pix == nullptr) {
tprintf("Image file %s cannot be read!\n", pagename);
return false;
}
tprintf("Page %u : %s\n", page, pagename);
bool r = ProcessPage(pix, page, pagename, retry_config, timeout_millisec, renderer);
pixDestroy(&pix);
if (!r) {
return false;
}
if (tessedit_page_number >= 0) {
break;
}
++page;
}
// Finish producing output
if (renderer && !renderer->EndDocument()) {
return false;
}
return true;
}
bool TessBaseAPI::ProcessPagesMultipageTiff(const l_uint8 *data, size_t size, const char *filename,
const char *retry_config, int timeout_millisec,
TessResultRenderer *renderer,
int tessedit_page_number) {
Pix *pix = nullptr;
int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
size_t offset = 0;
for (;; ++page) {
if (tessedit_page_number >= 0) {
page = tessedit_page_number;
pix = (data) ? pixReadMemTiff(data, size, page) : pixReadTiff(filename, page);
} else {
pix = (data) ? pixReadMemFromMultipageTiff(data, size, &offset)
: pixReadFromMultipageTiff(filename, &offset);
}
if (pix == nullptr) {
break;
}
if (offset || page > 0) {
// Only print page number for multipage TIFF file.
tprintf("Page %d\n", page + 1);
}
auto page_string = std::to_string(page);
SetVariable("applybox_page", page_string.c_str());
bool r = ProcessPage(pix, page, filename, retry_config, timeout_millisec, renderer);
pixDestroy(&pix);
if (!r) {
return false;
}
|
if (tessedit_page_number >= 0) {
break;
}
|
if (!offset) {
break;
}
}
return true;
}
// Master ProcessPages calls ProcessPagesInternal and then does any post-
// processing required due to being in a training mode.
bool TessBaseAPI::ProcessPages(const char *filename, const char *retry_config, int timeout_millisec,
TessResultRenderer *renderer) {
bool result = ProcessPagesInternal(filename, retry_config, timeout_millisec, renderer);
#ifndef DISABLED_LEGACY_ENGINE
if (result) {
if (tesseract_->tessedit_train_from_boxes && !tesseract_->WriteTRFile(output_file_.c_str())) {
tprintf("Write of TR file failed: %s\n", output_file_.c_str());
return false;
}
}
#endif // ndef DISABLED_LEGACY_ENGINE
return result;
}
#ifdef HAVE_LIBCURL
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size = size * nmemb;
auto *buf = reinterpret_cast<std::string *>(userp);
buf->append(reinterpret_cast<const char *>(contents), size);
return size;
}
#endif
// In the ideal scenario, Tesseract will start working on data as soon
// as it can. For example, if you stream a filelist through stdin, we
// should start the OCR process as soon as the first filename is
// available. This is particularly useful when hooking Tesseract up to
// slow hardware such as a book scanning machine.
//
// Unfortunately there are tradeoffs. You can't seek on stdin. That
// makes automatic detection of datatype (TIFF? filelist? PNG?)
// impractical. So we support a command line flag to explicitly
// identify the scenario that really matters: filelists on
// stdin. We'll still do our best if the user likes pipes.
bool TessBaseAPI::ProcessPagesInternal(const char *filename, const char *retry_config,
int timeout_millisec, TessResultRenderer *renderer) {
bool stdInput = !strcmp(filename, "stdin") || !strcmp(filename, "-");
if (stdInput) {
#ifdef WIN32
if (_setmode(_fileno(stdin), _O_BINARY) ==
|
ast_based
|
<|fim_prefix|> text_buf.draw(get_canvas_item(), string_pos, cc);
float icon_start_height = vofs + rect.size.y / 2.0;
Rect2 remove_rect = Rect2(remove_hpos, icon_start_height - remove->get_height() / 2.0, remove->get_width(), remove->get_height());
if (read_only) {
draw_texture(remove, remove_rect.position, dc);
} else {
draw_texture(remove, remove_rect.position);
}
Rect2 lock_rect = Rect2(lock_hpos, icon_start_height - lock->get_height() / 2.0, lock->get_width(), lock->get_height());
if (locked_tracks.has(current_track)) {
draw_texture(lock, lock_rect.position);
} else {
draw_texture(unlock, lock_rect.position);
}
Rect2 visible_rect = Rect2(visibility_hpos, icon_start_height - visibility_visible->get_height() / 2.0, visibility_visible->get_width(), visibility_visible->get_height());
if (hidden_tracks.has(current_track)) {
draw_texture(visibility_hidden, visible_rect.position);
} else {
draw_texture(visibility_visible, visible_rect.position);
}
Rect2 solo_rect = Rect2(solo_hpos, icon_start_height - solo->get_height() / 2.0, solo->get_width(), solo->get_height());
draw_texture(solo, solo_rect.position);
RBMap<int, Rect2> track_icons;
track_icons[REMOVE_ICON] = remove_rect;
track_icons[LOCK_ICON] = lock_rect;
track_icons[VISIBILITY_ICON] = visible_rect;
track_icons[SOLO_ICON] = solo_rect;
subtrack_icons[current_track] = track_icons;
vofs += text_buf.get_size().y + v_separation;
track_v_scroll_max += text_buf.get_size().y + v_separation;
}
}
const Color accent = get_theme_color(SNAME("accent_color"), EditorStringName(Editor));
// Guides.
{
float min_left_scale = font->get_height(font_size) + v_separation;
float scale = (min_left_scale * 2) * timeline_v_zoom;
float step = Math::pow(10.0, Math::round(Math::log(scale / 5.0) / Math::log(10.0))) * 5.0;
scale = Math::snapped(scale, step);<|fim_suffix|> scale += step;
}
bool first = true;
int prev_iv = 0;
for (int i = font->get_height(font_size); i < get_size().height; i++) {
float ofs = get_size().height / 2.0 - i;
ofs *= timeline_v_zoom;
ofs += timeline_v_scroll;
int iv = int(ofs / scale);
if (ofs < 0) {
iv -= 1;
}
if (!first && iv != prev_iv) {
Color lc = h_line_color;
lc.a *= 0.5;
draw_line(Point2(limit, i), Point2(right_limit, i), lc, Math::round(EDSCALE));
Color c = color;
c.a *= 0.5;
draw_string(font, Point2(limit + 8, i - 2), TS->format_number(rtos(Math::snapped((iv + 1) * scale, step))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, c);
}
first = false;
prev_iv = iv;
}
}
// Draw other curves.
{
float scale = timeline->get_zoom_scale();
Ref<Texture2D> point = get_editor_theme_icon(SNAME("KeyValue"));
for (const KeyValue<int, Color> &E : subtrack_colors) {
if (hidden_tracks.has(E.key)) {
continue;
}
_draw_track(E.key, E.value);
for (int i = 0; i < animation->track_get_key_count(E.key); i++) {
float offset = animation->track_get_key_time(E.key, i);
float value = animation->bezier_track_get_key_value(E.key, i);
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
if (pos.x >= limit && pos.x <= right_limit) {
draw_texture(point, pos - point->get_size() / 2.0, E.value);
}
}
}
if (track_count > 0 && !hidden_tracks.has(selected_track)) {
// Draw edited curve.
_draw_track(selected_track, selected_track_color);
}
}
const bool draw_selection_handles = selection.size() > 1;
LocalVector<Point2> selected_pos;
// Draw editor handles.
{
edit_points.clear();
float scale = timeline->get_zoom_scale();
for (int i = 0; i < track_count; ++i) {
bool draw_track = _is_track_curves_displayed(i) && !locked_tracks.has(i);<|fim_middle|>
while (scale / timeline_v_zoom < min_left_scale * 2) {
|
text_buf.draw(get_canvas_item(), string_pos, cc);
float icon_start_height = vofs + rect.size.y / 2.0;
Rect2 remove_rect = Rect2(remove_hpos, icon_start_height - remove->get_height() / 2.0, remove->get_width(), remove->get_height());
if (read_only) {
draw_texture(remove, remove_rect.position, dc);
} else {
draw_texture(remove, remove_rect.position);
}
Rect2 lock_rect = Rect2(lock_hpos, icon_start_height - lock->get_height() / 2.0, lock->get_width(), lock->get_height());
if (locked_tracks.has(current_track)) {
draw_texture(lock, lock_rect.position);
} else {
draw_texture(unlock, lock_rect.position);
}
Rect2 visible_rect = Rect2(visibility_hpos, icon_start_height - visibility_visible->get_height() / 2.0, visibility_visible->get_width(), visibility_visible->get_height());
if (hidden_tracks.has(current_track)) {
draw_texture(visibility_hidden, visible_rect.position);
} else {
draw_texture(visibility_visible, visible_rect.position);
}
Rect2 solo_rect = Rect2(solo_hpos, icon_start_height - solo->get_height() / 2.0, solo->get_width(), solo->get_height());
draw_texture(solo, solo_rect.position);
RBMap<int, Rect2> track_icons;
track_icons[REMOVE_ICON] = remove_rect;
track_icons[LOCK_ICON] = lock_rect;
track_icons[VISIBILITY_ICON] = visible_rect;
track_icons[SOLO_ICON] = solo_rect;
subtrack_icons[current_track] = track_icons;
vofs += text_buf.get_size().y + v_separation;
track_v_scroll_max += text_buf.get_size().y + v_separation;
}
}
const Color accent = get_theme_color(SNAME("accent_color"), EditorStringName(Editor));
// Guides.
{
float min_left_scale = font->get_height(font_size) + v_separation;
float scale = (min_left_scale * 2) * timeline_v_zoom;
float step = Math::pow(10.0, Math::round(Math::log(scale / 5.0) / Math::log(10.0))) * 5.0;
scale = Math::snapped(scale, step);
|
while (scale / timeline_v_zoom < min_left_scale * 2) {
|
scale += step;
}
bool first = true;
int prev_iv = 0;
for (int i = font->get_height(font_size); i < get_size().height; i++) {
float ofs = get_size().height / 2.0 - i;
ofs *= timeline_v_zoom;
ofs += timeline_v_scroll;
int iv = int(ofs / scale);
if (ofs < 0) {
iv -= 1;
}
if (!first && iv != prev_iv) {
Color lc = h_line_color;
lc.a *= 0.5;
draw_line(Point2(limit, i), Point2(right_limit, i), lc, Math::round(EDSCALE));
Color c = color;
c.a *= 0.5;
draw_string(font, Point2(limit + 8, i - 2), TS->format_number(rtos(Math::snapped((iv + 1) * scale, step))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, c);
}
first = false;
prev_iv = iv;
}
}
// Draw other curves.
{
float scale = timeline->get_zoom_scale();
Ref<Texture2D> point = get_editor_theme_icon(SNAME("KeyValue"));
for (const KeyValue<int, Color> &E : subtrack_colors) {
if (hidden_tracks.has(E.key)) {
continue;
}
_draw_track(E.key, E.value);
for (int i = 0; i < animation->track_get_key_count(E.key); i++) {
float offset = animation->track_get_key_time(E.key, i);
float value = animation->bezier_track_get_key_value(E.key, i);
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
if (pos.x >= limit && pos.x <= right_limit) {
draw_texture(point, pos - point->get_size() / 2.0, E.value);
}
}
}
if (track_count > 0 && !hidden_tracks.has(selected_track)) {
// Draw edited curve.
_draw_track(selected_track, selected_track_color);
}
}
const bool draw_selection_handles = selection.size() > 1;
LocalVector<Point2> selected_pos;
// Draw editor handles.
{
edit_points.clear();
float scale = timeline->get_zoom_scale();
for (int i = 0; i < track_count; ++i) {
bool draw_track = _is_track_curves_displayed(i) && !locked_tracks.has(i);
|
random
|
<|fim_prefix|>R_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_related_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_push_to_radio_group(ae->node, (accesskit_node_id)p_related_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_active_descendant(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_active_descendant(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_next_on_line(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_next_on_line(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_previous_on_line(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = <|fim_suffix|>;
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_previous_on_line(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_member_of(const RID &p_id, const RID &p_group_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_group_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_member_of(ae->node, (accesskit_node_id)p_group_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_in_page_link_target(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_in_page_link_target(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_error_message(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_n<|fim_middle|>rid_owner.get_or_null(p_id)
|
R_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_related_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_push_to_radio_group(ae->node, (accesskit_node_id)p_related_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_active_descendant(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_active_descendant(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_next_on_line(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_next_on_line(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_previous_on_line(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae =
|
rid_owner.get_or_null(p_id)
|
;
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_previous_on_line(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_member_of(const RID &p_id, const RID &p_group_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_group_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_member_of(ae->node, (accesskit_node_id)p_group_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_in_page_link_target(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_node(p_id, ae);
accesskit_node_set_in_page_link_target(ae->node, (accesskit_node_id)p_other_id.get_id());
}
void AccessibilityDriverAccessKit::accessibility_update_set_error_message(const RID &p_id, const RID &p_other_id) {
ERR_FAIL_COND_MSG(!in_accessibility_update, "Accessibility updates are only allowed inside the NOTIFICATION_ACCESSIBILITY_UPDATE notification.");
AccessibilityElement *ae = rid_owner.get_or_null(p_id);
ERR_FAIL_NULL(ae);
AccessibilityElement *other_ae = rid_owner.get_or_null(p_other_id);
ERR_FAIL_NULL(other_ae);
ERR_FAIL_COND(other_ae->window_id != ae->window_id);
_ensure_n
|
ast_based
|
<|fim_prefix|>
#include "android_keys_utils.h"
#include "display_server_android.h"
void AndroidInputHandler::process_joy_event(AndroidInputHandler::JoypadEvent p_event) {
switch (p_event.type) {
case JOY_EVENT_BUTTON:
Input::get_singleton()->joy_button(p_event.device, (JoyButton)p_event.index, p_event.pressed);
break;
case JOY_EVENT_AXIS:
Input::get_singleton()->joy_axis(p_event.device, (JoyAxis)p_event.index, p_event.value);
break;
case JOY_EVENT_HAT:
Input::get_singleton()->joy_hat(p_event.device, p_event.hat);
break;
default:
return;
}
}
void AndroidInputHandler::_set_key_modifier_state(Ref<InputEventWithModifiers> ev, Key p_keycode) {
if (p_keycode != Key::SHIFT) {
ev->set_shift_pressed(shift_mem);
}
if (p_keycode != Key::ALT) {
ev->set_alt_pressed(alt_mem);
}
if (p_keycode != Key::META) {
ev->set_meta_pressed(meta_mem);
}
if (p_keycode != Key::CTRL) {
ev->set_ctrl_pressed(control_mem);
}
}
void AndroidInputHandler::process_key_event(int p_physical_keycode, int p_unicode, int p_key_label, bool p_pressed, bool p_echo) {
static char32_t prev_wc = 0;
char32_t unicode = p_unicode;
if ((p_unicode & 0xfffffc00) == 0xd800) {
if (prev_wc != 0) {
ERR_PRINT("invalid utf16 surrogate input");
}
prev_wc = unicode;
return; // Skip surrogate.
} else if ((unicode & 0xfffffc00) == 0xdc00) {
if (prev_wc == 0) {
ERR_PRINT("invalid utf16 surrogate input");
return; // Skip invalid surrogate.
}
unicode = (prev_wc << 10UL) + unicode - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
prev_wc = 0;
} else {
prev_wc = 0;
}
Ref<InputEventKey> ev;
ev.instantiate();
Key physical_keycode = godot_code_from_android_code(p_physical_keycode);
Key keycode;
if (unicode == '\b') { // 0x08
keycode = Key::BACKSPACE;
} else if (unicode == '\t') { // 0x09
keycode = Key::TAB;
} else if (unicode == '\n') { // 0x0A
keycode = Key::ENTER;
} else if (unicode == 0x1B) {
keycode = Key::ESCAPE;
} else if (unicode == 0x1F) {<|fim_suffix|> } else {
keycode = fix_keycode(unicode, physical_keycode);
}
switch (physical_keycode) {
case Key::SHIFT: {
shift_mem = p_pressed;
} break;
case Key::ALT: {
alt_mem = p_pressed;
} break;
case Key::CTRL: {
control_mem = p_pressed;
} break;
case Key::META: {
meta_mem = p_pressed;
} break;
default:
break;
}
ev->set_keycode(keycode);
ev->set_physical_keycode(physical_keycode);
ev->set_key_label(fix_key_label(p_key_label, keycode));
ev->set_unicode(fix_unicode(unicode));
ev->set_location(godot_location_from_android_code(p_physical_keycode));
ev->set_pressed(p_pressed);
ev->set_echo(p_echo);
_set_key_modifier_state(ev, keycode);
if (p_physical_keycode == AKEYCODE_BACK && p_pressed) {
if (DisplayServerAndroid *dsa = Object::cast_to<DisplayServerAndroid>(DisplayServer::get_singleton())) {
dsa->send_window_event(DisplayServer::WINDOW_EVENT_GO_BACK_REQUEST, true);
}
}
Input::get_singleton()->parse_input_event(ev);
}
void AndroidInputHandler::_cancel_all_touch() {
_parse_all_touch(false, true);
touch.clear();
}
void AndroidInputHandler::_parse_all_touch(bool p_pressed, bool p_canceled, bool p_double_tap) {
if (touch.size()) {
//end all if exist
for (int i = 0; i < touch.size(); i++) {
Ref<InputEventScreenTouch> ev;
ev.instantiate();
ev->set_index(touch[i].id);
ev->set_pressed(p_pressed);
ev->set_canceled(p_canceled);
ev->set_position(touch[i].pos);
ev->set_double_tap(p_double_tap);
Input::get_singleton()->parse_input_event(ev);
}
}
}
void AndroidInputHandler::_release_all_touch() {
_parse_all_touch(false, false);
touch.clear();
}
void AndroidInputHandler::process_touch_event(int p_event, int p_pointer, const Vector<TouchPos> &p_points, bool p_double_tap) {
switch (p_event) {
case AMOTION_EVENT_ACTION_DOWN: { //gesture begin
// Release any remaining touches or mouse event
_release_mouse_event_info();
_release_all_touch();
touch.resize(p_points.size());<|fim_middle|> keycode = Key::KEY_DELETE;
|
#include "android_keys_utils.h"
#include "display_server_android.h"
void AndroidInputHandler::process_joy_event(AndroidInputHandler::JoypadEvent p_event) {
switch (p_event.type) {
case JOY_EVENT_BUTTON:
Input::get_singleton()->joy_button(p_event.device, (JoyButton)p_event.index, p_event.pressed);
break;
case JOY_EVENT_AXIS:
Input::get_singleton()->joy_axis(p_event.device, (JoyAxis)p_event.index, p_event.value);
break;
case JOY_EVENT_HAT:
Input::get_singleton()->joy_hat(p_event.device, p_event.hat);
break;
default:
return;
}
}
void AndroidInputHandler::_set_key_modifier_state(Ref<InputEventWithModifiers> ev, Key p_keycode) {
if (p_keycode != Key::SHIFT) {
ev->set_shift_pressed(shift_mem);
}
if (p_keycode != Key::ALT) {
ev->set_alt_pressed(alt_mem);
}
if (p_keycode != Key::META) {
ev->set_meta_pressed(meta_mem);
}
if (p_keycode != Key::CTRL) {
ev->set_ctrl_pressed(control_mem);
}
}
void AndroidInputHandler::process_key_event(int p_physical_keycode, int p_unicode, int p_key_label, bool p_pressed, bool p_echo) {
static char32_t prev_wc = 0;
char32_t unicode = p_unicode;
if ((p_unicode & 0xfffffc00) == 0xd800) {
if (prev_wc != 0) {
ERR_PRINT("invalid utf16 surrogate input");
}
prev_wc = unicode;
return; // Skip surrogate.
} else if ((unicode & 0xfffffc00) == 0xdc00) {
if (prev_wc == 0) {
ERR_PRINT("invalid utf16 surrogate input");
return; // Skip invalid surrogate.
}
unicode = (prev_wc << 10UL) + unicode - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
prev_wc = 0;
} else {
prev_wc = 0;
}
Ref<InputEventKey> ev;
ev.instantiate();
Key physical_keycode = godot_code_from_android_code(p_physical_keycode);
Key keycode;
if (unicode == '\b') { // 0x08
keycode = Key::BACKSPACE;
} else if (unicode == '\t') { // 0x09
keycode = Key::TAB;
} else if (unicode == '\n') { // 0x0A
keycode = Key::ENTER;
} else if (unicode == 0x1B) {
keycode = Key::ESCAPE;
} else if (unicode == 0x1F) {
|
keycode = Key::KEY_DELETE;
|
} else {
keycode = fix_keycode(unicode, physical_keycode);
}
switch (physical_keycode) {
case Key::SHIFT: {
shift_mem = p_pressed;
} break;
case Key::ALT: {
alt_mem = p_pressed;
} break;
case Key::CTRL: {
control_mem = p_pressed;
} break;
case Key::META: {
meta_mem = p_pressed;
} break;
default:
break;
}
ev->set_keycode(keycode);
ev->set_physical_keycode(physical_keycode);
ev->set_key_label(fix_key_label(p_key_label, keycode));
ev->set_unicode(fix_unicode(unicode));
ev->set_location(godot_location_from_android_code(p_physical_keycode));
ev->set_pressed(p_pressed);
ev->set_echo(p_echo);
_set_key_modifier_state(ev, keycode);
if (p_physical_keycode == AKEYCODE_BACK && p_pressed) {
if (DisplayServerAndroid *dsa = Object::cast_to<DisplayServerAndroid>(DisplayServer::get_singleton())) {
dsa->send_window_event(DisplayServer::WINDOW_EVENT_GO_BACK_REQUEST, true);
}
}
Input::get_singleton()->parse_input_event(ev);
}
void AndroidInputHandler::_cancel_all_touch() {
_parse_all_touch(false, true);
touch.clear();
}
void AndroidInputHandler::_parse_all_touch(bool p_pressed, bool p_canceled, bool p_double_tap) {
if (touch.size()) {
//end all if exist
for (int i = 0; i < touch.size(); i++) {
Ref<InputEventScreenTouch> ev;
ev.instantiate();
ev->set_index(touch[i].id);
ev->set_pressed(p_pressed);
ev->set_canceled(p_canceled);
ev->set_position(touch[i].pos);
ev->set_double_tap(p_double_tap);
Input::get_singleton()->parse_input_event(ev);
}
}
}
void AndroidInputHandler::_release_all_touch() {
_parse_all_touch(false, false);
touch.clear();
}
void AndroidInputHandler::process_touch_event(int p_event, int p_pointer, const Vector<TouchPos> &p_points, bool p_double_tap) {
switch (p_event) {
case AMOTION_EVENT_ACTION_DOWN: { //gesture begin
// Release any remaining touches or mouse event
_release_mouse_event_info();
_release_all_touch();
touch.resize(p_points.size());
|
random
|
<|fim_prefix|>
for (int i = 0; i < track_count; ++i) {
if (animation->track_get_type(i) != Animation::TrackType::TYPE_BEZIER || hidden_tracks.has(i) || locked_tracks.has(i)) {
continue;
}
float track_h = animation->bezier_track_interpolate(i, time);
float track_height = _bezier_h_to_pixel(track_h);
if (std::abs(mb->get_position().y - track_height) < 10) {
set_animation_and_track(animation, i, read_only);
break;
}
}
animation->set_length(animation_length);
}
box_selecting_attempt = false;
box_selecting = false;
queue_redraw();
}
if (moving_selection_attempt && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) {
if (!read_only) {
if (moving_selection && (std::abs(moving_selection_offset.x) > CMP_EPSILON || std::abs(moving_selection_offset.y) > CMP_EPSILON)) {
// Commit it.
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
undo_redo->create_action(TTR("Move Bezier Points"));
List<AnimMoveRestore> to_restore;
List<Animation::HandleMode> to_restore_handle_modes;
// 1 - Remove the keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->get().first, E->get().second);
}
// 2 - Remove overlapped keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t newtime = animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x;
int idx = animation->track_find_key(E->get().first, newtime, Animation::FIND_MODE_APPROX);
if (idx == -1) {
continue;
}
if (selection.has(IntPair(E->get().first, idx))) {
continue; // Already in selection, don't save.
}
undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_time", E->get().first, newtime);
AnimMoveRestore amr;
amr.key = animation->track_get_key_value(E->get().first, idx);<|fim_suffix|> amr.time = newtime;
to_restore.push_back(amr);
to_restore_handle_modes.push_back(animation->bezier_track_get_key_handle_mode(E->get().first, idx));
}
// 3 - Move the keys (re-insert them).
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t newpos = animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x;
Array key = animation->track_get_key_value(E->get().first, E->get().second);
real_t h = key[0];
h += moving_selection_offset.y;
key[0] = h;
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(E->get().first, E->get().second);
Animation::HandleSetMode handle_set_mode = Animation::HANDLE_SET_MODE_NONE;
if (moving_inserted_key) {
handle_mode = (Animation::HandleMode)editor->bezier_key_mode->get_selected_id();
handle_set_mode = Animation::HANDLE_SET_MODE_AUTO;
}
undo_redo->add_do_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
E->get().first,
newpos,
key[0],
Vector2(key[1], key[2]),
Vector2(key[3], key[4]),
handle_mode,
handle_set_mode);
}
// 4 - (undo) Remove inserted keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t newpos = animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x;
undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", E->get().first, newpos);
}
// 5 - (undo) Reinsert keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t oldpos = animation->track_get_key_time(E->get().first, E->get().second);
Array key = animation->track_get_key_value(E->get().first, E->get().second);
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
E->get().first,
oldpos,
key[0],<|fim_middle|> amr.track = E->get().first;
|
for (int i = 0; i < track_count; ++i) {
if (animation->track_get_type(i) != Animation::TrackType::TYPE_BEZIER || hidden_tracks.has(i) || locked_tracks.has(i)) {
continue;
}
float track_h = animation->bezier_track_interpolate(i, time);
float track_height = _bezier_h_to_pixel(track_h);
if (std::abs(mb->get_position().y - track_height) < 10) {
set_animation_and_track(animation, i, read_only);
break;
}
}
animation->set_length(animation_length);
}
box_selecting_attempt = false;
box_selecting = false;
queue_redraw();
}
if (moving_selection_attempt && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) {
if (!read_only) {
if (moving_selection && (std::abs(moving_selection_offset.x) > CMP_EPSILON || std::abs(moving_selection_offset.y) > CMP_EPSILON)) {
// Commit it.
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
undo_redo->create_action(TTR("Move Bezier Points"));
List<AnimMoveRestore> to_restore;
List<Animation::HandleMode> to_restore_handle_modes;
// 1 - Remove the keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->get().first, E->get().second);
}
// 2 - Remove overlapped keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t newtime = animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x;
int idx = animation->track_find_key(E->get().first, newtime, Animation::FIND_MODE_APPROX);
if (idx == -1) {
continue;
}
if (selection.has(IntPair(E->get().first, idx))) {
continue; // Already in selection, don't save.
}
undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_time", E->get().first, newtime);
AnimMoveRestore amr;
amr.key = animation->track_get_key_value(E->get().first, idx);
|
amr.track = E->get().first;
|
amr.time = newtime;
to_restore.push_back(amr);
to_restore_handle_modes.push_back(animation->bezier_track_get_key_handle_mode(E->get().first, idx));
}
// 3 - Move the keys (re-insert them).
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t newpos = animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x;
Array key = animation->track_get_key_value(E->get().first, E->get().second);
real_t h = key[0];
h += moving_selection_offset.y;
key[0] = h;
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(E->get().first, E->get().second);
Animation::HandleSetMode handle_set_mode = Animation::HANDLE_SET_MODE_NONE;
if (moving_inserted_key) {
handle_mode = (Animation::HandleMode)editor->bezier_key_mode->get_selected_id();
handle_set_mode = Animation::HANDLE_SET_MODE_AUTO;
}
undo_redo->add_do_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
E->get().first,
newpos,
key[0],
Vector2(key[1], key[2]),
Vector2(key[3], key[4]),
handle_mode,
handle_set_mode);
}
// 4 - (undo) Remove inserted keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t newpos = animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x;
undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", E->get().first, newpos);
}
// 5 - (undo) Reinsert keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t oldpos = animation->track_get_key_time(E->get().first, E->get().second);
Array key = animation->track_get_key_value(E->get().first, E->get().second);
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
E->get().first,
oldpos,
key[0],
|
random
|
<|fim_prefix|> = [curl, &curlcode](const char *function) {
fprintf(stderr, "Error, %s failed with error %s\n", function, curl_easy_strerror(curlcode));
curl_easy_cleanup(curl);
return false;
};
curlcode = curl_easy_setopt(curl, CURLOPT_URL, filename);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
curlcode = curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
// Follow HTTP, HTTPS, FTP and FTPS redirects.
curlcode = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
// Allow no more than 8 redirections to prevent endless loops.
curlcode = curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 8);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
int timeout = curl_timeout;
if (timeout > 0) {
curlcode = curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
curlcode = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
}
std::string cookiefile = curl_cookiefile;
if (!cookiefile.empty()) {
curlcode = curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookiefile.c_str());
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
}
curlcode = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
curlcode = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
curlcode = curl_easy_setopt(curl, CURLOPT_USERAGENT, "Tesseract OCR");
if (curlcode != CURLE_OK) <|fim_suffix|>
curlcode = curl_easy_perform(curl);
if (curlcode != CURLE_OK) {
return error("curl_easy_perform");
}
curl_easy_cleanup(curl);
data = reinterpret_cast<const l_uint8 *>(buf.data());
}
#else
fprintf(stderr, "Error, this tesseract has no URL support\n");
return false;
#endif
} else {
// Check whether the input file can be read.
if (FILE *file = fopen(filename, "rb")) {
fclose(file);
} else {
fprintf(stderr, "Error, cannot read input file %s: %s\n", filename, strerror(errno));
return false;
}
}
// Here is our autodetection
int format;
int r =
(data != nullptr) ? findFileFormatBuffer(data, &format) : findFileFormat(filename, &format);
// Maybe we have a filelist
if (r != 0 || format == IFF_UNKNOWN) {
std::string s;
if (data != nullptr) {
s = buf.c_str();
} else {
std::ifstream t(filename);
std::string u((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
s = u.c_str();
}
return ProcessPagesFileList(nullptr, &s, retry_config, timeout_millisec, renderer,
tesseract_->tessedit_page_number);
}
// Maybe we have a TIFF which is potentially multipage
bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS || format == IFF_TIFF_RLE ||
format == IFF_TIFF_G3 || format == IFF_TIFF_G4 || format == IFF_TIFF_LZW ||
#if LIBLEPT_MAJOR_VERSION > 1 || LIBLEPT_MINOR_VERSION > 76
format == IFF_TIFF_JPEG ||
#endif
format == IFF_TIFF_ZIP);
// Fail early if we can, before producing any output
Pix *pix = nullptr;
if (!tiff) {
pix = (data != nullptr) ? pixReadMem(data, buf.size()) : pixRead(filename);
if (pix == nullptr) {
return false;
}
}
// Begin the output
if (renderer && !renderer->BeginDocument(document_title.c_str())) {
pixDestroy(&pix);
return false;
}
// Produce output
r = (tiff) ? Pro<|fim_middle|>{
return error("curl_easy_setopt");
}
|
= [curl, &curlcode](const char *function) {
fprintf(stderr, "Error, %s failed with error %s\n", function, curl_easy_strerror(curlcode));
curl_easy_cleanup(curl);
return false;
};
curlcode = curl_easy_setopt(curl, CURLOPT_URL, filename);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
curlcode = curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
// Follow HTTP, HTTPS, FTP and FTPS redirects.
curlcode = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
// Allow no more than 8 redirections to prevent endless loops.
curlcode = curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 8);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
int timeout = curl_timeout;
if (timeout > 0) {
curlcode = curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
curlcode = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
}
std::string cookiefile = curl_cookiefile;
if (!cookiefile.empty()) {
curlcode = curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookiefile.c_str());
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
}
curlcode = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
curlcode = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf);
if (curlcode != CURLE_OK) {
return error("curl_easy_setopt");
}
curlcode = curl_easy_setopt(curl, CURLOPT_USERAGENT, "Tesseract OCR");
if (curlcode != CURLE_OK)
|
{
return error("curl_easy_setopt");
}
|
curlcode = curl_easy_perform(curl);
if (curlcode != CURLE_OK) {
return error("curl_easy_perform");
}
curl_easy_cleanup(curl);
data = reinterpret_cast<const l_uint8 *>(buf.data());
}
#else
fprintf(stderr, "Error, this tesseract has no URL support\n");
return false;
#endif
} else {
// Check whether the input file can be read.
if (FILE *file = fopen(filename, "rb")) {
fclose(file);
} else {
fprintf(stderr, "Error, cannot read input file %s: %s\n", filename, strerror(errno));
return false;
}
}
// Here is our autodetection
int format;
int r =
(data != nullptr) ? findFileFormatBuffer(data, &format) : findFileFormat(filename, &format);
// Maybe we have a filelist
if (r != 0 || format == IFF_UNKNOWN) {
std::string s;
if (data != nullptr) {
s = buf.c_str();
} else {
std::ifstream t(filename);
std::string u((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
s = u.c_str();
}
return ProcessPagesFileList(nullptr, &s, retry_config, timeout_millisec, renderer,
tesseract_->tessedit_page_number);
}
// Maybe we have a TIFF which is potentially multipage
bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS || format == IFF_TIFF_RLE ||
format == IFF_TIFF_G3 || format == IFF_TIFF_G4 || format == IFF_TIFF_LZW ||
#if LIBLEPT_MAJOR_VERSION > 1 || LIBLEPT_MINOR_VERSION > 76
format == IFF_TIFF_JPEG ||
#endif
format == IFF_TIFF_ZIP);
// Fail early if we can, before producing any output
Pix *pix = nullptr;
if (!tiff) {
pix = (data != nullptr) ? pixReadMem(data, buf.size()) : pixRead(filename);
if (pix == nullptr) {
return false;
}
}
// Begin the output
if (renderer && !renderer->BeginDocument(document_title.c_str())) {
pixDestroy(&pix);
return false;
}
// Produce output
r = (tiff) ? Pro
|
ast_based
|
<|fim_prefix|> */
/* 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. */
/**************************************************************************/
#include "android_input_handler.h"
#include "android_keys_utils.h"
#include "display_server_android.h"
void AndroidInputHandler::process_joy_event(AndroidInputHandler::JoypadEvent p_event) {
switch (p_event.type) {
case JOY_EVENT_BUTTON:
Input::get_singleton()->joy_button(p_event.device, (JoyButton)p_event.index, p_event.pressed);
break;
case JOY_EVENT_AXIS:
Input::get_singleton()->joy_axis(p_event.device, (JoyAxis)p_event.index, p_event.value);
break;
case JOY_EVENT_HAT:
Input::get_singleton()->joy_hat(p_event.device, p_event.hat);
break;
default:
return;
}
}
void AndroidInputHandler::_set_key_modifier_state(Ref<InputEventWithModifiers> ev, Key p_keycode) {
if (p_keycode != Key::SHIFT) {
ev->set_shift_pressed(shift_mem);
}
if (p_keycode != Key::ALT) {
ev->set_alt_pressed(alt_mem);
}
<|fim_suffix|>
}
void AndroidInputHandler::process_key_event(int p_physical_keycode, int p_unicode, int p_key_label, bool p_pressed, bool p_echo) {
static char32_t prev_wc = 0;
char32_t unicode = p_unicode;
if ((p_unicode & 0xfffffc00) == 0xd800) {
if (prev_wc != 0) {
ERR_PRINT("invalid utf16 surrogate input");
}
prev_wc = unicode;
return; // Skip surrogate.
} else if ((unicode & 0xfffffc00) == 0xdc00) {
if (prev_wc == 0) {
ERR_PRINT("invalid utf16 surrogate input");
return; // Skip invalid surrogate.
}
unicode = (prev_wc << 10UL) + unicode - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
prev_wc = 0;
} else {
prev_wc = 0;
}
Ref<InputEventKey> ev;
ev.instantiate();
Key physical_keycode = godot_code_from_android_code(p_physical_keycode);
Key keycode;
if (unicode == '\b') { // 0x08
keycode = Key::BACKSPACE;
} else if (unicode == '\t') { // 0x09
keycode = Key::TAB;
} else if (unicode == '\n') { // 0x0A
keycode = Key::ENTER;
} else if (unicode == 0x1B) {
keycode = Key::ESCAPE;
} else if (unicode == 0x1F) {
keycode = Key::KEY_DELETE;
} else {
keycode = fix_keycode(unicode, physical_keycode);
}
switch (physical_keycode) {
case Key::SHIFT: {
shift_mem = p_pressed;
} break;
case Key::ALT: {
alt_mem = p_pressed;
} break;
case Key::CTRL: {
control_mem = p_pressed;
} break;
case Key::META: {
meta_mem = p_pressed;
} break;
default:
break;
}
ev->set_keycode(keycode);
ev->set_physical_keycode(physical_keycode);
ev->set_key_label(fix_key_label(p_key_label, keycode));
ev->set_unicode(fix_unicode(unicode));
ev->set_location(godot_location_from_android_code(p_physical_keycode));
ev->set_pressed(p_pressed);
ev->set_echo(p_echo);
_set_key_modifier_state(ev, keycode);
if (p_physical_keycode == AKEYCODE_BACK && p_pressed) {
if (DisplayServerAndroid *dsa = Object::cast_to<DisplayServerAndroid>(DisplayServer::get_singleton())) {
dsa->send_window_event(DisplayServer::WINDOW_EVENT_GO_BACK_REQUEST, true)<|fim_middle|>if (p_keycode != Key::META) {
ev->set_meta_pressed(meta_mem);
}
if (p_keycode != Key::CTRL) {
ev->set_ctrl_pressed(control_mem);
}
|
*/
/* 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. */
/**************************************************************************/
#include "android_input_handler.h"
#include "android_keys_utils.h"
#include "display_server_android.h"
void AndroidInputHandler::process_joy_event(AndroidInputHandler::JoypadEvent p_event) {
switch (p_event.type) {
case JOY_EVENT_BUTTON:
Input::get_singleton()->joy_button(p_event.device, (JoyButton)p_event.index, p_event.pressed);
break;
case JOY_EVENT_AXIS:
Input::get_singleton()->joy_axis(p_event.device, (JoyAxis)p_event.index, p_event.value);
break;
case JOY_EVENT_HAT:
Input::get_singleton()->joy_hat(p_event.device, p_event.hat);
break;
default:
return;
}
}
void AndroidInputHandler::_set_key_modifier_state(Ref<InputEventWithModifiers> ev, Key p_keycode) {
if (p_keycode != Key::SHIFT) {
ev->set_shift_pressed(shift_mem);
}
if (p_keycode != Key::ALT) {
ev->set_alt_pressed(alt_mem);
}
|
if (p_keycode != Key::META) {
ev->set_meta_pressed(meta_mem);
}
if (p_keycode != Key::CTRL) {
ev->set_ctrl_pressed(control_mem);
}
|
}
void AndroidInputHandler::process_key_event(int p_physical_keycode, int p_unicode, int p_key_label, bool p_pressed, bool p_echo) {
static char32_t prev_wc = 0;
char32_t unicode = p_unicode;
if ((p_unicode & 0xfffffc00) == 0xd800) {
if (prev_wc != 0) {
ERR_PRINT("invalid utf16 surrogate input");
}
prev_wc = unicode;
return; // Skip surrogate.
} else if ((unicode & 0xfffffc00) == 0xdc00) {
if (prev_wc == 0) {
ERR_PRINT("invalid utf16 surrogate input");
return; // Skip invalid surrogate.
}
unicode = (prev_wc << 10UL) + unicode - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
prev_wc = 0;
} else {
prev_wc = 0;
}
Ref<InputEventKey> ev;
ev.instantiate();
Key physical_keycode = godot_code_from_android_code(p_physical_keycode);
Key keycode;
if (unicode == '\b') { // 0x08
keycode = Key::BACKSPACE;
} else if (unicode == '\t') { // 0x09
keycode = Key::TAB;
} else if (unicode == '\n') { // 0x0A
keycode = Key::ENTER;
} else if (unicode == 0x1B) {
keycode = Key::ESCAPE;
} else if (unicode == 0x1F) {
keycode = Key::KEY_DELETE;
} else {
keycode = fix_keycode(unicode, physical_keycode);
}
switch (physical_keycode) {
case Key::SHIFT: {
shift_mem = p_pressed;
} break;
case Key::ALT: {
alt_mem = p_pressed;
} break;
case Key::CTRL: {
control_mem = p_pressed;
} break;
case Key::META: {
meta_mem = p_pressed;
} break;
default:
break;
}
ev->set_keycode(keycode);
ev->set_physical_keycode(physical_keycode);
ev->set_key_label(fix_key_label(p_key_label, keycode));
ev->set_unicode(fix_unicode(unicode));
ev->set_location(godot_location_from_android_code(p_physical_keycode));
ev->set_pressed(p_pressed);
ev->set_echo(p_echo);
_set_key_modifier_state(ev, keycode);
if (p_physical_keycode == AKEYCODE_BACK && p_pressed) {
if (DisplayServerAndroid *dsa = Object::cast_to<DisplayServerAndroid>(DisplayServer::get_singleton())) {
dsa->send_window_event(DisplayServer::WINDOW_EVENT_GO_BACK_REQUEST, true)
|
ast_based
|
<|fim_prefix|> ggml_context * ctx = ctx_for_buft(buft);
if (!ctx) {
LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
return false;
}
ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hparams.n_embd);
tensors.push_back(tensor);
}
// allocate tensors / buffers and zero
bufs.reserve(ctx_map.size());
for (auto it : ctx_map) {
ggml_backend_buffer_type_t buft = it.first;
ggml_context * ctx = it.second;
ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
if (!buf) {
LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
return false;
}
ggml_backend_buffer_clear(buf, 0);
bufs.emplace_back(buf);
}
return true;
}
bool llama_adapter_cvec::apply(
const llama_model & model,
const float * data,
size_t len,
int32_t n_embd,
int32_t il_start,
int32_t il_end) {
const auto & hparams = model.hparams;
if (data == nullptr) {
// disable the current control vector (but leave allocated for later)
layer_start = -1;
layer_end = -1;
return true;
}
if (n_embd != (int) hparams.n_embd) {
LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
return false;
}
if (tensors.empty()) {
if (!init(model)) {
return false;
}
}
layer_start = il_start;
layer_end = il_end;
for (size_t il = 1; il < hparams.n_layer; il++) {
assert(tensors[il] != nullptr);
const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
if (off + n_embd <= len) {
ggml_backend_tensor_set(tensors[il], data + off, 0, n_embd * ggml_element_size(tensors[il]));
}<|fim_suffix|>
// lora
llama_adapter_lora_weight * llama_adapter_lora::get_weight(ggml_tensor * w) {
const std::string name(w->name);
const auto pos = ab_map.find(name);
if (pos != ab_map.end()) {
return &pos->second;
}
return nullptr;
}
static void llama_adapter_lora_init_impl(llama_model & model, const char * path_lora, llama_adapter_lora & adapter) {
LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora);
ggml_context * ctx_init;
gguf_init_params meta_gguf_params = {
/* .no_alloc = */ true,
/* .ctx = */ &ctx_init,
};
gguf_context_ptr ctx_gguf { gguf_init_from_file(path_lora, meta_gguf_params) };
if (!ctx_gguf) {
throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora));
}
ggml_context_ptr ctx { ctx_init };
// check metadata
{
const gguf_context * gguf_ctx = ctx_gguf.get();
LLAMA_LOG_INFO("%s: Dumping metadata keys/values.\n", __func__);
// get metadata as string
for (int i = 0; i < gguf_get_n_kv(gguf_ctx); i++) {
gguf_type type = gguf_get_kv_type(gguf_ctx, i);
const std::string type_name =
type == GGUF_TYPE_ARRAY
? format("%s[%s,%zu]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(gguf_ctx, i)), gguf_get_arr_n(gguf_ctx, i))
: gguf_type_name(type);
const char * name = gguf_get_key(gguf_ctx, i);
const std::string value = gguf_kv_to_str(gguf_ctx, i);
if (type != GGUF_TYPE_ARRAY) {
adapter.gguf_kv.emplace(name, value);
}
const size_t MAX_VALUE_LEN = 40;
std::string print_value = value.size() > MAX_VALUE_LEN ? format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str()) : value;
replace_all(print_value, "\n", "\\n");
<|fim_middle|> }
return true;
}
|
ggml_context * ctx = ctx_for_buft(buft);
if (!ctx) {
LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
return false;
}
ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hparams.n_embd);
tensors.push_back(tensor);
}
// allocate tensors / buffers and zero
bufs.reserve(ctx_map.size());
for (auto it : ctx_map) {
ggml_backend_buffer_type_t buft = it.first;
ggml_context * ctx = it.second;
ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
if (!buf) {
LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
return false;
}
ggml_backend_buffer_clear(buf, 0);
bufs.emplace_back(buf);
}
return true;
}
bool llama_adapter_cvec::apply(
const llama_model & model,
const float * data,
size_t len,
int32_t n_embd,
int32_t il_start,
int32_t il_end) {
const auto & hparams = model.hparams;
if (data == nullptr) {
// disable the current control vector (but leave allocated for later)
layer_start = -1;
layer_end = -1;
return true;
}
if (n_embd != (int) hparams.n_embd) {
LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
return false;
}
if (tensors.empty()) {
if (!init(model)) {
return false;
}
}
layer_start = il_start;
layer_end = il_end;
for (size_t il = 1; il < hparams.n_layer; il++) {
assert(tensors[il] != nullptr);
const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
if (off + n_embd <= len) {
ggml_backend_tensor_set(tensors[il], data + off, 0, n_embd * ggml_element_size(tensors[il]));
}
|
}
return true;
}
|
// lora
llama_adapter_lora_weight * llama_adapter_lora::get_weight(ggml_tensor * w) {
const std::string name(w->name);
const auto pos = ab_map.find(name);
if (pos != ab_map.end()) {
return &pos->second;
}
return nullptr;
}
static void llama_adapter_lora_init_impl(llama_model & model, const char * path_lora, llama_adapter_lora & adapter) {
LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora);
ggml_context * ctx_init;
gguf_init_params meta_gguf_params = {
/* .no_alloc = */ true,
/* .ctx = */ &ctx_init,
};
gguf_context_ptr ctx_gguf { gguf_init_from_file(path_lora, meta_gguf_params) };
if (!ctx_gguf) {
throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora));
}
ggml_context_ptr ctx { ctx_init };
// check metadata
{
const gguf_context * gguf_ctx = ctx_gguf.get();
LLAMA_LOG_INFO("%s: Dumping metadata keys/values.\n", __func__);
// get metadata as string
for (int i = 0; i < gguf_get_n_kv(gguf_ctx); i++) {
gguf_type type = gguf_get_kv_type(gguf_ctx, i);
const std::string type_name =
type == GGUF_TYPE_ARRAY
? format("%s[%s,%zu]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(gguf_ctx, i)), gguf_get_arr_n(gguf_ctx, i))
: gguf_type_name(type);
const char * name = gguf_get_key(gguf_ctx, i);
const std::string value = gguf_kv_to_str(gguf_ctx, i);
if (type != GGUF_TYPE_ARRAY) {
adapter.gguf_kv.emplace(name, value);
}
const size_t MAX_VALUE_LEN = 40;
std::string print_value = value.size() > MAX_VALUE_LEN ? format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str()) : value;
replace_all(print_value, "\n", "\\n");
|
random
|
<|fim_prefix|> (int)getRMSState() + (int)mCoverageQualityState;
return rating == 4;
}
bool calib::calibController::getFramesNumberState() const
{
return std::max(mCalibData->imagePoints.size(), mCalibData->allCharucoCorners.size()) > mMinFramesNum;
}
bool calib::calibController::getConfidenceIntrervalsState() const
{
return mConfIntervalsState;
}
bool calib::calibController::getRMSState() const
{
return mCalibData->totalAvgErr < 0.5;
}
int calib::calibController::getNewFlags() const
{
return mCalibFlags;
}
//////////////////// calibDataController
double calib::calibDataController::estimateGridSubsetQuality(size_t excludedIndex)
{
{
int gridSize = 10;
int xGridStep = mCalibData->imageSize.width / gridSize;
int yGridStep = mCalibData->imageSize.height / gridSize;
std::vector<int> pointsInCell(gridSize*gridSize);
std::fill(pointsInCell.begin(), pointsInCell.end(), 0);
for(size_t k = 0; k < mCalibData->imagePoints.size(); k++)
if(k != excludedIndex)
for(std::vector<cv::Point2f>::iterator pointIt = mCalibData->imagePoints[k].begin(); pointIt != mCalibData->imagePoints[k].end(); ++pointIt) {
int i = (int)((*pointIt).x / xGridStep);
int j = (int)((*pointIt).y / yGridStep);
pointsInCell[i*gridSize + j]++;
}
for(size_t k = 0; k < mCalibData->allCharucoCorners.size(); k++)
if(k != excludedIndex)
for(int l = 0; l < mCalibData->allCharucoCorners[k].size[0]; l++) {
int i = (int)(mCalibData->allCharucoCorners[k].at<float>(l, 0) / xGridStep);
int j = (int)(mCalibData->allCharucoCorners[k].at<float>(l, 1) / yGridStep);
pointsInCell[i*gridSize + j]++;
}
cv::Mat mean, stdDev;
cv::meanStdDev(pointsInCell, mean, stdDev);
<|fim_suffix|>}
calib::calibDataController::calibDataController(cv::Ptr<calib::calibrationData> data, int maxFrames, double convParameter) :
mCalibData(data), mParamsFileName("CamParams.xml")
{
mMaxFramesNum = maxFrames;
mAlpha = convParameter;
}
calib::calibDataController::calibDataController()
{
}
void calib::calibDataController::filterFrames()
{
size_t numberOfFrames = std::max(mCalibData->allCharucoIds.size(), mCalibData->imagePoints.size());
CV_Assert(numberOfFrames == mCalibData->perViewErrors.total());
if(numberOfFrames >= mMaxFramesNum) {
double worstValue = -HUGE_VAL, maxQuality = estimateGridSubsetQuality(numberOfFrames);
size_t worstElemIndex = 0;
for(size_t i = 0; i < numberOfFrames; i++) {
double gridQDelta = estimateGridSubsetQuality(i) - maxQuality;
double currentValue = mCalibData->perViewErrors.at<double>((int)i)*mAlpha + gridQDelta*(1. - mAlpha);
if(currentValue > worstValue) {
worstValue = currentValue;
worstElemIndex = i;
}
}
showOverlayMessage(cv::format("Frame %zu is worst", worstElemIndex + 1));
if(mCalibData->allFrames.size())
mCalibData->allFrames.erase(mCalibData->allFrames.begin() + worstElemIndex);
if(mCalibData->imagePoints.size()) {
mCalibData->imagePoints.erase(mCalibData->imagePoints.begin() + worstElemIndex);
mCalibData->objectPoints.erase(mCalibData->objectPoints.begin() + worstElemIndex);
if (mCalibData->allCharucoCorners.size()) {
mCalibData->allCharucoCorners.erase(mCalibData->allCharucoCorners.begin() + worstElemIndex);
mCalibData->allCharucoIds.erase(mCalibData->allCharucoIds.begin() + worstElemIndex);
}
}
cv::Mat newErrorsVec = cv::Mat((int)numberOfFrames - 1, 1, CV_64F);
std::copy(mCalibData->perViewErrors.ptr<double>(0),<|fim_middle|> return mean.at<double>(0) / (stdDev.at<double>(0) + 1e-7);
}
|
(int)getRMSState() + (int)mCoverageQualityState;
return rating == 4;
}
bool calib::calibController::getFramesNumberState() const
{
return std::max(mCalibData->imagePoints.size(), mCalibData->allCharucoCorners.size()) > mMinFramesNum;
}
bool calib::calibController::getConfidenceIntrervalsState() const
{
return mConfIntervalsState;
}
bool calib::calibController::getRMSState() const
{
return mCalibData->totalAvgErr < 0.5;
}
int calib::calibController::getNewFlags() const
{
return mCalibFlags;
}
//////////////////// calibDataController
double calib::calibDataController::estimateGridSubsetQuality(size_t excludedIndex)
{
{
int gridSize = 10;
int xGridStep = mCalibData->imageSize.width / gridSize;
int yGridStep = mCalibData->imageSize.height / gridSize;
std::vector<int> pointsInCell(gridSize*gridSize);
std::fill(pointsInCell.begin(), pointsInCell.end(), 0);
for(size_t k = 0; k < mCalibData->imagePoints.size(); k++)
if(k != excludedIndex)
for(std::vector<cv::Point2f>::iterator pointIt = mCalibData->imagePoints[k].begin(); pointIt != mCalibData->imagePoints[k].end(); ++pointIt) {
int i = (int)((*pointIt).x / xGridStep);
int j = (int)((*pointIt).y / yGridStep);
pointsInCell[i*gridSize + j]++;
}
for(size_t k = 0; k < mCalibData->allCharucoCorners.size(); k++)
if(k != excludedIndex)
for(int l = 0; l < mCalibData->allCharucoCorners[k].size[0]; l++) {
int i = (int)(mCalibData->allCharucoCorners[k].at<float>(l, 0) / xGridStep);
int j = (int)(mCalibData->allCharucoCorners[k].at<float>(l, 1) / yGridStep);
pointsInCell[i*gridSize + j]++;
}
cv::Mat mean, stdDev;
cv::meanStdDev(pointsInCell, mean, stdDev);
|
return mean.at<double>(0) / (stdDev.at<double>(0) + 1e-7);
}
|
}
calib::calibDataController::calibDataController(cv::Ptr<calib::calibrationData> data, int maxFrames, double convParameter) :
mCalibData(data), mParamsFileName("CamParams.xml")
{
mMaxFramesNum = maxFrames;
mAlpha = convParameter;
}
calib::calibDataController::calibDataController()
{
}
void calib::calibDataController::filterFrames()
{
size_t numberOfFrames = std::max(mCalibData->allCharucoIds.size(), mCalibData->imagePoints.size());
CV_Assert(numberOfFrames == mCalibData->perViewErrors.total());
if(numberOfFrames >= mMaxFramesNum) {
double worstValue = -HUGE_VAL, maxQuality = estimateGridSubsetQuality(numberOfFrames);
size_t worstElemIndex = 0;
for(size_t i = 0; i < numberOfFrames; i++) {
double gridQDelta = estimateGridSubsetQuality(i) - maxQuality;
double currentValue = mCalibData->perViewErrors.at<double>((int)i)*mAlpha + gridQDelta*(1. - mAlpha);
if(currentValue > worstValue) {
worstValue = currentValue;
worstElemIndex = i;
}
}
showOverlayMessage(cv::format("Frame %zu is worst", worstElemIndex + 1));
if(mCalibData->allFrames.size())
mCalibData->allFrames.erase(mCalibData->allFrames.begin() + worstElemIndex);
if(mCalibData->imagePoints.size()) {
mCalibData->imagePoints.erase(mCalibData->imagePoints.begin() + worstElemIndex);
mCalibData->objectPoints.erase(mCalibData->objectPoints.begin() + worstElemIndex);
if (mCalibData->allCharucoCorners.size()) {
mCalibData->allCharucoCorners.erase(mCalibData->allCharucoCorners.begin() + worstElemIndex);
mCalibData->allCharucoIds.erase(mCalibData->allCharucoIds.begin() + worstElemIndex);
}
}
cv::Mat newErrorsVec = cv::Mat((int)numberOfFrames - 1, 1, CV_64F);
std::copy(mCalibData->perViewErrors.ptr<double>(0),
|
random
|
<|fim_prefix|>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_H_
#define TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_H_
#include <atomic>
#include <functional>
#include <memory>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "xla/tsl/platform/macros.h"
#include "xla/tsl/platform/types.h"
namespace tsl {
class CoordinationServiceAgent;
}
namespace tensorflow {
namespace activity_watcher {
using ActivityId = tsl::uint64;
constexpr ActivityId kActivityNotRecorded = 0;
constexpr int kWatcherDisabled = 0;
enum ActivityCategory {
kCollective = 0,
kRemoteFunction = 1,
kMisc = 2,
kDatasetOp = 3,
kTpuOp = 4,
kRendezvous = 5,
};
static tsl::string ToString(ActivityCategory category) {
switch (category) {
case ActivityCategory::kCollective:
return "Collective";
case ActivityCategory::kRemoteFunction:
return "Remote Function";
case ActivityCategory::kMisc:<|fim_suffix|> }
}
// An activity to be recorded.
struct Activity {
using Attributes = absl::flat_hash_map<tsl::string, tsl::string>;
// A human readable title of the activity.
tsl::string title;
// The category of the activity.
ActivityCategory category = ActivityCategory::kMisc;
// Key/value pairs that are attached to the activity.
Attributes attributes;
Activity() = default;
Activity(tsl::string title, ActivityCategory category)
: title(std::move(title)), category(category) {}
Activity(tsl::string title, ActivityCategory category, Attributes attributes)
: title(std::move(title)),
category(category),
attributes(std::move(attributes)) {}
};
// Enable activity wathcer to send own workers activities to coordination
// service and also fetch all workers' activities.
void MaybeEnableMultiWorkersWatching(tsl::CoordinationServiceAgent* agent);
namespace tfw_internal {
#if defined(TF_ENABLE_ACTIVITY_WATCHER)
// Records an activity start without checking whether the watcher is enabled.
ActivityId RecordActivityStart(std::unique_ptr<Activity> activity);
// Records an activity end without checking whether the activity_id is valid.
void RecordActivityEnd(ActivityId activity_id);
TF_EXPORT extern std::atomic<int> g_watcher_level;
// Returns whether the activitity watcher is enabled.
inline bool WatcherEnabled(int level = 1) {
return g_watcher_level.load(std::memory_order_acquire) >= level;
}
#endif
// NOTE: Borrowed from boost C++ libraries because std::is_invocable_r is not
// available in Android NDK.
template <typename R, typename F, typename... Args>
struct is_invocable_r
: std::is_constructible<
std::function<R(Args...)>,
std::reference_wrapper<typename std::remove_reference<F>::type>> {};
} // namespace tfw_internal
template <typename F>
constexpr bool is_activity_generator =
tfw_internal::is_invocable_r<std::unique_ptr<Activity>, F>::value;
<|fim_middle|> return "Miscellaneous";
case ActivityCategory::kDatasetOp:
return "Dataset Op";
case ActivityCategory::kTpuOp:
return "TPU Op";
case ActivityCategory::kRendezvous:
return "Rendezvous";
|
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_H_
#define TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_H_
#include <atomic>
#include <functional>
#include <memory>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "xla/tsl/platform/macros.h"
#include "xla/tsl/platform/types.h"
namespace tsl {
class CoordinationServiceAgent;
}
namespace tensorflow {
namespace activity_watcher {
using ActivityId = tsl::uint64;
constexpr ActivityId kActivityNotRecorded = 0;
constexpr int kWatcherDisabled = 0;
enum ActivityCategory {
kCollective = 0,
kRemoteFunction = 1,
kMisc = 2,
kDatasetOp = 3,
kTpuOp = 4,
kRendezvous = 5,
};
static tsl::string ToString(ActivityCategory category) {
switch (category) {
case ActivityCategory::kCollective:
return "Collective";
case ActivityCategory::kRemoteFunction:
return "Remote Function";
case ActivityCategory::kMisc:
|
return "Miscellaneous";
case ActivityCategory::kDatasetOp:
return "Dataset Op";
case ActivityCategory::kTpuOp:
return "TPU Op";
case ActivityCategory::kRendezvous:
return "Rendezvous";
|
}
}
// An activity to be recorded.
struct Activity {
using Attributes = absl::flat_hash_map<tsl::string, tsl::string>;
// A human readable title of the activity.
tsl::string title;
// The category of the activity.
ActivityCategory category = ActivityCategory::kMisc;
// Key/value pairs that are attached to the activity.
Attributes attributes;
Activity() = default;
Activity(tsl::string title, ActivityCategory category)
: title(std::move(title)), category(category) {}
Activity(tsl::string title, ActivityCategory category, Attributes attributes)
: title(std::move(title)),
category(category),
attributes(std::move(attributes)) {}
};
// Enable activity wathcer to send own workers activities to coordination
// service and also fetch all workers' activities.
void MaybeEnableMultiWorkersWatching(tsl::CoordinationServiceAgent* agent);
namespace tfw_internal {
#if defined(TF_ENABLE_ACTIVITY_WATCHER)
// Records an activity start without checking whether the watcher is enabled.
ActivityId RecordActivityStart(std::unique_ptr<Activity> activity);
// Records an activity end without checking whether the activity_id is valid.
void RecordActivityEnd(ActivityId activity_id);
TF_EXPORT extern std::atomic<int> g_watcher_level;
// Returns whether the activitity watcher is enabled.
inline bool WatcherEnabled(int level = 1) {
return g_watcher_level.load(std::memory_order_acquire) >= level;
}
#endif
// NOTE: Borrowed from boost C++ libraries because std::is_invocable_r is not
// available in Android NDK.
template <typename R, typename F, typename... Args>
struct is_invocable_r
: std::is_constructible<
std::function<R(Args...)>,
std::reference_wrapper<typename std::remove_reference<F>::type>> {};
} // namespace tfw_internal
template <typename F>
constexpr bool is_activity_generator =
tfw_internal::is_invocable_r<std::unique_ptr<Activity>, F>::value;
|
random
|
<|fim_prefix|> const bool kRegistered = method.channel_tag() && context->authority().empty();
grpc_call* c_call = nullptr;
if (kRegistered) {
c_call = grpc_channel_create_registered_call(
c_channel_, context->propagate_from_call_,
context->propagation_options_.c_bitmask(), cq->cq(),
method.channel_tag(), context->raw_deadline(), nullptr);
} else {
const ::std::string* host_str = nullptr;
if (!context->authority_.empty()) {
host_str = &context->authority_;
} else if (!host_.empty()) {
host_str = &host_;
}
grpc_slice method_slice =
SliceFromArray(method.name(), strlen(method.name()));
grpc_slice host_slice;
if (host_str != nullptr) {
host_slice = grpc::SliceFromCopiedString(*host_str);
}
c_call = grpc_channel_create_call(
c_channel_, context->propagate_from_call_,
context->propagation_options_.c_bitmask(), cq->cq(), method_slice,
host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(),
nullptr);
grpc_slice_unref(method_slice);
if (host_str != nullptr) {
grpc_slice_unref(host_slice);
}
}
grpc_census_call_set_context(c_call, context->census_context());
// ClientRpcInfo should be set before call because set_call also checks
// whether the call has been cancelled, and if the call was cancelled, we
// should notify the interceptors too.
auto* info = context->set_client_rpc_info(
method.name(), method.suffix_for_stats(), method.method_type(), this,
interceptor_creators_, interceptor_pos);
context->set_call(c_call, shared_from_this());
return grpc::internal::Call(c_call, this, cq, info);
}
grpc::internal::Call Channel::CreateCall(
const grpc::internal::RpcMethod& method, grpc::ClientContext* context,
CompletionQueue* cq) {
return CreateCallInternal(method, context, cq, 0);
}
void Channel::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops,<|fim_suffix|>
grpc_connectivity_state Channel::GetState(bool try_to_connect) {
return grpc_channel_check_connectivity_state(c_channel_, try_to_connect);
}
namespace {
class TagSaver final : public grpc::internal::CompletionQueueTag {
public:
explicit TagSaver(void* tag) : tag_(tag) {}
~TagSaver() override {}
bool FinalizeResult(void** tag, bool* /*status*/) override {
*tag = tag_;
delete this;
return true;
}
private:
void* tag_;
};
} // namespace
void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline,
grpc::CompletionQueue* cq, void* tag) {
TagSaver* tag_saver = new TagSaver(tag);
grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline,
cq->cq(), tag_saver);
}
bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline) {
grpc::CompletionQueue cq;
bool ok = false;
void* tag = nullptr;
NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr);
cq.Next(&tag, &ok);
GRPC_CHECK_EQ(tag, nullptr);
return ok;
}
namespace {
class ShutdownCallback : public grpc_completion_queue_functor {
public:
ShutdownCallback() {
functor_run = &ShutdownCallback::Run;
// Set inlineable to true since this callback is trivial and thus does not
// need to be run from the EventEngine (potentially triggering a thread
// hop). This should only be used by internal callbacks like this and not by
// user application code.
inlineable = true;
}
// TakeCQ takes ownership of the cq into the shutdown callback
// so that the shutdown callback will be responsible for destroying it
void TakeCQ(grpc::CompletionQueue* cq) { cq_ = cq; }
// The Run function will get invoked by the completion queue library
// when the shutdown is actually complete<|fim_middle|> grpc::internal::Call* call) {
ops->FillOps(
call); // Make a copy of call. It's fine since Call just has pointers
}
void* Channel::RegisterMethod(const char* method) {
return grpc_channel_register_call(
c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr);
}
|
const bool kRegistered = method.channel_tag() && context->authority().empty();
grpc_call* c_call = nullptr;
if (kRegistered) {
c_call = grpc_channel_create_registered_call(
c_channel_, context->propagate_from_call_,
context->propagation_options_.c_bitmask(), cq->cq(),
method.channel_tag(), context->raw_deadline(), nullptr);
} else {
const ::std::string* host_str = nullptr;
if (!context->authority_.empty()) {
host_str = &context->authority_;
} else if (!host_.empty()) {
host_str = &host_;
}
grpc_slice method_slice =
SliceFromArray(method.name(), strlen(method.name()));
grpc_slice host_slice;
if (host_str != nullptr) {
host_slice = grpc::SliceFromCopiedString(*host_str);
}
c_call = grpc_channel_create_call(
c_channel_, context->propagate_from_call_,
context->propagation_options_.c_bitmask(), cq->cq(), method_slice,
host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(),
nullptr);
grpc_slice_unref(method_slice);
if (host_str != nullptr) {
grpc_slice_unref(host_slice);
}
}
grpc_census_call_set_context(c_call, context->census_context());
// ClientRpcInfo should be set before call because set_call also checks
// whether the call has been cancelled, and if the call was cancelled, we
// should notify the interceptors too.
auto* info = context->set_client_rpc_info(
method.name(), method.suffix_for_stats(), method.method_type(), this,
interceptor_creators_, interceptor_pos);
context->set_call(c_call, shared_from_this());
return grpc::internal::Call(c_call, this, cq, info);
}
grpc::internal::Call Channel::CreateCall(
const grpc::internal::RpcMethod& method, grpc::ClientContext* context,
CompletionQueue* cq) {
return CreateCallInternal(method, context, cq, 0);
}
void Channel::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops,
|
grpc::internal::Call* call) {
ops->FillOps(
call); // Make a copy of call. It's fine since Call just has pointers
}
void* Channel::RegisterMethod(const char* method) {
return grpc_channel_register_call(
c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr);
}
|
grpc_connectivity_state Channel::GetState(bool try_to_connect) {
return grpc_channel_check_connectivity_state(c_channel_, try_to_connect);
}
namespace {
class TagSaver final : public grpc::internal::CompletionQueueTag {
public:
explicit TagSaver(void* tag) : tag_(tag) {}
~TagSaver() override {}
bool FinalizeResult(void** tag, bool* /*status*/) override {
*tag = tag_;
delete this;
return true;
}
private:
void* tag_;
};
} // namespace
void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline,
grpc::CompletionQueue* cq, void* tag) {
TagSaver* tag_saver = new TagSaver(tag);
grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline,
cq->cq(), tag_saver);
}
bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline) {
grpc::CompletionQueue cq;
bool ok = false;
void* tag = nullptr;
NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr);
cq.Next(&tag, &ok);
GRPC_CHECK_EQ(tag, nullptr);
return ok;
}
namespace {
class ShutdownCallback : public grpc_completion_queue_functor {
public:
ShutdownCallback() {
functor_run = &ShutdownCallback::Run;
// Set inlineable to true since this callback is trivial and thus does not
// need to be run from the EventEngine (potentially triggering a thread
// hop). This should only be used by internal callbacks like this and not by
// user application code.
inlineable = true;
}
// TakeCQ takes ownership of the cq into the shutdown callback
// so that the shutdown callback will be responsible for destroying it
void TakeCQ(grpc::CompletionQueue* cq) { cq_ = cq; }
// The Run function will get invoked by the completion queue library
// when the shutdown is actually complete
|
random
|
<|fim_prefix|>
int selected_track = 0;
Vector<Rect2> view_rects;
Ref<Texture2D> bezier_icon;
Ref<Texture2D> bezier_handle_icon;
Ref<Texture2D> selected_icon;
RBMap<int, Rect2> subtracks;
enum {
REMOVE_ICON,
LOCK_ICON,
SOLO_ICON,
VISIBILITY_ICON
};
RBMap<int, RBMap<int, Rect2>> subtrack_icons;
HashSet<int> locked_tracks;
HashSet<int> hidden_tracks;
int solo_track = -1;
bool is_filtered = false;
float track_v_scroll = 0;
float track_v_scroll_max = 0;
float timeline_v_scroll = 0;
float timeline_v_zoom = 1;
PopupMenu *menu = nullptr;
void _zoom_changed();
void _update_locked_tracks_after(int p_track);
void _update_hidden_tracks_after(int p_track);
virtual void gui_input(const Ref<InputEvent> &p_event) override;
void _menu_selected(int p_index);
void _play_position_draw();
bool _is_track_displayed(int p_track_index);
bool _is_track_curves_displayed(int p_track_index);
Vector2 insert_at_pos;
typedef Pair<int, int> IntPair;
bool moving_selection_attempt = false;
bool moving_inserted_key = false;
Point2 moving_selection_mouse_begin;
IntPair select_single_attempt;
bool moving_selection = false;
int moving_selection_from_key = 0;
int moving_selection_from_track = 0;
Vector2 moving_selection_offset;
bool box_selecting_attempt = false;
bool box_selecting = false;
bool box_selecting_add = false;
Vector2 box_selection_from;
Vector2 box_selection_to;
Rect2 selection_rect;
Rect2 selection_handles_rect;
bool scaling_selection = false;
Vector2i scaling_selection_handles;
Vector2 scaling_selection_scale = Vector2(1, 1);
Vector2 scaling_selection_offset;
Point2 scaling_selection_pivot;
int moving_handle = 0; //0 no move -1 or +1 out, 2 both (drawing only)
int moving_handle_key = 0;
int moving_handle_track = 0;
Vector2 moving_handle_left;
Vector2 moving_handle_right;
int moving_handle_mode = 0; // value from Animation::HandleMode
struct PairHasher {
static _FORCE_INLINE_ uint32_t hash(const Pair<int, int> &p_value) <|fim_suffix|>
hash = hash * 31 * hash_one_uint64(p_value.second);
return hash;
}
};
HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_lefts;
HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_rights;
void _clear_selection();
void _clear_selection_for_anim(const Ref<Animation> &p_anim);
void _select_at_anim(const Ref<Animation> &p_anim, int p_track, real_t p_pos, bool p_single);
bool _try_select_at_ui_pos(const Point2 &p_pos, bool p_aggregate, bool p_deselectable);
void _change_selected_keys_handle_mode(Animation::HandleMode p_mode, bool p_auto = false);
Vector2 menu_insert_key;
struct AnimMoveRestore {
int track = 0;
double time = 0;
Variant key;
real_t transition = 0;
};
AnimationTrackEditor *editor = nullptr;
struct EditPoint {
Rect2 point_rect;
Rect2 in_rect;
Rect2 out_rect;
int track = 0;
int key = 0;
};
Vector<EditPoint> edit_points;
struct PairCompare {
bool operator()(const IntPair &lh, const IntPair &rh) {
if (lh.first == rh.first) {
return lh.second < rh.second;
} else {
return lh.first < rh.first;
}
}
};
typedef RBSet<IntPair, PairCompare> SelectionSet;
SelectionSet selection;
Ref<ViewPanner> panner;
void _pan_callback(Vector2 p_scroll_vec, Ref<InputEvent> p_event);
void _zoom_callback(float p_zoom_factor, Vector2 p_origin, Ref<InputEvent> p_event);
void _draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right);
void _draw_track(int p_track, const Color &p_color);
float _bezier_h_to_pixel(float p_h);
void _zoom_vertically(real_t p_minimum_value, real_t p_maximum_value);
protected:
static void _bind_methods();
void _notification(int p_what);
public:
static float get_bezier_key_value(Array p_bezier_key_array);
virtual String get_tooltip(const Point2 &p_pos) const override;
Ref<Animation> get_animation() const;
void set_animation_and_track(const Ref<Animation> &p_animation, int<|fim_middle|>{
int32_t hash = 23;
hash = hash * 31 * hash_one_uint64(p_value.first);
|
int selected_track = 0;
Vector<Rect2> view_rects;
Ref<Texture2D> bezier_icon;
Ref<Texture2D> bezier_handle_icon;
Ref<Texture2D> selected_icon;
RBMap<int, Rect2> subtracks;
enum {
REMOVE_ICON,
LOCK_ICON,
SOLO_ICON,
VISIBILITY_ICON
};
RBMap<int, RBMap<int, Rect2>> subtrack_icons;
HashSet<int> locked_tracks;
HashSet<int> hidden_tracks;
int solo_track = -1;
bool is_filtered = false;
float track_v_scroll = 0;
float track_v_scroll_max = 0;
float timeline_v_scroll = 0;
float timeline_v_zoom = 1;
PopupMenu *menu = nullptr;
void _zoom_changed();
void _update_locked_tracks_after(int p_track);
void _update_hidden_tracks_after(int p_track);
virtual void gui_input(const Ref<InputEvent> &p_event) override;
void _menu_selected(int p_index);
void _play_position_draw();
bool _is_track_displayed(int p_track_index);
bool _is_track_curves_displayed(int p_track_index);
Vector2 insert_at_pos;
typedef Pair<int, int> IntPair;
bool moving_selection_attempt = false;
bool moving_inserted_key = false;
Point2 moving_selection_mouse_begin;
IntPair select_single_attempt;
bool moving_selection = false;
int moving_selection_from_key = 0;
int moving_selection_from_track = 0;
Vector2 moving_selection_offset;
bool box_selecting_attempt = false;
bool box_selecting = false;
bool box_selecting_add = false;
Vector2 box_selection_from;
Vector2 box_selection_to;
Rect2 selection_rect;
Rect2 selection_handles_rect;
bool scaling_selection = false;
Vector2i scaling_selection_handles;
Vector2 scaling_selection_scale = Vector2(1, 1);
Vector2 scaling_selection_offset;
Point2 scaling_selection_pivot;
int moving_handle = 0; //0 no move -1 or +1 out, 2 both (drawing only)
int moving_handle_key = 0;
int moving_handle_track = 0;
Vector2 moving_handle_left;
Vector2 moving_handle_right;
int moving_handle_mode = 0; // value from Animation::HandleMode
struct PairHasher {
static _FORCE_INLINE_ uint32_t hash(const Pair<int, int> &p_value)
|
{
int32_t hash = 23;
hash = hash * 31 * hash_one_uint64(p_value.first);
|
hash = hash * 31 * hash_one_uint64(p_value.second);
return hash;
}
};
HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_lefts;
HashMap<Pair<int, int>, Vector2, PairHasher> additional_moving_handle_rights;
void _clear_selection();
void _clear_selection_for_anim(const Ref<Animation> &p_anim);
void _select_at_anim(const Ref<Animation> &p_anim, int p_track, real_t p_pos, bool p_single);
bool _try_select_at_ui_pos(const Point2 &p_pos, bool p_aggregate, bool p_deselectable);
void _change_selected_keys_handle_mode(Animation::HandleMode p_mode, bool p_auto = false);
Vector2 menu_insert_key;
struct AnimMoveRestore {
int track = 0;
double time = 0;
Variant key;
real_t transition = 0;
};
AnimationTrackEditor *editor = nullptr;
struct EditPoint {
Rect2 point_rect;
Rect2 in_rect;
Rect2 out_rect;
int track = 0;
int key = 0;
};
Vector<EditPoint> edit_points;
struct PairCompare {
bool operator()(const IntPair &lh, const IntPair &rh) {
if (lh.first == rh.first) {
return lh.second < rh.second;
} else {
return lh.first < rh.first;
}
}
};
typedef RBSet<IntPair, PairCompare> SelectionSet;
SelectionSet selection;
Ref<ViewPanner> panner;
void _pan_callback(Vector2 p_scroll_vec, Ref<InputEvent> p_event);
void _zoom_callback(float p_zoom_factor, Vector2 p_origin, Ref<InputEvent> p_event);
void _draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right);
void _draw_track(int p_track, const Color &p_color);
float _bezier_h_to_pixel(float p_h);
void _zoom_vertically(real_t p_minimum_value, real_t p_maximum_value);
protected:
static void _bind_methods();
void _notification(int p_what);
public:
static float get_bezier_key_value(Array p_bezier_key_array);
virtual String get_tooltip(const Point2 &p_pos) const override;
Ref<Animation> get_animation() const;
void set_animation_and_track(const Ref<Animation> &p_animation, int
|
ast_based
|
<|fim_prefix|>ling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
}
if (moving_inserted_key && moving_selection_from_track == p_track) {
if (moving_selection_from_key == i) {
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(p_track, i);
if (handle_mode != Animation::HANDLE_MODE_FREE) {
float offset_p = offset;
float height_p = height;
if (E->prev()) {
int i_p = E->prev()->get();
offset_p = animation->track_get_key_time(p_track, i_p);
height_p = animation->bezier_track_get_key_value(p_track, i_p);
}
animation->bezier_track_calculate_handles(offset, offset_p, height_p, offset_n, height_n, handle_mode, Animation::HANDLE_SET_MODE_AUTO, nullptr, &out_handle);
}
} else if (moving_selection_from_key == i_n) {
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(p_track, i_n);
if (handle_mode != Animation::HANDLE_MODE_FREE) {
float offset_nn = offset_n;
float height_nn = height_n;
if (E->next()->next()) {
int i_nn = E->next()->next()->get();
offset_nn = animation->track_get_key_time(p_track, i_nn);
height_nn = animation->bezier_track_get_key_value(p_track, i_nn);
}
animation->bezier_track_calculate_handles(offset_n, offset, height, offset_nn, height_nn, handle_mode, Animation::HANDLE_SET_MODE_AUTO, &in_handle, nullptr);
}
}
}
out_handle += Vector2(offset, height);
in_handle += Vector2(offset_n, height_n);
Vector2 start(offset, height);
Vector2 end(offset_n, height_n);
int from_x = (offset - timeline->get_value()) * scale + limit;
int point_start = from_x;
int to_x = (offset_n - timeline->get_value()) * scale + limit;
int point_end = to_x;
if (from_x > right_limit) { // Not visible.
continue;
}
if (to_x < limit) { // Not visible.
continue;
}
from_x = MAX(from_x, limit);
to_x = MIN(to_x, right_limit);
Vector<Vector2> lines;
Vector2 prev_pos;
for (<|fim_suffix|> j <= to_x; j++) {
float t = (j - limit) / scale + timeline->get_value();
float h;
if (j == point_end) {
h = end.y; // Make sure it always connects.
} else if (j == point_start) {
h = start.y; // Make sure it always connects.
} else { // Custom interpolation, used because it needs to show paths affected by moving the selection or handles.
int iterations = 10;
float low = 0;
float high = 1;
// Narrow high and low as much as possible.
for (int k = 0; k < iterations; k++) {
float middle = (low + high) / 2.0;
Vector2 interp = start.bezier_interpolate(out_handle, in_handle, end, middle);
if (interp.x < t) {
low = middle;
} else {
high = middle;
}
}
// Interpolate the result.
Vector2 low_pos = start.bezier_interpolate(out_handle, in_handle, end, low);
Vector2 high_pos = start.bezier_interpolate(out_handle, in_handle, end, high);
float c = (t - low_pos.x) / (high_pos.x - low_pos.x);
h = low_pos.lerp(high_pos, c).y;
}
h = _bezier_h_to_pixel(h);
Vector2 pos(j, h);
if (j > from_x) {
lines.push_back(prev_pos);
lines.push_back(pos);
}
prev_pos = pos;
}
if (lines.size() >= 2) {
draw_multiline(lines, p_color, Math::round(EDSCALE), true);
}
}
}
void AnimationBezierTrackEdit::_draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right) {
Vector2 from = p_from;
Vector2 to = p_to;
if (from.x == to.x && from.y == to.y) {
return;
}
if (to.x < from.x) {
SWAP(to, from);
}
if (to.x < p_clip_left) {
return;
}
if (from.x > p_clip_right) {
return;
}
if (to.x > p_clip_right) {
float c = (p_clip_right - from.x) / (to.x - from.x);
to = from.lerp(to, c);
}
if (from.x < p_clip_left) {
float c = (p_clip_left - from.x) / (to.x - from.x);
from = from.lerp(to, c);
}
draw_line(from, to, p_color, Math::round(EDSCALE), true);
}
void AnimationBezierTrackEdit:<|fim_middle|>int j = from_x;
|
ling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
}
if (moving_inserted_key && moving_selection_from_track == p_track) {
if (moving_selection_from_key == i) {
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(p_track, i);
if (handle_mode != Animation::HANDLE_MODE_FREE) {
float offset_p = offset;
float height_p = height;
if (E->prev()) {
int i_p = E->prev()->get();
offset_p = animation->track_get_key_time(p_track, i_p);
height_p = animation->bezier_track_get_key_value(p_track, i_p);
}
animation->bezier_track_calculate_handles(offset, offset_p, height_p, offset_n, height_n, handle_mode, Animation::HANDLE_SET_MODE_AUTO, nullptr, &out_handle);
}
} else if (moving_selection_from_key == i_n) {
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(p_track, i_n);
if (handle_mode != Animation::HANDLE_MODE_FREE) {
float offset_nn = offset_n;
float height_nn = height_n;
if (E->next()->next()) {
int i_nn = E->next()->next()->get();
offset_nn = animation->track_get_key_time(p_track, i_nn);
height_nn = animation->bezier_track_get_key_value(p_track, i_nn);
}
animation->bezier_track_calculate_handles(offset_n, offset, height, offset_nn, height_nn, handle_mode, Animation::HANDLE_SET_MODE_AUTO, &in_handle, nullptr);
}
}
}
out_handle += Vector2(offset, height);
in_handle += Vector2(offset_n, height_n);
Vector2 start(offset, height);
Vector2 end(offset_n, height_n);
int from_x = (offset - timeline->get_value()) * scale + limit;
int point_start = from_x;
int to_x = (offset_n - timeline->get_value()) * scale + limit;
int point_end = to_x;
if (from_x > right_limit) { // Not visible.
continue;
}
if (to_x < limit) { // Not visible.
continue;
}
from_x = MAX(from_x, limit);
to_x = MIN(to_x, right_limit);
Vector<Vector2> lines;
Vector2 prev_pos;
for (
|
int j = from_x;
|
j <= to_x; j++) {
float t = (j - limit) / scale + timeline->get_value();
float h;
if (j == point_end) {
h = end.y; // Make sure it always connects.
} else if (j == point_start) {
h = start.y; // Make sure it always connects.
} else { // Custom interpolation, used because it needs to show paths affected by moving the selection or handles.
int iterations = 10;
float low = 0;
float high = 1;
// Narrow high and low as much as possible.
for (int k = 0; k < iterations; k++) {
float middle = (low + high) / 2.0;
Vector2 interp = start.bezier_interpolate(out_handle, in_handle, end, middle);
if (interp.x < t) {
low = middle;
} else {
high = middle;
}
}
// Interpolate the result.
Vector2 low_pos = start.bezier_interpolate(out_handle, in_handle, end, low);
Vector2 high_pos = start.bezier_interpolate(out_handle, in_handle, end, high);
float c = (t - low_pos.x) / (high_pos.x - low_pos.x);
h = low_pos.lerp(high_pos, c).y;
}
h = _bezier_h_to_pixel(h);
Vector2 pos(j, h);
if (j > from_x) {
lines.push_back(prev_pos);
lines.push_back(pos);
}
prev_pos = pos;
}
if (lines.size() >= 2) {
draw_multiline(lines, p_color, Math::round(EDSCALE), true);
}
}
}
void AnimationBezierTrackEdit::_draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right) {
Vector2 from = p_from;
Vector2 to = p_to;
if (from.x == to.x && from.y == to.y) {
return;
}
if (to.x < from.x) {
SWAP(to, from);
}
if (to.x < p_clip_left) {
return;
}
if (from.x > p_clip_right) {
return;
}
if (to.x > p_clip_right) {
float c = (p_clip_right - from.x) / (to.x - from.x);
to = from.lerp(to, c);
}
if (from.x < p_clip_left) {
float c = (p_clip_left - from.x) / (to.x - from.x);
from = from.lerp(to, c);
}
draw_line(from, to, p_color, Math::round(EDSCALE), true);
}
void AnimationBezierTrackEdit:
|
ast_based
|
<|fim_prefix|> }
Ref<Texture2D> t;
if (animation) {
t = frames->get_frame_texture(animation, frame);
}
if (t.is_null()) {
return Rect2();
}
Size2 s = t->get_size();
Point2 ofs = offset;
if (centered) {
ofs -= s / 2;
}
if (s == Size2(0, 0)) {
s = Size2(1, 1);
}
return Rect2(ofs, s);
}
void AnimatedSprite2D::_validate_property(PropertyInfo &p_property) const {
if (frames.is_null()) {
return;
}
if (!Engine::get_singleton()->is_editor_hint()) {
if (p_property.name == "frame" && playing) {
p_property.usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_READ_ONLY;
}
return;
}
if (p_property.name == "animation") {
List<StringName> names;
frames->get_animation_list(&names);
names.sort_custom<StringName::AlphCompare>();
bool current_found = false;
bool is_first_element = true;
for (const StringName &E : names) {
if (!is_first_element) {
p_property.hint_string += ",";
} else {
is_first_element = false;
}
p_property.hint_string += String(E);
if (animation == E) {
current_found = true;
}
}
if (!current_found) {
if (p_property.hint_string.is_empty()) {
p_property.hint_string = String(animation);
} else {
p_property.hint_string = String(animation) + "," + p_property.hint_string;
}
}
return;
}
if (p_property.name == "frame") {
if (playing) {
p_property.usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_READ_ONLY;
return;
}
p_property.hint = PROPERTY_HINT_RANGE;
if (frames->has_animation(animation) && frames->get_frame_count(animation) > 0) {
p_property.hint_string = "0," + itos(frames->get_frame_count(animation) - 1) + ",1";
} else {
// Avoid an error, `hint_string` is required for `PROPERTY_HINT_RANGE`.
p_property.hint_string = "0,0,1";
}
p_property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
}
void AnimatedSprite2D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ACCESSIBILITY_UPDATE: {
RID ae = get_accessibility_element();<|fim_suffix|>
Rect2 dst_rect = _get_rect();
DisplayServer::get_singleton()->accessibility_update_set_role(ae, DisplayServer::AccessibilityRole::ROLE_IMAGE);
DisplayServer::get_singleton()->accessibility_update_set_transform(ae, get_transform());
DisplayServer::get_singleton()->accessibility_update_set_bounds(ae, dst_rect);
} break;
case NOTIFICATION_READY: {
if (!Engine::get_singleton()->is_editor_hint() && frames.is_valid() && frames->has_animation(autoplay)) {
play(autoplay);
}
} break;
case NOTIFICATION_INTERNAL_PROCESS: {
if (frames.is_null() || !frames->has_animation(animation)) {
return;
}
double remaining = get_process_delta_time();
int i = 0;
while (remaining) {
// Animation speed may be changed by animation_finished or frame_changed signals.
double speed = frames->get_animation_speed(animation) * speed_scale * custom_speed_scale * frame_speed_scale;
double abs_speed = Math::abs(speed);
if (speed == 0) {
return; // Do nothing.
}
// Frame count may be changed by animation_finished or frame_changed signals.
int fc = frames->get_frame_count(animation);
int last_frame = fc - 1;
if (!std::signbit(speed)) {
// Forwards.
if (frame_progress >= 1.0) {
if (frame >= last_frame) {
if (frames->get_animation_loop(animation)) {
frame = 0;
emit_signal("animation_looped");
} else {
frame = last_frame;
pause();
emit_signal(SceneStringName(animation_finished));
return;
}
} else {
frame++;
}
_calc_frame_speed_scale();
frame_progress = 0.0;
queue_redraw();
emit_signal(SceneStringName(frame_changed));
}
double to_process = MIN((1.0 - frame_progress) / abs_speed, remaining);
frame_progress += to_process * abs_speed;
remaining -= to_process;
} else {
// Backwards.
if (frame_progress <= 0) {
if (frame <= 0) {<|fim_middle|> ERR_FAIL_COND(ae.is_null());
|
}
Ref<Texture2D> t;
if (animation) {
t = frames->get_frame_texture(animation, frame);
}
if (t.is_null()) {
return Rect2();
}
Size2 s = t->get_size();
Point2 ofs = offset;
if (centered) {
ofs -= s / 2;
}
if (s == Size2(0, 0)) {
s = Size2(1, 1);
}
return Rect2(ofs, s);
}
void AnimatedSprite2D::_validate_property(PropertyInfo &p_property) const {
if (frames.is_null()) {
return;
}
if (!Engine::get_singleton()->is_editor_hint()) {
if (p_property.name == "frame" && playing) {
p_property.usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_READ_ONLY;
}
return;
}
if (p_property.name == "animation") {
List<StringName> names;
frames->get_animation_list(&names);
names.sort_custom<StringName::AlphCompare>();
bool current_found = false;
bool is_first_element = true;
for (const StringName &E : names) {
if (!is_first_element) {
p_property.hint_string += ",";
} else {
is_first_element = false;
}
p_property.hint_string += String(E);
if (animation == E) {
current_found = true;
}
}
if (!current_found) {
if (p_property.hint_string.is_empty()) {
p_property.hint_string = String(animation);
} else {
p_property.hint_string = String(animation) + "," + p_property.hint_string;
}
}
return;
}
if (p_property.name == "frame") {
if (playing) {
p_property.usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_READ_ONLY;
return;
}
p_property.hint = PROPERTY_HINT_RANGE;
if (frames->has_animation(animation) && frames->get_frame_count(animation) > 0) {
p_property.hint_string = "0," + itos(frames->get_frame_count(animation) - 1) + ",1";
} else {
// Avoid an error, `hint_string` is required for `PROPERTY_HINT_RANGE`.
p_property.hint_string = "0,0,1";
}
p_property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
}
void AnimatedSprite2D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ACCESSIBILITY_UPDATE: {
RID ae = get_accessibility_element();
|
ERR_FAIL_COND(ae.is_null());
|
Rect2 dst_rect = _get_rect();
DisplayServer::get_singleton()->accessibility_update_set_role(ae, DisplayServer::AccessibilityRole::ROLE_IMAGE);
DisplayServer::get_singleton()->accessibility_update_set_transform(ae, get_transform());
DisplayServer::get_singleton()->accessibility_update_set_bounds(ae, dst_rect);
} break;
case NOTIFICATION_READY: {
if (!Engine::get_singleton()->is_editor_hint() && frames.is_valid() && frames->has_animation(autoplay)) {
play(autoplay);
}
} break;
case NOTIFICATION_INTERNAL_PROCESS: {
if (frames.is_null() || !frames->has_animation(animation)) {
return;
}
double remaining = get_process_delta_time();
int i = 0;
while (remaining) {
// Animation speed may be changed by animation_finished or frame_changed signals.
double speed = frames->get_animation_speed(animation) * speed_scale * custom_speed_scale * frame_speed_scale;
double abs_speed = Math::abs(speed);
if (speed == 0) {
return; // Do nothing.
}
// Frame count may be changed by animation_finished or frame_changed signals.
int fc = frames->get_frame_count(animation);
int last_frame = fc - 1;
if (!std::signbit(speed)) {
// Forwards.
if (frame_progress >= 1.0) {
if (frame >= last_frame) {
if (frames->get_animation_loop(animation)) {
frame = 0;
emit_signal("animation_looped");
} else {
frame = last_frame;
pause();
emit_signal(SceneStringName(animation_finished));
return;
}
} else {
frame++;
}
_calc_frame_speed_scale();
frame_progress = 0.0;
queue_redraw();
emit_signal(SceneStringName(frame_changed));
}
double to_process = MIN((1.0 - frame_progress) / abs_speed, remaining);
frame_progress += to_process * abs_speed;
remaining -= to_process;
} else {
// Backwards.
if (frame_progress <= 0) {
if (frame <= 0) {
|
random
|
<|fim_prefix|>/**************************************************************************/
/* engine.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/* */<|fim_suffix|>/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#include "core/os/main_loop.h"
#include "core/string/ustring.h"
#include "core/templates/list.h"
template <typename T>
class TypedArray;
class Engine {
public:
struct Singleton {
StringName name;
Object *ptr = nullptr;
StringName class_name; // Used for binding generation hinting.
// Singleton scope flags.
bool user_created = false;
bool editor_only = false;
Singleton(const StringName &p_name = StringName(), Object *p_ptr = nullptr, const StringName &p_class_name = StringName());
};
private:
friend class Main;
uint64_t frames_drawn = 0;
uint32_t _frame_delay = 0;
uint64_t _frame_ticks = 0;
double _process_step = 0;
int ips = 60;
double physics_jitter_fix = 0.5;
double _fps = 1;
int _max_fps = 0;
int _audio_output_latency = 0;
double _time_scale = 1.0;
uint64_t _physics_frames = 0;
int max_physics_steps_per_frame = 8;
double _physics_interpolation_fraction = 0.0f;
bool abort_on_gpu_errors = false;
bool use_validation_layers = false;
bool generate_spirv_debug_info = false;
bool extra_gpu_memory_tracking = false;
#if defined(DEBUG_ENABLED) || defined(DEV_ENABLED)
bool accurate_breadcrumbs = false;
#endif
int32_t gpu_idx = -1;
uint64_t _process_frames = 0;
bool _in_physics = false;
List<Singleton> singletons;
HashMap<StringName, Object *> singleton_ptrs;
bool editor_hint = false;
bool project_manager_hint = false;
bool extension_reloading = false;
bool embedded_in_editor = false;
bool recovery_mode_hint = false;
bool _print_header = true;
static inline Engine *singleton = nullptr;
String write_movie_path;
String shader_cache_path;
static constexpr int SERVER_SYNC_FRAME_COUNT_WARNING = 5;
int server_syncs = 0;
bool frame_server_synced = false;
<|fim_middle|>/* 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, */
|
/**************************************************************************/
/* engine.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/**************************************************************************/
#pragma once
#include "core/os/main_loop.h"
#include "core/string/ustring.h"
#include "core/templates/list.h"
template <typename T>
class TypedArray;
class Engine {
public:
struct Singleton {
StringName name;
Object *ptr = nullptr;
StringName class_name; // Used for binding generation hinting.
// Singleton scope flags.
bool user_created = false;
bool editor_only = false;
Singleton(const StringName &p_name = StringName(), Object *p_ptr = nullptr, const StringName &p_class_name = StringName());
};
private:
friend class Main;
uint64_t frames_drawn = 0;
uint32_t _frame_delay = 0;
uint64_t _frame_ticks = 0;
double _process_step = 0;
int ips = 60;
double physics_jitter_fix = 0.5;
double _fps = 1;
int _max_fps = 0;
int _audio_output_latency = 0;
double _time_scale = 1.0;
uint64_t _physics_frames = 0;
int max_physics_steps_per_frame = 8;
double _physics_interpolation_fraction = 0.0f;
bool abort_on_gpu_errors = false;
bool use_validation_layers = false;
bool generate_spirv_debug_info = false;
bool extra_gpu_memory_tracking = false;
#if defined(DEBUG_ENABLED) || defined(DEV_ENABLED)
bool accurate_breadcrumbs = false;
#endif
int32_t gpu_idx = -1;
uint64_t _process_frames = 0;
bool _in_physics = false;
List<Singleton> singletons;
HashMap<StringName, Object *> singleton_ptrs;
bool editor_hint = false;
bool project_manager_hint = false;
bool extension_reloading = false;
bool embedded_in_editor = false;
bool recovery_mode_hint = false;
bool _print_header = true;
static inline Engine *singleton = nullptr;
String write_movie_path;
String shader_cache_path;
static constexpr int SERVER_SYNC_FRAME_COUNT_WARNING = 5;
int server_syncs = 0;
bool frame_server_synced = false;
|
random
|
<|fim_prefix|> handle_mode,
handle_set_mode);
}
// 4 - (undo) Remove inserted keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t newpos = animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x;
undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", E->get().first, newpos);
}
// 5 - (undo) Reinsert keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t oldpos = animation->track_get_key_time(E->get().first, E->get().second);
Array key = animation->track_get_key_value(E->get().first, E->get().second);
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
E->get().first,
oldpos,
key[0],
Vector2(key[1], key[2]),
Vector2(key[3], key[4]),
animation->bezier_track_get_key_handle_mode(E->get().first, E->get().second));
}
// 6 - (undo) Reinsert overlapped keys.
List<AnimMoveRestore>::ConstIterator restore_itr = to_restore.begin();
List<Animation::HandleMode>::ConstIterator handle_itr = to_restore_handle_modes.begin();
for (; restore_itr != to_restore.end() && handle_itr != to_restore_handle_modes.end(); ++restore_itr, ++handle_itr) {
const AnimMoveRestore &amr = *restore_itr;
Array key = amr.key;
undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, 1);
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
amr.track,
amr.time,
key[0],
Vector2(key[1], key[2]),
Vector2(key[3], key[4]),
*handle_itr);
}
undo_redo->add_do_method(this, "_clear_selection_for_anim", animation);
undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation);
// 7 - Reselect.
int i = 0;
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) <|fim_suffix|>
real_t newpos = oldpos + moving_selection_offset.x;
undo_redo->add_do_method(this, "_select_at_anim", animation, E->get().first, newpos, i == 0);
undo_redo->add_undo_method(this, "_select_at_anim", animation, E->get().first, oldpos, i == 0);
i++;
}
AnimationPlayerEditor *ape = AnimationPlayerEditor::get_singleton();
if (ape) {
undo_redo->add_do_method(ape, "_animation_update_key_frame");
undo_redo->add_undo_method(ape, "_animation_update_key_frame");
}
undo_redo->commit_action();
} else if (select_single_attempt != IntPair(-1, -1)) {
selection.clear();
set_animation_and_track(animation, select_single_attempt.first, read_only);
_select_at_anim(animation, select_single_attempt.first, animation->track_get_key_time(select_single_attempt.first, select_single_attempt.second), true);
}
moving_selection = false;
moving_selection_attempt = false;
moving_inserted_key = false;
moving_selection_mouse_begin = Point2();
queue_redraw();
}
}
if (scaling_selection && mb.is_valid() && !read_only && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) {
if (std::abs(scaling_selection_scale.x - 1) > CMP_EPSILON || std::abs(scaling_selection_scale.y - 1) > CMP_EPSILON) {
// Scale it.
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
undo_redo->create_action(TTR("Scale Bezier Points"));
List<AnimMoveRestore> to_restore;
List<Animation::HandleMode> to_restore_handle_modes;
// 1 - Remove the keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->get().first, E->get().second);
}
// 2 - Remove overlapped keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t newtime = animation->track_get_key_time(E->get().first, E->get().second);
newtime += -scaling_selection_offset.x + (newtime - scaling_selection_pivot.x<|fim_middle|>{
real_t oldpos = animation->track_get_key_time(E->get().first, E->get().second);
|
handle_mode,
handle_set_mode);
}
// 4 - (undo) Remove inserted keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t newpos = animation->track_get_key_time(E->get().first, E->get().second) + moving_selection_offset.x;
undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_time", E->get().first, newpos);
}
// 5 - (undo) Reinsert keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t oldpos = animation->track_get_key_time(E->get().first, E->get().second);
Array key = animation->track_get_key_value(E->get().first, E->get().second);
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
E->get().first,
oldpos,
key[0],
Vector2(key[1], key[2]),
Vector2(key[3], key[4]),
animation->bezier_track_get_key_handle_mode(E->get().first, E->get().second));
}
// 6 - (undo) Reinsert overlapped keys.
List<AnimMoveRestore>::ConstIterator restore_itr = to_restore.begin();
List<Animation::HandleMode>::ConstIterator handle_itr = to_restore_handle_modes.begin();
for (; restore_itr != to_restore.end() && handle_itr != to_restore_handle_modes.end(); ++restore_itr, ++handle_itr) {
const AnimMoveRestore &amr = *restore_itr;
Array key = amr.key;
undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, 1);
undo_redo->add_undo_method(
this,
"_bezier_track_insert_key_at_anim",
animation,
amr.track,
amr.time,
key[0],
Vector2(key[1], key[2]),
Vector2(key[3], key[4]),
*handle_itr);
}
undo_redo->add_do_method(this, "_clear_selection_for_anim", animation);
undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation);
// 7 - Reselect.
int i = 0;
for (SelectionSet::Element *E = selection.back(); E; E = E->prev())
|
{
real_t oldpos = animation->track_get_key_time(E->get().first, E->get().second);
|
real_t newpos = oldpos + moving_selection_offset.x;
undo_redo->add_do_method(this, "_select_at_anim", animation, E->get().first, newpos, i == 0);
undo_redo->add_undo_method(this, "_select_at_anim", animation, E->get().first, oldpos, i == 0);
i++;
}
AnimationPlayerEditor *ape = AnimationPlayerEditor::get_singleton();
if (ape) {
undo_redo->add_do_method(ape, "_animation_update_key_frame");
undo_redo->add_undo_method(ape, "_animation_update_key_frame");
}
undo_redo->commit_action();
} else if (select_single_attempt != IntPair(-1, -1)) {
selection.clear();
set_animation_and_track(animation, select_single_attempt.first, read_only);
_select_at_anim(animation, select_single_attempt.first, animation->track_get_key_time(select_single_attempt.first, select_single_attempt.second), true);
}
moving_selection = false;
moving_selection_attempt = false;
moving_inserted_key = false;
moving_selection_mouse_begin = Point2();
queue_redraw();
}
}
if (scaling_selection && mb.is_valid() && !read_only && !mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) {
if (std::abs(scaling_selection_scale.x - 1) > CMP_EPSILON || std::abs(scaling_selection_scale.y - 1) > CMP_EPSILON) {
// Scale it.
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
undo_redo->create_action(TTR("Scale Bezier Points"));
List<AnimMoveRestore> to_restore;
List<Animation::HandleMode> to_restore_handle_modes;
// 1 - Remove the keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->get().first, E->get().second);
}
// 2 - Remove overlapped keys.
for (SelectionSet::Element *E = selection.back(); E; E = E->prev()) {
real_t newtime = animation->track_get_key_time(E->get().first, E->get().second);
newtime += -scaling_selection_offset.x + (newtime - scaling_selection_pivot.x
|
ast_based
|
<|fim_prefix|>
lc.a *= 0.5;
draw_line(Point2(limit, i), Point2(right_limit, i), lc, Math::round(EDSCALE));
Color c = color;
c.a *= 0.5;
draw_string(font, Point2(limit + 8, i - 2), TS->format_number(rtos(Math::snapped((iv + 1) * scale, step))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, c);
}
first = false;
prev_iv = iv;
}
}
// Draw other curves.
{
float scale = timeline->get_zoom_scale();
Ref<Texture2D> point = get_editor_theme_icon(SNAME("KeyValue"));
for (const KeyValue<int, Color> &E : subtrack_colors) {
if (hidden_tracks.has(E.key)) {
continue;
}
_draw_track(E.key, E.value);
for (int i = 0; i < animation->track_get_key_count(E.key); i++) {
float offset = animation->track_get_key_time(E.key, i);
float value = animation->bezier_track_get_key_value(E.key, i);
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
if (pos.x >= limit && pos.x <= right_limit) {
draw_texture(point, pos - point->get_size() / 2.0, E.value);
}
}
}
if (track_count > 0 && !hidden_tracks.has(selected_track)) {
// Draw edited curve.
_draw_track(selected_track, selected_track_color);
}
}
const bool draw_selection_handles = selection.size() > 1;
LocalVector<Point2> selected_pos;
// Draw editor handles.
{
edit_points.clear();
float scale = timeline->get_zoom_scale();
for (int i = 0; i < track_count; ++i) {
bool draw_track = _is_track_curves_displayed(i) && !locked_tracks.has(i);
if (!draw_selection_handles && !draw_track) {
continue;
}
int key_count = animation->track_get_key_count(i);
for (int j = 0; j < key_count; ++j) {
float offset = animation->track_get_key_time(i, j);
float value = animation->bezier_track_get_key_value(i, j);
bool is_selected = selection.has(IntPair(i, j));
if (is_selected) {
if (moving_selection) <|fim_suffix|>
} else if (scaling_selection) {
offset += -scaling_selection_offset.x + (offset - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
value += -scaling_selection_offset.y + (value - scaling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
}
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
if (draw_selection_handles && is_selected) {
selected_pos.push_back(pos);
}
if (!draw_track) {
continue;
}
Vector2 in_vec = animation->bezier_track_get_key_in_handle(i, j);
Vector2 out_vec = animation->bezier_track_get_key_out_handle(i, j);
if ((moving_handle == 1 || moving_handle == -1) && moving_handle_track == i && moving_handle_key == j) {
in_vec = moving_handle_left;
}
if ((moving_handle == 1 || moving_handle == -1) && moving_handle_track == i && moving_handle_key == j) {
out_vec = moving_handle_right;
}
if (moving_inserted_key && moving_selection_from_key == j) {
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(i, j);
if (handle_mode != Animation::HANDLE_MODE_FREE) {
int key_prev = 0;
int key_next = moving_selection_from_key;
for (int k = 0; k < key_count; k++) {
if (k == moving_selection_from_key) {
continue;
}
if (animation->track_get_key_time(i, k) < offset) {
key_prev = k;
} else {
key_next = k;
break;
}
}
float prev_time = offset;
float prev_value = value;
if (key_prev != moving_selection_from_key) {
prev_time = animation->track_get_key_time(i, key_prev);
prev_value = animation->bezier_track_get_key_value(i, key_prev);
}
float next_time = offset;
float next_value = value;
if (key_next != moving_selection_from_key) {
next_time = a<|fim_middle|>{
offset += moving_selection_offset.x;
value += moving_selection_offset.y;
|
lc.a *= 0.5;
draw_line(Point2(limit, i), Point2(right_limit, i), lc, Math::round(EDSCALE));
Color c = color;
c.a *= 0.5;
draw_string(font, Point2(limit + 8, i - 2), TS->format_number(rtos(Math::snapped((iv + 1) * scale, step))), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, c);
}
first = false;
prev_iv = iv;
}
}
// Draw other curves.
{
float scale = timeline->get_zoom_scale();
Ref<Texture2D> point = get_editor_theme_icon(SNAME("KeyValue"));
for (const KeyValue<int, Color> &E : subtrack_colors) {
if (hidden_tracks.has(E.key)) {
continue;
}
_draw_track(E.key, E.value);
for (int i = 0; i < animation->track_get_key_count(E.key); i++) {
float offset = animation->track_get_key_time(E.key, i);
float value = animation->bezier_track_get_key_value(E.key, i);
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
if (pos.x >= limit && pos.x <= right_limit) {
draw_texture(point, pos - point->get_size() / 2.0, E.value);
}
}
}
if (track_count > 0 && !hidden_tracks.has(selected_track)) {
// Draw edited curve.
_draw_track(selected_track, selected_track_color);
}
}
const bool draw_selection_handles = selection.size() > 1;
LocalVector<Point2> selected_pos;
// Draw editor handles.
{
edit_points.clear();
float scale = timeline->get_zoom_scale();
for (int i = 0; i < track_count; ++i) {
bool draw_track = _is_track_curves_displayed(i) && !locked_tracks.has(i);
if (!draw_selection_handles && !draw_track) {
continue;
}
int key_count = animation->track_get_key_count(i);
for (int j = 0; j < key_count; ++j) {
float offset = animation->track_get_key_time(i, j);
float value = animation->bezier_track_get_key_value(i, j);
bool is_selected = selection.has(IntPair(i, j));
if (is_selected) {
if (moving_selection)
|
{
offset += moving_selection_offset.x;
value += moving_selection_offset.y;
|
} else if (scaling_selection) {
offset += -scaling_selection_offset.x + (offset - scaling_selection_pivot.x) * (scaling_selection_scale.x - 1);
value += -scaling_selection_offset.y + (value - scaling_selection_pivot.y) * (scaling_selection_scale.y - 1);
}
}
Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value));
if (draw_selection_handles && is_selected) {
selected_pos.push_back(pos);
}
if (!draw_track) {
continue;
}
Vector2 in_vec = animation->bezier_track_get_key_in_handle(i, j);
Vector2 out_vec = animation->bezier_track_get_key_out_handle(i, j);
if ((moving_handle == 1 || moving_handle == -1) && moving_handle_track == i && moving_handle_key == j) {
in_vec = moving_handle_left;
}
if ((moving_handle == 1 || moving_handle == -1) && moving_handle_track == i && moving_handle_key == j) {
out_vec = moving_handle_right;
}
if (moving_inserted_key && moving_selection_from_key == j) {
Animation::HandleMode handle_mode = animation->bezier_track_get_key_handle_mode(i, j);
if (handle_mode != Animation::HANDLE_MODE_FREE) {
int key_prev = 0;
int key_next = moving_selection_from_key;
for (int k = 0; k < key_count; k++) {
if (k == moving_selection_from_key) {
continue;
}
if (animation->track_get_key_time(i, k) < offset) {
key_prev = k;
} else {
key_next = k;
break;
}
}
float prev_time = offset;
float prev_value = value;
if (key_prev != moving_selection_from_key) {
prev_time = animation->track_get_key_time(i, key_prev);
prev_value = animation->bezier_track_get_key_value(i, key_prev);
}
float next_time = offset;
float next_value = value;
if (key_next != moving_selection_from_key) {
next_time = a
|
ast_based
|
<|fim_prefix|>
// set tensor data
{
llama_file gguf_file(path_lora, "rb");
std::vector<uint8_t> read_buf;
auto set_tensor = [&](ggml_tensor * orig, ggml_tensor * dev) {
size_t offs = gguf_get_data_offset(ctx_gguf.get()) + gguf_get_tensor_offset(ctx_gguf.get(), gguf_find_tensor(ctx_gguf.get(), orig->name));
size_t size = ggml_nbytes(orig);
read_buf.resize(size);
gguf_file.seek(offs, SEEK_SET);
gguf_file.read_raw(read_buf.data(), size);
ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
};
for (auto & it : adapter.ab_map) {
auto orig = ab_map[it.first];
auto dev = it.second;
set_tensor(orig.a, dev.a);
set_tensor(orig.b, dev.b);
}
}
LLAMA_LOG_INFO("%s: loaded %zu tensors from lora file\n", __func__, adapter.ab_map.size()*2);
}
llama_adapter_lora * llama_adapter_lora_init(llama_model * model, const char * path_lora) {
llama_adapter_lora * adapter = new llama_adapter_lora();
try {
llama_adapter_lora_init_impl(*model, path_lora, *adapter);
return adapter;
} catch (const std::exception & err) {
LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
delete adapter;
}
return nullptr;
}
int32_t llama_adapter_meta_val_str(const llama_adapter_lora * adapter, const char * key, char * buf, size_t buf_size) {
const auto & it = adapter->gguf_kv.find(key);
if (it == adapter->gguf_kv.end()) {
if (buf_size > 0) {
buf[0] = '\0';
}
return -1;
}
return snprintf(buf, buf_size, "%s", it->second.c_str());
}
int32_t llama_adapter_meta_count(const llama_adapter_lora * adapter) {
return (int)adapter->gguf_kv.size();
}
int32_t llama_adapter_meta_key_by_index(const llama_adapter_lora * adapter, int i, char * buf, size_t buf_size) {
if (i < 0 || i >= (int)adapter->gguf_kv.size()) <|fim_suffix|>
auto it = adapter->gguf_kv.begin();
std::advance(it, i);
return snprintf(buf, buf_size, "%s", it->first.c_str());
}
int32_t llama_adapter_meta_val_str_by_index(const llama_adapter_lora * adapter, int32_t i, char * buf, size_t buf_size) {
if (i < 0 || i >= (int)adapter->gguf_kv.size()) {
if (buf_size > 0) {
buf[0] = '\0';
}
return -1;
}
auto it = adapter->gguf_kv.begin();
std::advance(it, i);
return snprintf(buf, buf_size, "%s", it->second.c_str());
}
void llama_adapter_lora_free(llama_adapter_lora * adapter) {
delete adapter;
}
uint64_t llama_adapter_get_alora_n_invocation_tokens(const struct llama_adapter_lora * adapter) {
if (!adapter) {
return 0;
}
return adapter->alora_invocation_tokens.size();
}
const llama_token * llama_adapter_get_alora_invocation_tokens(const llama_adapter_lora * adapter) {
GGML_ASSERT(adapter);
return adapter->alora_invocation_tokens.data();
}
<|fim_middle|>{
if (buf_size > 0) {
buf[0] = '\0';
}
return -1;
}
|
// set tensor data
{
llama_file gguf_file(path_lora, "rb");
std::vector<uint8_t> read_buf;
auto set_tensor = [&](ggml_tensor * orig, ggml_tensor * dev) {
size_t offs = gguf_get_data_offset(ctx_gguf.get()) + gguf_get_tensor_offset(ctx_gguf.get(), gguf_find_tensor(ctx_gguf.get(), orig->name));
size_t size = ggml_nbytes(orig);
read_buf.resize(size);
gguf_file.seek(offs, SEEK_SET);
gguf_file.read_raw(read_buf.data(), size);
ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
};
for (auto & it : adapter.ab_map) {
auto orig = ab_map[it.first];
auto dev = it.second;
set_tensor(orig.a, dev.a);
set_tensor(orig.b, dev.b);
}
}
LLAMA_LOG_INFO("%s: loaded %zu tensors from lora file\n", __func__, adapter.ab_map.size()*2);
}
llama_adapter_lora * llama_adapter_lora_init(llama_model * model, const char * path_lora) {
llama_adapter_lora * adapter = new llama_adapter_lora();
try {
llama_adapter_lora_init_impl(*model, path_lora, *adapter);
return adapter;
} catch (const std::exception & err) {
LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
delete adapter;
}
return nullptr;
}
int32_t llama_adapter_meta_val_str(const llama_adapter_lora * adapter, const char * key, char * buf, size_t buf_size) {
const auto & it = adapter->gguf_kv.find(key);
if (it == adapter->gguf_kv.end()) {
if (buf_size > 0) {
buf[0] = '\0';
}
return -1;
}
return snprintf(buf, buf_size, "%s", it->second.c_str());
}
int32_t llama_adapter_meta_count(const llama_adapter_lora * adapter) {
return (int)adapter->gguf_kv.size();
}
int32_t llama_adapter_meta_key_by_index(const llama_adapter_lora * adapter, int i, char * buf, size_t buf_size) {
if (i < 0 || i >= (int)adapter->gguf_kv.size())
|
{
if (buf_size > 0) {
buf[0] = '\0';
}
return -1;
}
|
auto it = adapter->gguf_kv.begin();
std::advance(it, i);
return snprintf(buf, buf_size, "%s", it->first.c_str());
}
int32_t llama_adapter_meta_val_str_by_index(const llama_adapter_lora * adapter, int32_t i, char * buf, size_t buf_size) {
if (i < 0 || i >= (int)adapter->gguf_kv.size()) {
if (buf_size > 0) {
buf[0] = '\0';
}
return -1;
}
auto it = adapter->gguf_kv.begin();
std::advance(it, i);
return snprintf(buf, buf_size, "%s", it->second.c_str());
}
void llama_adapter_lora_free(llama_adapter_lora * adapter) {
delete adapter;
}
uint64_t llama_adapter_get_alora_n_invocation_tokens(const struct llama_adapter_lora * adapter) {
if (!adapter) {
return 0;
}
return adapter->alora_invocation_tokens.size();
}
const llama_token * llama_adapter_get_alora_invocation_tokens(const llama_adapter_lora * adapter) {
GGML_ASSERT(adapter);
return adapter->alora_invocation_tokens.data();
}
|
ast_based
|
End of preview. Expand
in Data Studio
fim-dataset
A Fill-in-the-Middle (FIM) dataset for code autocompletion.
Dataset Description
This dataset is designed for training code autocompletion models using the Fill-in-the-Middle (FIM) approach. The dataset contains code snippets formatted with FIM special tokens:
<fim_prefix>: Code before the completion point<fim_suffix>: Code after the completion point<fim_middle>: The code to be completed
Dataset Structure
Data Fields
text: The formatted FIM instruction containing prefix, suffix, and middle tokens
Data Splits
| Split | Examples |
|---|---|
| train | 42,922 |
| validation | 2,259 |
Usage
from datasets import load_dataset
# Load the dataset
dataset = load_dataset("KrzTyb/fim-dataset")
# Access train and validation splits
train_data = dataset["train"]
val_data = dataset["validation"]
# Example: Print first training example
print(train_data[0]["text"])
Training
This dataset can be used to fine-tune code language models for autocompletion:
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer
from datasets import load_dataset
# Load model and tokenizer
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-Coder-0.5B")
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-Coder-0.5B")
# Add FIM tokens
fim_tokens = ["<fim_prefix>", "<fim_suffix>", "<fim_middle>", "<fim_pad>"]
tokenizer.add_special_tokens({"additional_special_tokens": fim_tokens})
model.resize_token_embeddings(len(tokenizer))
# Load dataset
dataset = load_dataset("KrzTyb/fim-dataset")
# Train (see full training script for details)
trainer = Trainer(
model=model,
train_dataset=dataset["train"],
eval_dataset=dataset["validation"],
# ... other training arguments
)
trainer.train()
Citation
If you use this dataset, please cite:
@dataset{KrzTyb_fim-dataset},
title={fim-dataset},
author={Dataset Creator},
year={2025},
publisher={Hugging Face},
howpublished={\url{https://huggingface.co/datasets/KrzTyb/fim-dataset}}
}
License
Please specify the license for your dataset.
- Downloads last month
- 21