repo_id stringlengths 6 101 | file_path stringlengths 2 269 | content stringlengths 367 5.14M | size int64 367 5.14M | filename stringlengths 1 248 | ext stringlengths 0 87 | lang stringclasses 88 values | program_lang stringclasses 232 values | doc_type stringclasses 5 values | quality_signal stringlengths 2 1.9k | effective stringclasses 2 values | hit_map stringlengths 2 1.4k |
|---|---|---|---|---|---|---|---|---|---|---|---|
0015/esp_rlottie | rlottie/src/lottie/rapidjson/error/en.h | // Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// 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 RAPIDJSON_ERROR_EN_H_
#define RAPIDJSON_ERROR_EN_H_
#include "error.h"
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(switch-enum)
RAPIDJSON_DIAG_OFF(covered-switch-default)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Maps error code of parsing into error message.
/*!
\ingroup RAPIDJSON_ERRORS
\param parseErrorCode Error code obtained in parsing.
\return the error message.
\note User can make a copy of this function for localization.
Using switch-case is safer for future modification of error codes.
*/
inline const RAPIDJSON_ERROR_CHARTYPE* GetParseError_En(ParseErrorCode parseErrorCode) {
switch (parseErrorCode) {
case kParseErrorNone: return RAPIDJSON_ERROR_STRING("No error.");
case kParseErrorDocumentEmpty: return RAPIDJSON_ERROR_STRING("The document is empty.");
case kParseErrorDocumentRootNotSingular: return RAPIDJSON_ERROR_STRING("The document root must not be followed by other values.");
case kParseErrorValueInvalid: return RAPIDJSON_ERROR_STRING("Invalid value.");
case kParseErrorObjectMissName: return RAPIDJSON_ERROR_STRING("Missing a name for object member.");
case kParseErrorObjectMissColon: return RAPIDJSON_ERROR_STRING("Missing a colon after a name of object member.");
case kParseErrorObjectMissCommaOrCurlyBracket: return RAPIDJSON_ERROR_STRING("Missing a comma or '}' after an object member.");
case kParseErrorArrayMissCommaOrSquareBracket: return RAPIDJSON_ERROR_STRING("Missing a comma or ']' after an array element.");
case kParseErrorStringUnicodeEscapeInvalidHex: return RAPIDJSON_ERROR_STRING("Incorrect hex digit after \\u escape in string.");
case kParseErrorStringUnicodeSurrogateInvalid: return RAPIDJSON_ERROR_STRING("The surrogate pair in string is invalid.");
case kParseErrorStringEscapeInvalid: return RAPIDJSON_ERROR_STRING("Invalid escape character in string.");
case kParseErrorStringMissQuotationMark: return RAPIDJSON_ERROR_STRING("Missing a closing quotation mark in string.");
case kParseErrorStringInvalidEncoding: return RAPIDJSON_ERROR_STRING("Invalid encoding in string.");
case kParseErrorNumberTooBig: return RAPIDJSON_ERROR_STRING("Number too big to be stored in double.");
case kParseErrorNumberMissFraction: return RAPIDJSON_ERROR_STRING("Miss fraction part in number.");
case kParseErrorNumberMissExponent: return RAPIDJSON_ERROR_STRING("Miss exponent in number.");
case kParseErrorTermination: return RAPIDJSON_ERROR_STRING("Terminate parsing due to Handler error.");
case kParseErrorUnspecificSyntaxError: return RAPIDJSON_ERROR_STRING("Unspecific syntax error.");
default: return RAPIDJSON_ERROR_STRING("Unknown error.");
}
}
RAPIDJSON_NAMESPACE_END
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_ERROR_EN_H_
| 3,870 | en | h | en | c | code | {"qsc_code_num_words": 431, "qsc_code_num_chars": 3870.0, "qsc_code_mean_word_length": 6.35962877, "qsc_code_frac_words_unique": 0.44083527, "qsc_code_frac_chars_top_2grams": 0.11747537, "qsc_code_frac_chars_top_3grams": 0.13863553, "qsc_code_frac_chars_top_4grams": 0.18022619, "qsc_code_frac_chars_dupe_5grams": 0.16782196, "qsc_code_frac_chars_dupe_6grams": 0.09923386, "qsc_code_frac_chars_dupe_7grams": 0.03502371, "qsc_code_frac_chars_dupe_8grams": 0.03502371, "qsc_code_frac_chars_dupe_9grams": 0.03502371, "qsc_code_frac_chars_dupe_10grams": 0.03502371, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00196399, "qsc_code_frac_chars_whitespace": 0.21059432, "qsc_code_size_file_byte": 3870.0, "qsc_code_num_lines": 74.0, "qsc_code_num_chars_line_max": 146.0, "qsc_code_num_chars_line_mean": 52.2972973, "qsc_code_frac_chars_alphabet": 0.89525368, "qsc_code_frac_chars_comments": 0.27286822, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.13513514, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.22672353, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.56756757, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 1.0, "qsc_codec_score_lines_no_logic": 0.59459459, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 1, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 1, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/rapidjson/error/error.h | // Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// 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 RAPIDJSON_ERROR_ERROR_H_
#define RAPIDJSON_ERROR_ERROR_H_
#include "../rapidjson.h"
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(padded)
#endif
/*! \file error.h */
/*! \defgroup RAPIDJSON_ERRORS RapidJSON error handling */
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_ERROR_CHARTYPE
//! Character type of error messages.
/*! \ingroup RAPIDJSON_ERRORS
The default character type is \c char.
On Windows, user can define this macro as \c TCHAR for supporting both
unicode/non-unicode settings.
*/
#ifndef RAPIDJSON_ERROR_CHARTYPE
#define RAPIDJSON_ERROR_CHARTYPE char
#endif
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_ERROR_STRING
//! Macro for converting string literial to \ref RAPIDJSON_ERROR_CHARTYPE[].
/*! \ingroup RAPIDJSON_ERRORS
By default this conversion macro does nothing.
On Windows, user can define this macro as \c _T(x) for supporting both
unicode/non-unicode settings.
*/
#ifndef RAPIDJSON_ERROR_STRING
#define RAPIDJSON_ERROR_STRING(x) x
#endif
RAPIDJSON_NAMESPACE_BEGIN
///////////////////////////////////////////////////////////////////////////////
// ParseErrorCode
//! Error code of parsing.
/*! \ingroup RAPIDJSON_ERRORS
\see GenericReader::Parse, GenericReader::GetParseErrorCode
*/
enum ParseErrorCode {
kParseErrorNone = 0, //!< No error.
kParseErrorDocumentEmpty, //!< The document is empty.
kParseErrorDocumentRootNotSingular, //!< The document root must not follow by other values.
kParseErrorValueInvalid, //!< Invalid value.
kParseErrorObjectMissName, //!< Missing a name for object member.
kParseErrorObjectMissColon, //!< Missing a colon after a name of object member.
kParseErrorObjectMissCommaOrCurlyBracket, //!< Missing a comma or '}' after an object member.
kParseErrorArrayMissCommaOrSquareBracket, //!< Missing a comma or ']' after an array element.
kParseErrorStringUnicodeEscapeInvalidHex, //!< Incorrect hex digit after \\u escape in string.
kParseErrorStringUnicodeSurrogateInvalid, //!< The surrogate pair in string is invalid.
kParseErrorStringEscapeInvalid, //!< Invalid escape character in string.
kParseErrorStringMissQuotationMark, //!< Missing a closing quotation mark in string.
kParseErrorStringInvalidEncoding, //!< Invalid encoding in string.
kParseErrorNumberTooBig, //!< Number too big to be stored in double.
kParseErrorNumberMissFraction, //!< Miss fraction part in number.
kParseErrorNumberMissExponent, //!< Miss exponent in number.
kParseErrorTermination, //!< Parsing was terminated.
kParseErrorUnspecificSyntaxError //!< Unspecific syntax error.
};
//! Result of parsing (wraps ParseErrorCode)
/*!
\ingroup RAPIDJSON_ERRORS
\code
Document doc;
ParseResult ok = doc.Parse("[42]");
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
exit(EXIT_FAILURE);
}
\endcode
\see GenericReader::Parse, GenericDocument::Parse
*/
struct ParseResult {
//!! Unspecified boolean type
typedef bool (ParseResult::*BooleanType)() const;
public:
//! Default constructor, no error.
ParseResult() : code_(kParseErrorNone), offset_(0) {}
//! Constructor to set an error.
ParseResult(ParseErrorCode code, size_t offset) : code_(code), offset_(offset) {}
//! Get the error code.
ParseErrorCode Code() const { return code_; }
//! Get the error offset, if \ref IsError(), 0 otherwise.
size_t Offset() const { return offset_; }
//! Explicit conversion to \c bool, returns \c true, iff !\ref IsError().
operator BooleanType() const { return !IsError() ? &ParseResult::IsError : NULL; }
//! Whether the result is an error.
bool IsError() const { return code_ != kParseErrorNone; }
bool operator==(const ParseResult& that) const { return code_ == that.code_; }
bool operator==(ParseErrorCode code) const { return code_ == code; }
friend bool operator==(ParseErrorCode code, const ParseResult & err) { return code == err.code_; }
bool operator!=(const ParseResult& that) const { return !(*this == that); }
bool operator!=(ParseErrorCode code) const { return !(*this == code); }
friend bool operator!=(ParseErrorCode code, const ParseResult & err) { return err != code; }
//! Reset error code.
void Clear() { Set(kParseErrorNone); }
//! Update error code and offset.
void Set(ParseErrorCode code, size_t offset = 0) { code_ = code; offset_ = offset; }
private:
ParseErrorCode code_;
size_t offset_;
};
//! Function pointer type of GetParseError().
/*! \ingroup RAPIDJSON_ERRORS
This is the prototype for \c GetParseError_X(), where \c X is a locale.
User can dynamically change locale in runtime, e.g.:
\code
GetParseErrorFunc GetParseError = GetParseError_En; // or whatever
const RAPIDJSON_ERROR_CHARTYPE* s = GetParseError(document.GetParseErrorCode());
\endcode
*/
typedef const RAPIDJSON_ERROR_CHARTYPE* (*GetParseErrorFunc)(ParseErrorCode);
RAPIDJSON_NAMESPACE_END
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_ERROR_ERROR_H_
| 6,213 | error | h | en | c | code | {"qsc_code_num_words": 662, "qsc_code_num_chars": 6213.0, "qsc_code_mean_word_length": 6.15558912, "qsc_code_frac_words_unique": 0.38066465, "qsc_code_frac_chars_top_2grams": 0.04466258, "qsc_code_frac_chars_top_3grams": 0.03239264, "qsc_code_frac_chars_top_4grams": 0.02944785, "qsc_code_frac_chars_dupe_5grams": 0.16147239, "qsc_code_frac_chars_dupe_6grams": 0.13104294, "qsc_code_frac_chars_dupe_7grams": 0.1001227, "qsc_code_frac_chars_dupe_8grams": 0.0790184, "qsc_code_frac_chars_dupe_9grams": 0.0790184, "qsc_code_frac_chars_dupe_10grams": 0.06233129, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00241741, "qsc_code_frac_chars_whitespace": 0.2010301, "qsc_code_size_file_byte": 6213.0, "qsc_code_num_lines": 161.0, "qsc_code_num_chars_line_max": 104.0, "qsc_code_num_chars_line_mean": 38.59006211, "qsc_code_frac_chars_alphabet": 0.81849315, "qsc_code_frac_chars_comments": 0.57685498, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.14, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00532522, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.16, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.18, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/OfflineMapDownloader | static/style.css | html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
background-color: #f4f4f4;
}
#app-container {
display: flex;
height: 100%;
width: 100%;
}
#map {
flex: 3;
height: 100%;
z-index: 0;
}
#overlay {
flex: 1;
height: 100%;
max-width: 360px;
min-width: 280px;
background-color: #1e1e1e;
color: #f0f0f0;
padding: 24px 20px;
border-left: 1px solid #333;
box-shadow: -4px 0 12px rgba(0, 0, 0, 0.5);
font-size: 14px;
display: flex;
flex-direction: column;
gap: 12px;
overflow-y: auto;
z-index: 1000;
}
#overlay h3,
#overlay label {
color: #f0f0f0;
}
#overlay input[type="text"],
#overlay input[type="number"],
#overlay input[type="range"],
#overlay select {
width: 100%;
padding: 8px;
border-radius: 6px;
background-color: #2b2b2b;
border: 1px solid #555;
color: #f0f0f0;
box-sizing: border-box;
}
#overlay input[type="radio"] {
accent-color: #007acc;
}
#overlay button {
width: 100%;
padding: 12px;
background-color: #007acc;
color: white;
border: none;
border-radius: 8px;
font-weight: bold;
cursor: pointer;
transition: background-color 0.2s;
}
#overlay button:hover {
background-color: #005fa3;
}
#overlay button:active {
transform: translateY(1px);
}
#overlay input[type="radio"] {
margin-right: 6px;
}
#status {
margin-top: 4px;
font-weight: 500;
color: #ccc;
min-height: 20px;
}
#tile-preview {
background-color: transparent !important;
border: 1px solid #444;
border-radius: 0px !important;
margin-top: 0 !important;
padding: 0 !important;
display: block;
}
#zoom-slider {
margin-top: 4px;
background-color: #2b2b2b;
border-radius: 4px;
padding: 6px 10px;
box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.3);
}
#zoom-slider .noUi-connect {
background: #007acc;
}
#zoom-slider .noUi-handle {
background: #f0f0f0;
border: 2px solid #007acc;
border-radius: 50%;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.4);
}
#prediction {
margin-top: 10px;
font-size: 13px;
font-weight: 500;
color: #bbb;
}
#loading-modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.6);
display: none;
justify-content: center;
align-items: center;
z-index: 2000;
}
#loading-content {
background: white;
padding: 20px 40px;
border-radius: 10px;
text-align: center;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}
.spinner {
width: 32px;
height: 32px;
border: 4px solid #ccc;
border-top: 4px solid #0066cc;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 12px;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
} | 2,718 | style | css | en | css | data | {"qsc_code_num_words": 369, "qsc_code_num_chars": 2718.0, "qsc_code_mean_word_length": 4.72899729, "qsc_code_frac_words_unique": 0.37669377, "qsc_code_frac_chars_top_2grams": 0.01833811, "qsc_code_frac_chars_top_3grams": 0.01719198, "qsc_code_frac_chars_top_4grams": 0.02005731, "qsc_code_frac_chars_dupe_5grams": 0.02292264, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.09493088, "qsc_code_frac_chars_whitespace": 0.20161884, "qsc_code_size_file_byte": 2718.0, "qsc_code_num_lines": 167.0, "qsc_code_num_chars_line_max": 64.0, "qsc_code_num_chars_line_mean": 16.2754491, "qsc_code_frac_chars_alphabet": 0.70921659, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.18055556, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01213682, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_words_unique": 1, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0} |
003random/003Recon | tools/javascript_files_extractor.py | #!/usr/bin/python
import re, requests, sys
input_file = sys.argv[1]
output_file = sys.argv[2]
print("\n-- Extracting javascript files from domains in "+input_file+" with output file, "+output_file+" --\n")
domains_file = open(input_file,'r')
domains = domains_file.read().split('\n')
file = open(output_file,"w+")
black_listed_domains = ["ajax.googleapis.com",
"cdn.optimizely.com",
"googletagmanager.com",
"fontawesome.com"]
for domain in domains:
domain_written = False
i = 0
b_amount = 0
full_domain = ""
if domain != "":
matches = ""
r = ""
regex = r'<script.*src=[\'|"]([^\'"]*)[\'|"]'
try:
r = requests.get("http://"+domain).content
except:
print "[-]Error in http://"+domain
matches = re.findall(regex, r, re.MULTILINE)
for m in matches:
if domain_written != True:
file.write("\n-"+domain+"\n")
domain_written = True
black_listed = False
for b in black_listed_domains:
if b in m:
black_listed = True
if black_listed != True:
if m.startswith("/"):
if m.startswith("//"):
full_domain = "https:"+m
else:
full_domain = "https://"+domain+m
elif m.startswith("http"):
full_domain = m
else:
full_domain = "https://"+domain+"/"+m
else:
b_amount += 1
if black_listed != True:
i += 1
file.write(full_domain+"\n")
print "[+]"+str(i)+" scripts, "+str(b_amount)+" blacklisted in "+domain
else:
print "[-]Domain is invalid " + domain
file.close()
domains_file.close()
print("\n-- Done --")
| 1,593 | javascript_files_extractor | py | en | python | code | {"qsc_code_num_words": 209, "qsc_code_num_chars": 1593.0, "qsc_code_mean_word_length": 4.3492823, "qsc_code_frac_words_unique": 0.34449761, "qsc_code_frac_chars_top_2grams": 0.07260726, "qsc_code_frac_chars_top_3grams": 0.04950495, "qsc_code_frac_chars_top_4grams": 0.03740374, "qsc_code_frac_chars_dupe_5grams": 0.05940594, "qsc_code_frac_chars_dupe_6grams": 0.05940594, "qsc_code_frac_chars_dupe_7grams": 0.05940594, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00492207, "qsc_code_frac_chars_whitespace": 0.23477715, "qsc_code_size_file_byte": 1593.0, "qsc_code_num_lines": 71.0, "qsc_code_num_chars_line_max": 112.0, "qsc_code_num_chars_line_mean": 22.43661972, "qsc_code_frac_chars_alphabet": 0.74077112, "qsc_code_frac_chars_comments": 0.01004394, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.11111111, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.18972081, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 0.0, "qsc_codepython_frac_lines_func_ratio": null, "qsc_codepython_cate_var_zero": null, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.01851852, "qsc_codepython_frac_lines_simplefunc": null, "qsc_codepython_score_lines_no_logic": null, "qsc_codepython_frac_lines_print": 0.09259259} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 1, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
003random/003Recon | tools/error_page_info_check.py | #!/usr/bin/python
import requests, sys
input_file = sys.argv[1]
output_file = sys.argv[2]
payload_file = sys.argv[3]
is_closed = True
domains = open(input_file,'r').read().split('\n')
info = [line.rstrip('\n').lower() for line in open(payload_file)]
print("\n-- Checking for sensitive info in error pages "+input_file+" with output file, "+output_file+" --")
payloads = ["/",
"/NotFound123",
"/.htaccess",
"/<>"]
for payload in payloads:
print "\n - Trying payload "+payload+" - "
for domain in domains:
info_found = ""
if domain != "":
found = False
try:
response = requests.get("http://"+domain+payload)
except:
print("[-]Error on http://"+domain+payload)
for i in info:
if i.lower() in response.content.lower():
found = True
#Search and get the line in the response that contains i.lower()
info_found = [x for x in [x.lower() for x in response.content.split("\n")] if i.lower() in x]
if found:
if is_closed:
file = open(output_file,"w+")
is_closed = False
print("[+]"+domain+payload+" - "+str(info_found))
file.write(domain + payload +" - "+str(info_found)+ "\n")
else:
print("[-]"+domain+payload+" - "+str(info_found))
else:
print("[-]Domain is invalid")
if is_closed == False:
file.close()
print("\n-- Done --")
| 1,614 | error_page_info_check | py | en | python | code | {"qsc_code_num_words": 188, "qsc_code_num_chars": 1614.0, "qsc_code_mean_word_length": 4.26595745, "qsc_code_frac_words_unique": 0.34042553, "qsc_code_frac_chars_top_2grams": 0.05610973, "qsc_code_frac_chars_top_3grams": 0.04114713, "qsc_code_frac_chars_top_4grams": 0.07481297, "qsc_code_frac_chars_dupe_5grams": 0.10598504, "qsc_code_frac_chars_dupe_6grams": 0.07481297, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0056391, "qsc_code_frac_chars_whitespace": 0.34076828, "qsc_code_size_file_byte": 1614.0, "qsc_code_num_lines": 51.0, "qsc_code_num_chars_line_max": 114.0, "qsc_code_num_chars_line_mean": 31.64705882, "qsc_code_frac_chars_alphabet": 0.7481203, "qsc_code_frac_chars_comments": 0.04894672, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.05128205, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.13242009, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 0.0, "qsc_codepython_frac_lines_func_ratio": null, "qsc_codepython_cate_var_zero": null, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.02564103, "qsc_codepython_frac_lines_simplefunc": null, "qsc_codepython_score_lines_no_logic": null, "qsc_codepython_frac_lines_print": 0.17948718} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 1, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
003random/003Recon | tools/open_redirect.py | #!/usr/bin/python
import requests,sys
def start():
input_file = sys.argv[1]
output_file = sys.argv[2]
payload_file = sys.argv[3]
print("\n-- Testing open redirects on domains in "+input_file+" with output file, "+output_file+" --")
is_closed = True
payloads = open(payload_file,'r').read().split('\n')
#First loop trough the payloads to prevent 429 (rate limit)
for payload in payloads:
domains = open(input_file,'r').read().split('\n')
print "\n - Trying payload "+payload+" - "
for domain in domains:
if domain != "":
url = "https://" + domain + payload
url = url.strip()
try:
r = requests.head(url, allow_redirects=True, timeout=5)
if r.history:
if r.url == "https://example.com":
print "[+]"+url
if is_closed:
file = open(output_file,"w+")
is_closed = False
file.write(url + "\n")
else:
print "[-]"+url
else:
print "[-]"+url
except:
print "[-]Error on " + url
else:
print "[-]Domain is invalid"
if is_closed == False:
file.close()
print("\n-- Done --")
start()
| 1,494 | open_redirect | py | en | python | code | {"qsc_code_num_words": 151, "qsc_code_num_chars": 1494.0, "qsc_code_mean_word_length": 4.21192053, "qsc_code_frac_words_unique": 0.43046358, "qsc_code_frac_chars_top_2grams": 0.06289308, "qsc_code_frac_chars_top_3grams": 0.05188679, "qsc_code_frac_chars_top_4grams": 0.04402516, "qsc_code_frac_chars_dupe_5grams": 0.04716981, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0083632, "qsc_code_frac_chars_whitespace": 0.43975904, "qsc_code_size_file_byte": 1494.0, "qsc_code_num_lines": 49.0, "qsc_code_num_chars_line_max": 107.0, "qsc_code_num_chars_line_mean": 30.48979592, "qsc_code_frac_chars_alphabet": 0.75149343, "qsc_code_frac_chars_comments": 0.04953146, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.13888889, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.12491179, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 0.0, "qsc_codepython_frac_lines_func_ratio": null, "qsc_codepython_cate_var_zero": null, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.02777778, "qsc_codepython_frac_lines_simplefunc": null, "qsc_codepython_score_lines_no_logic": null, "qsc_codepython_frac_lines_print": 0.22222222} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 1, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
003random/003Recon | tools/header_scan.py | import requests, sys
input_file = sys.argv[1]
output_file = sys.argv[2]
payload_file = sys.argv[3]
print("\n-- Testing for sensitive info in headers on domains in "+input_file+" with output file, "+output_file+" --\n")
is_closed = True
domains = open(input_file,'r').read().split('\n')
headers = [line.rstrip('\n').lower() for line in open(payload_file)]
for domain in domains:
if domain != "":
try:
r = requests.head("https://"+domain, timeout=5)
except:
print("[-]Error on https://"+domain)
headers_found = []
for header in headers:
current_header = r.headers.get(header.lower())
if current_header != None and "nginx" not in current_header.lower():
headers_found.append(str(current_header))
if headers_found != []:
if is_closed:
file = open(output_file,"w+")
is_closed = False
print("[+]"+domain+" - "+str(headers_found))
file.write(domain+" - "+str(headers_found)+"\n")
else:
print("[-]"+domain+" - "+str(headers_found))
else:
print "[-]Domain is invalid"
if is_closed == False:
file.close()
print("\n-- Done --")
| 1,094 | header_scan | py | en | python | code | {"qsc_code_num_words": 155, "qsc_code_num_chars": 1094.0, "qsc_code_mean_word_length": 4.41290323, "qsc_code_frac_words_unique": 0.37419355, "qsc_code_frac_chars_top_2grams": 0.10526316, "qsc_code_frac_chars_top_3grams": 0.04824561, "qsc_code_frac_chars_top_4grams": 0.09210526, "qsc_code_frac_chars_dupe_5grams": 0.07602339, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00442478, "qsc_code_frac_chars_whitespace": 0.17367459, "qsc_code_size_file_byte": 1094.0, "qsc_code_num_lines": 39.0, "qsc_code_num_chars_line_max": 120.0, "qsc_code_num_chars_line_mean": 28.05128205, "qsc_code_frac_chars_alphabet": 0.75221239, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0625, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.15539305, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 0.0, "qsc_codepython_frac_lines_func_ratio": null, "qsc_codepython_cate_var_zero": null, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.03125, "qsc_codepython_frac_lines_simplefunc": null, "qsc_codepython_score_lines_no_logic": null, "qsc_codepython_frac_lines_print": 0.1875} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 1, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
003random/003Recon | tools/subdomain_takeover_scan.py | #!/usr/bin/python
import requests, sys, dns.resolver
input_file = sys.argv[1]
output_file = sys.argv[2]
is_closed = True
domains = open(input_file,'r').read().split('\n')
take_over_cnames = ["createsend",
"cargocollective",
"cloudfront",
"desk.com",
"fastly.net",
"feedpress.me",
"freshdesk.com",
"github.io",
"helpjuice.com",
"helpscoutdocs.com",
"herokudns.com",
"herokussl.com",
"herokuapp.com",
"pageserve.co",
"pingdom.com",
"amazonaws.com",
"myshopify.com",
"stspg-customer.com",
"sgizmo.com",
"surveygizmo.eu",
"sgizmoca.com",
"sgizmoca.com",
"tictail.com",
"domains.tumblr.com",
"uservoice.com",
"wpengine.com",
"squarespace.com",
"unbounce.com",
"zendesk.com"]
take_over_content = ["<strong>Trying to access your account",
"Use a personal domain name",
"The request could not be satisfied",
"Sorry, We Couldn't Find That Page",
"Fastly error: unknown domain",
"The feed has not been found",
"You can claim it now at",
"Publishing platform",
"There isn't a GitHub Pages site here",
"No settings were found for this company",
"<title>No such app</title>",
"You've Discovered A Missing Link. Our Apologies!",
"Sorry, couldn’t find the status page",
"NoSuchBucket",
"Sorry, this shop is currently unavailable",
"<title>Hosted Status Pages for Your Company</title>",
"data-html-name=\"Header Logo Link\"",
"<title>Oops - We didn't find your site.</title>",
"class=\"MarketplaceHeader__tictailLogo\"",
"Whatever you were looking for doesn't currently exist at this address",
"The requested URL was not found on this server",
"The page you have requested does not exist",
"This UserVoice subdomain is currently available!",
"but is not configured for an account on our platform",
"<title>Help Center Closed | Zendesk</title>"]
print("\n-- Checking possible subdomain take overs in "+input_file+" with output file, "+output_file+" --\n")
for domain in domains:
#Skip first row, lol
if domain != domains[0]:
found_content = False
found_cname = False
try:
r=requests.get("http://"+domain, timeout=5).text
except:
print("[-]Error in http://"+domain)
for content in take_over_content:
if str(content) in r:
found_content = True
try:
cnames = dns.resolver.query(domain, 'CNAME')
for cname in cnames:
for cname_url in take_over_cnames:
if str(cname_url) in str(cname.target):
found_cname = True
if found_cname and found_content:
print("[+]"+domain)
if is_closed:
file = open(output_file,"w+")
is_closed = False
file.write(domain+"\n")
else:
print("[-]"+domain)
except:
print "[-]No cnames for "+domain
if is_closed == False:
file.close()
print("\n-- Done --")
| 2,819 | subdomain_takeover_scan | py | en | python | code | {"qsc_code_num_words": 387, "qsc_code_num_chars": 2819.0, "qsc_code_mean_word_length": 4.72868217, "qsc_code_frac_words_unique": 0.47803618, "qsc_code_frac_chars_top_2grams": 0.02185792, "qsc_code_frac_chars_top_3grams": 0.01202186, "qsc_code_frac_chars_top_4grams": 0.01748634, "qsc_code_frac_chars_dupe_5grams": 0.0, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00176289, "qsc_code_frac_chars_whitespace": 0.19510465, "qsc_code_size_file_byte": 2819.0, "qsc_code_num_lines": 117.0, "qsc_code_num_chars_line_max": 110.0, "qsc_code_num_chars_line_mean": 24.09401709, "qsc_code_frac_chars_alphabet": 0.80475981, "qsc_code_frac_chars_comments": 0.01241575, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.06666667, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.50505415, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 0.0, "qsc_codepython_frac_lines_func_ratio": null, "qsc_codepython_cate_var_zero": null, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.01111111, "qsc_codepython_frac_lines_simplefunc": null, "qsc_codepython_score_lines_no_logic": null, "qsc_codepython_frac_lines_print": 0.06666667} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 1, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
006lp/akashgen-api-go | services/akash.go | package services
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"go.uber.org/zap"
"github.com/006lp/akashgen-api-go/config"
"github.com/006lp/akashgen-api-go/models"
"github.com/006lp/akashgen-api-go/utils"
)
// AkashService handles communication with Akash network API
type AkashService struct {
logger *zap.Logger
client *http.Client
}
// NewAkashService creates a new AkashService instance
func NewAkashService(logger *zap.Logger) *AkashService {
return &AkashService{
logger: logger,
client: &http.Client{Timeout: config.GenerateTimeout},
}
}
// SendGenerateRequest sends a generate request to upstream API
func (s *AkashService) SendGenerateRequest(ctx context.Context, req models.UpstreamGenerateRequest) (string, error) {
body, err := json.Marshal(req)
if err != nil {
return "", fmt.Errorf("failed to marshal request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, "POST", config.UpstreamGenerateURL, bytes.NewBuffer(body))
if err != nil {
return "", fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err := s.client.Do(httpReq)
if err != nil {
return "", fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return "", fmt.Errorf("upstream generate API error: %d, body: %s", resp.StatusCode, string(body))
}
var result models.GenerateJobResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", fmt.Errorf("failed to decode response: %w", err)
}
return result.JobID, nil
}
// PollJobStatus polls the job status until completion
func (s *AkashService) PollJobStatus(ctx context.Context, jobID string) (string, error) {
pollCtx, cancel := context.WithTimeout(ctx, config.MaxPollingDuration)
defer cancel()
ticker := time.NewTicker(config.PollingInterval)
defer ticker.Stop()
for {
select {
case <-pollCtx.Done():
return "", fmt.Errorf("polling timeout exceeded: %w", pollCtx.Err())
case <-ticker.C:
status, err := s.checkJobStatus(ctx, jobID)
if err != nil {
s.logger.Warn("Failed to check job status", zap.Error(err), zap.String("job_id", jobID))
continue
}
s.logger.Debug("Job status checked",
zap.String("job_id", jobID),
zap.String("status", status.Status),
zap.Int("queue_position", status.QueuePosition),
)
switch status.Status {
case "succeeded":
return status.Result, nil
case "failed", "cancelled", "timeout":
return "", fmt.Errorf("job failed with status: %s", status.Status)
case "pending", "waiting":
// Continue polling
default:
s.logger.Warn("Unknown job status", zap.String("status", status.Status))
}
}
}
}
func (s *AkashService) checkJobStatus(ctx context.Context, jobID string) (*models.UpstreamStatusResponse, error) {
url := fmt.Sprintf("%s?ids=%s", config.UpstreamStatusURL, jobID)
req, err := utils.NewHTTPRequest(ctx, "GET", url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create status request: %w", err)
}
client := &http.Client{Timeout: config.StatusTimeout}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to check status: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("status API error: %d, body: %s", resp.StatusCode, string(body))
}
var results []models.UpstreamStatusResponse
if err := json.NewDecoder(resp.Body).Decode(&results); err != nil {
return nil, fmt.Errorf("failed to decode status response: %w", err)
}
if len(results) == 0 {
return nil, fmt.Errorf("no status returned for job_id: %s", jobID)
}
return &results[0], nil
} | 3,796 | akash | go | en | go | code | {"qsc_code_num_words": 495, "qsc_code_num_chars": 3796.0, "qsc_code_mean_word_length": 5.3030303, "qsc_code_frac_words_unique": 0.28686869, "qsc_code_frac_chars_top_2grams": 0.04114286, "qsc_code_frac_chars_top_3grams": 0.032, "qsc_code_frac_chars_top_4grams": 0.04533333, "qsc_code_frac_chars_dupe_5grams": 0.32038095, "qsc_code_frac_chars_dupe_6grams": 0.23047619, "qsc_code_frac_chars_dupe_7grams": 0.19961905, "qsc_code_frac_chars_dupe_8grams": 0.16342857, "qsc_code_frac_chars_dupe_9grams": 0.11580952, "qsc_code_frac_chars_dupe_10grams": 0.08990476, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0034375, "qsc_code_frac_chars_whitespace": 0.15700738, "qsc_code_size_file_byte": 3796.0, "qsc_code_num_lines": 134.0, "qsc_code_num_chars_line_max": 118.0, "qsc_code_num_chars_line_mean": 28.32835821, "qsc_code_frac_chars_alphabet": 0.816875, "qsc_code_frac_chars_comments": 0.0658588, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.11320755, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.2055258, "qsc_code_frac_chars_long_word_length": 0.03270369, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codego_cate_testfile": 0.0, "qsc_codego_frac_lines_func_ratio": 0.03773585, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.20754717, "qsc_codego_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_codego_cate_testfile": 0, "qsc_codego_frac_lines_func_ratio": 0, "qsc_codego_cate_var_zero": 0, "qsc_codego_score_lines_no_logic": 0, "qsc_codego_frac_lines_print": 0} |
006lp/akashgen-api-go | services/image.go | package services
import (
"context"
"fmt"
"io"
"net/http"
"go.uber.org/zap"
"github.com/006lp/akashgen-api-go/config"
"github.com/006lp/akashgen-api-go/utils"
)
// ImageService handles image fetching operations
type ImageService struct {
logger *zap.Logger
client *http.Client
}
// NewImageService creates a new ImageService instance
func NewImageService(logger *zap.Logger) *ImageService {
return &ImageService{
logger: logger,
client: &http.Client{Timeout: config.ImageFetchTimeout},
}
}
// FetchImage fetches the generated image from the upstream server
func (s *ImageService) FetchImage(ctx context.Context, imagePath string) ([]byte, string, error) {
url := config.UpstreamImageBase + imagePath + "&w=2048&q=100"
req, err := utils.NewHTTPRequest(ctx, "GET", url, nil)
if err != nil {
return nil, "", fmt.Errorf("failed to create image request: %w", err)
}
resp, err := s.client.Do(req)
if err != nil {
return nil, "", fmt.Errorf("failed to fetch image: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, "", fmt.Errorf("image fetch error: %d, body: %s", resp.StatusCode, string(body))
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", fmt.Errorf("failed to read image data: %w", err)
}
contentType := resp.Header.Get("Content-Type")
return data, contentType, nil
} | 1,407 | image | go | en | go | code | {"qsc_code_num_words": 190, "qsc_code_num_chars": 1407.0, "qsc_code_mean_word_length": 5.14210526, "qsc_code_frac_words_unique": 0.43157895, "qsc_code_frac_chars_top_2grams": 0.03684749, "qsc_code_frac_chars_top_3grams": 0.04912999, "qsc_code_frac_chars_top_4grams": 0.07369498, "qsc_code_frac_chars_dupe_5grams": 0.15967247, "qsc_code_frac_chars_dupe_6grams": 0.15967247, "qsc_code_frac_chars_dupe_7grams": 0.10440123, "qsc_code_frac_chars_dupe_8grams": 0.10440123, "qsc_code_frac_chars_dupe_9grams": 0.10440123, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01094276, "qsc_code_frac_chars_whitespace": 0.15565032, "qsc_code_size_file_byte": 1407.0, "qsc_code_num_lines": 56.0, "qsc_code_num_chars_line_max": 99.0, "qsc_code_num_chars_line_mean": 25.125, "qsc_code_frac_chars_alphabet": 0.81144781, "qsc_code_frac_chars_comments": 0.12011372, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.07142857, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.20903955, "qsc_code_frac_chars_long_word_length": 0.06214689, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codego_cate_testfile": 0.0, "qsc_codego_frac_lines_func_ratio": 0.04761905, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.23809524, "qsc_codego_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_codego_cate_testfile": 0, "qsc_codego_frac_lines_func_ratio": 0, "qsc_codego_cate_var_zero": 0, "qsc_codego_score_lines_no_logic": 0, "qsc_codego_frac_lines_print": 0} |
007durgesh219/BTGamepad | sdp_record_gamepad.xml | <?xml version="1.0" encoding="UTF-8" ?>
<record>
<attribute id="0x0001">
<sequence>
<uuid value="0x1124" />
</sequence>
</attribute>
<attribute id="0x0004">
<sequence>
<sequence>
<uuid value="0x0100" />
<uint16 value="0x0011" />
</sequence>
<sequence>
<uuid value="0x0011" />
</sequence>
</sequence>
</attribute>
<attribute id="0x0005">
<sequence>
<uuid value="0x1002" />
</sequence>
</attribute>
<attribute id="0x0006">
<sequence>
<uint16 value="0x656e" />
<uint16 value="0x006a" />
<uint16 value="0x0100" />
</sequence>
</attribute>
<attribute id="0x0009">
<sequence>
<sequence>
<uuid value="0x1124" />
<uint16 value="0x0100" />
</sequence>
</sequence>
</attribute>
<attribute id="0x000d">
<sequence>
<sequence>
<sequence>
<uuid value="0x0100" />
<uint16 value="0x0013" />
</sequence>
<sequence>
<uuid value="0x0011" />
</sequence>
</sequence>
</sequence>
</attribute>
<attribute id="0x0100">
<text value="A Virtual Gamepad Controller" />
</attribute>
<attribute id="0x0101">
<text value="Keyboard > BT Gamepad" />
</attribute>
<attribute id="0x0102">
<text value="Durgesh" />
</attribute>
<attribute id="0x0200">
<uint16 value="0x0100" />
</attribute>
<attribute id="0x0201">
<uint16 value="0x0111" />
</attribute>
<attribute id="0x0202">
<uint8 value="0x08" />
</attribute>
<attribute id="0x0203">
<uint8 value="0x00" />
</attribute>
<attribute id="0x0204">
<boolean value="true" />
</attribute>
<attribute id="0x0205">
<boolean value="true" />
</attribute>
<attribute id="0x0206">
<sequence>
<sequence>
<uint8 value="0x22" />
<text encoding="hex" value="05010905a101a103850105091901290215002501950e75018102950175028103a10005010930093115002564750895028102c0c0c0" />
</sequence>
</sequence>
</attribute>
<attribute id="0x0207">
<sequence>
<sequence>
<uint16 value="0x0409" />
<uint16 value="0x0100" />
</sequence>
</sequence>
</attribute>
<attribute id="0x020b">
<uint16 value="0x0100" />
</attribute>
<attribute id="0x020c">
<uint16 value="0x0c80" />
</attribute>
<attribute id="0x020d">
<boolean value="false" />
</attribute>
<attribute id="0x020e">
<boolean value="true" />
</attribute>
<attribute id="0x020f">
<uint16 value="0x0640" />
</attribute>
<attribute id="0x0210">
<uint16 value="0x0320" />
</attribute>
</record>
| 2,455 | sdp_record_gamepad | xml | en | xml | data | {"qsc_code_num_words": 236, "qsc_code_num_chars": 2455.0, "qsc_code_mean_word_length": 6.53389831, "qsc_code_frac_words_unique": 0.27542373, "qsc_code_frac_chars_top_2grams": 0.16407263, "qsc_code_frac_chars_top_3grams": 0.28534371, "qsc_code_frac_chars_top_4grams": 0.14526589, "qsc_code_frac_chars_dupe_5grams": 0.35667964, "qsc_code_frac_chars_dupe_6grams": 0.30220493, "qsc_code_frac_chars_dupe_7grams": 0.18417639, "qsc_code_frac_chars_dupe_8grams": 0.06874189, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.17483903, "qsc_code_frac_chars_whitespace": 0.17759674, "qsc_code_size_file_byte": 2455.0, "qsc_code_num_lines": 113.0, "qsc_code_num_chars_line_max": 143.0, "qsc_code_num_chars_line_mean": 21.72566372, "qsc_code_frac_chars_alphabet": 0.5889054, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 1.0, "qsc_code_frac_lines_dupe_lines": 0.61061947, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.1898167, "qsc_code_frac_chars_long_word_length": 0.04317719, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.11242363, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_words_unique": 1, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 1, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 1, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0} |
007durgesh219/BTGamepad | Gamepad.py | import time
from evdev import *
class Gamepad:
"""docstring for Gamepad"""
def __init__(self):
self.mapping = {}
self.mapping['KEY_A'] = 0
self.mapping['KEY_W'] = 1
self.mapping['KEY_D'] = 2
self.mapping['KEY_X'] = 3
self.mapping['KEY_H'] = 4
self.mapping['KEY_U'] = 5
self.mapping['KEY_K'] = 6
self.mapping['KEY_M'] = 7
self.mapping['KEY_Q'] = 8
self.mapping['KEY_E'] = 9
self.mapping['KEY_R'] = 10
self.mapping['KEY_T'] = 11
self.mapping['KEY_Y'] = 12
self.mapping['KEY_P'] = 13
self.mapping['KEY_I'] = 14
self.mapping['KEY_O'] = 15
self.state = [
0xA1,
0x03,
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,0,0
],
0x00,
0x00,0x00,0x00]
i = 0
while True:
try:
self.dev = InputDevice("/dev/input/event"+str(i))
if "keyboard" in str(self.dev):
break
except Exception, e:
print "Keyboard not found."
break
i += 1
print "keyboard found "+str(self.dev)
def change_state(self, event):
evdev_code = ecodes.KEY[event.code]
if self.mapping.has_key(evdev_code):
if event.value == 1:
self.state[2][self.mapping[evdev_code]] = 1
else:
self.state[2][self.mapping[evdev_code]] = 0
def event_loop(self,bt):
for event in self.dev.read_loop():
if event.type == ecodes.EV_KEY and event.value < 2:
self.change_state(event)
print self.state
bt.sendInput(self.state)
| 1,764 | Gamepad | py | en | python | code | {"qsc_code_num_words": 227, "qsc_code_num_chars": 1764.0, "qsc_code_mean_word_length": 3.64317181, "qsc_code_frac_words_unique": 0.34801762, "qsc_code_frac_chars_top_2grams": 0.26602177, "qsc_code_frac_chars_top_3grams": 0.27085852, "qsc_code_frac_chars_top_4grams": 0.06287787, "qsc_code_frac_chars_dupe_5grams": 0.09189843, "qsc_code_frac_chars_dupe_6grams": 0.09189843, "qsc_code_frac_chars_dupe_7grams": 0.09189843, "qsc_code_frac_chars_dupe_8grams": 0.01934704, "qsc_code_frac_chars_dupe_9grams": 0.01934704, "qsc_code_frac_chars_dupe_10grams": 0.01934704, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.05779817, "qsc_code_frac_chars_whitespace": 0.38208617, "qsc_code_size_file_byte": 1764.0, "qsc_code_num_lines": 69.0, "qsc_code_num_chars_line_max": 64.0, "qsc_code_num_chars_line_mean": 25.56521739, "qsc_code_frac_chars_alphabet": 0.70091743, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.22727273, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.07944732, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.01381693, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 0.0, "qsc_codepython_frac_lines_func_ratio": null, "qsc_codepython_cate_var_zero": null, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.03030303, "qsc_codepython_frac_lines_simplefunc": null, "qsc_codepython_score_lines_no_logic": null, "qsc_codepython_frac_lines_print": 0.04545455} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 1, "qsc_code_frac_chars_top_3grams": 1, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 1, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
007durgesh219/BTGamepad | Bluetooth.py | from bluetooth import *
import dbus # Used to set up the SDP record
class Bluetooth:
"""docstring for Gamepad"""
HOST = 0
PORT = 1
P_CTRL = 17
P_INTR = 19
UUID = "1f16e7c0-b59b-11e3-95d2-0002a5d5c51b"
def __init__(self, sdp, classname, devname):
self.classname = classname
self.devname = devname
self.soccontrol = BluetoothSocket(L2CAP)
self.sockinter = BluetoothSocket(L2CAP)
self.soccontrol.bind(("", Bluetooth.P_CTRL))
self.sockinter.bind(("",Bluetooth.P_INTR))
self.bus = dbus.SystemBus()
try:
self.manager = dbus.Interface(self.bus.get_object("org.bluez", "/"), "org.bluez.Manager")
adapter_path = self.manager.DefaultAdapter()
self.service = dbus.Interface(self.bus.get_object("org.bluez", adapter_path),"org.bluez.Service")
except Exception, e:
sys.exit("Please turn on bluetooth")
try:
fh = open(sdp,"r")
except Exception, e:
sys.exit("Cannot open sdp_record file")
self.service_record = fh.read()
fh.close()
def listen(self):
self.service.handle = self.service.AddRecord(self.service_record)
os.system("sudo hciconfig hci0 class "+self.classname)
os.system("sudo hciconfig hci0 name "+self.devname)
self.soccontrol.listen(1)
self.sockinter.listen(1)
print "waiting for connection"
self.ccontrol, self.cinfo = self.soccontrol.accept()
print "Control channel connected to "+self.cinfo[Bluetooth.HOST]
self.cinter, self.cinfo = self.sockinter.accept()
print "Interrupt channel connected to "+self.cinfo[Bluetooth.HOST]
def sendInput(self, inp):
str_inp = ""
for elem in inp:
if type(elem) is list:
tmp_str = ""
for tmp_elem in elem:
tmp_str += str(tmp_elem)
for i in range(0,len(tmp_str)/8):
if((i+1)*8 >= len(tmp_str)):
str_inp += chr(int(tmp_str[i*8:],2))
else:
str_inp += chr(int(tmp_str[i*8:(i+1)*8],2))
else:
str_inp += chr(elem)
self.cinter.send(str_inp) | 2,282 | Bluetooth | py | en | python | code | {"qsc_code_num_words": 281, "qsc_code_num_chars": 2282.0, "qsc_code_mean_word_length": 4.58362989, "qsc_code_frac_words_unique": 0.38078292, "qsc_code_frac_chars_top_2grams": 0.02795031, "qsc_code_frac_chars_top_3grams": 0.02096273, "qsc_code_frac_chars_top_4grams": 0.0310559, "qsc_code_frac_chars_dupe_5grams": 0.24068323, "qsc_code_frac_chars_dupe_6grams": 0.16614907, "qsc_code_frac_chars_dupe_7grams": 0.15062112, "qsc_code_frac_chars_dupe_8grams": 0.08850932, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02702703, "qsc_code_frac_chars_whitespace": 0.30280456, "qsc_code_size_file_byte": 2282.0, "qsc_code_num_lines": 59.0, "qsc_code_num_chars_line_max": 110.0, "qsc_code_num_chars_line_mean": 38.6779661, "qsc_code_frac_chars_alphabet": 0.78252671, "qsc_code_frac_chars_comments": 0.01270815, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.11111111, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.12314607, "qsc_code_frac_chars_long_word_length": 0.01617978, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 0.0, "qsc_codepython_frac_lines_func_ratio": null, "qsc_codepython_cate_var_zero": null, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.03703704, "qsc_codepython_frac_lines_simplefunc": null, "qsc_codepython_score_lines_no_logic": null, "qsc_codepython_frac_lines_print": 0.05555556} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 1, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
007durgesh219/BTGamepad | sdp_record_kbd.xml | <?xml version="1.0" encoding="UTF-8" ?>
<record>
<attribute id="0x0001">
<sequence>
<uuid value="0x1124" />
</sequence>
</attribute>
<attribute id="0x0004">
<sequence>
<sequence>
<uuid value="0x0100" />
<uint16 value="0x0011" />
</sequence>
<sequence>
<uuid value="0x0011" />
</sequence>
</sequence>
</attribute>
<attribute id="0x0005">
<sequence>
<uuid value="0x1002" />
</sequence>
</attribute>
<attribute id="0x0006">
<sequence>
<uint16 value="0x656e" />
<uint16 value="0x006a" />
<uint16 value="0x0100" />
</sequence>
</attribute>
<attribute id="0x0009">
<sequence>
<sequence>
<uuid value="0x1124" />
<uint16 value="0x0100" />
</sequence>
</sequence>
</attribute>
<attribute id="0x000d">
<sequence>
<sequence>
<sequence>
<uuid value="0x0100" />
<uint16 value="0x0013" />
</sequence>
<sequence>
<uuid value="0x0011" />
</sequence>
</sequence>
</sequence>
</attribute>
<attribute id="0x0100">
<text value="A Virtual Keyboard" />
</attribute>
<attribute id="0x0101">
<text value="Keyboard > BT Keyboard" />
</attribute>
<attribute id="0x0102">
<text value="Durgesh" />
</attribute>
<attribute id="0x0200">
<uint16 value="0x0100" />
</attribute>
<attribute id="0x0201">
<uint16 value="0x0111" />
</attribute>
<attribute id="0x0202">
<uint8 value="0x40" />
</attribute>
<attribute id="0x0203">
<uint8 value="0x00" />
</attribute>
<attribute id="0x0204">
<boolean value="true" />
</attribute>
<attribute id="0x0205">
<boolean value="true" />
</attribute>
<attribute id="0x0206">
<sequence>
<sequence>
<uint8 value="0x22" />
<text encoding="hex" value="05010906a101850175019508050719e029e715002501810295017508810395057501050819012905910295017503910395067508150026ff000507190029ff8100c0050c0901a1018503150025017501950b0a23020a21020ab10109b809b609cd09b509e209ea09e9093081029501750d8103c0" />
</sequence>
</sequence>
</attribute>
<attribute id="0x0207">
<sequence>
<sequence>
<uint16 value="0x0409" />
<uint16 value="0x0100" />
</sequence>
</sequence>
</attribute>
<attribute id="0x020b">
<uint16 value="0x0100" />
</attribute>
<attribute id="0x020c">
<uint16 value="0x0c80" />
</attribute>
<attribute id="0x020d">
<boolean value="false" />
</attribute>
<attribute id="0x020e">
<boolean value="true" />
</attribute>
<attribute id="0x020f">
<uint16 value="0x0640" />
</attribute>
<attribute id="0x0210">
<uint16 value="0x0320" />
</attribute>
</record>
| 2,573 | sdp_record_kbd | xml | en | xml | data | {"qsc_code_num_words": 235, "qsc_code_num_chars": 2573.0, "qsc_code_mean_word_length": 7.06382979, "qsc_code_frac_words_unique": 0.26808511, "qsc_code_frac_chars_top_2grams": 0.15240964, "qsc_code_frac_chars_top_3grams": 0.26506024, "qsc_code_frac_chars_top_4grams": 0.13493976, "qsc_code_frac_chars_dupe_5grams": 0.3313253, "qsc_code_frac_chars_dupe_6grams": 0.28072289, "qsc_code_frac_chars_dupe_7grams": 0.17108434, "qsc_code_frac_chars_dupe_8grams": 0.06385542, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.21525503, "qsc_code_frac_chars_whitespace": 0.169452, "qsc_code_size_file_byte": 2573.0, "qsc_code_num_lines": 114.0, "qsc_code_num_chars_line_max": 269.0, "qsc_code_num_chars_line_mean": 22.57017544, "qsc_code_frac_chars_alphabet": 0.56153486, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 1.0, "qsc_code_frac_lines_dupe_lines": 0.61061947, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.22658375, "qsc_code_frac_chars_long_word_length": 0.09016712, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.10726778, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_words_unique": 1, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 1, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 1, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 1, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0} |
007durgesh219/BTGamepad | keymap.py | # Convert value returned from Linux event device ("evdev") to a HID code. This
# is reverse of what's actually hardcoded in the kernel.
#
# Lubomir Rintel <lkundrak@v3.sk>
# License: GPL
#
# Ported to a Python module by Liam Fraser.
#
keytable = {
"KEY_RESERVED" : 0,
"KEY_ESC" : 41,
"KEY_1" : 30,
"KEY_2" : 31,
"KEY_3" : 32,
"KEY_4" : 33,
"KEY_5" : 34,
"KEY_6" : 35,
"KEY_7" : 36,
"KEY_8" : 37,
"KEY_9" : 38,
"KEY_0" : 39,
"KEY_MINUS" : 45,
"KEY_EQUAL" : 46,
"KEY_BACKSPACE" : 42,
"KEY_TAB" : 43,
"KEY_Q" : 20,
"KEY_W" : 26,
"KEY_E" : 8,
"KEY_R" : 21,
"KEY_T" : 23,
"KEY_Y" : 28,
"KEY_U" : 24,
"KEY_I" : 12,
"KEY_O" : 18,
"KEY_P" : 19,
"KEY_LEFTBRACE" : 47,
"KEY_RIGHTBRACE" : 48,
"KEY_ENTER" : 40,
"KEY_LEFTCTRL" : 224,
"KEY_A" : 4,
"KEY_S" : 22,
"KEY_D" : 7,
"KEY_F" : 9,
"KEY_G" : 10,
"KEY_H" : 11,
"KEY_J" : 13,
"KEY_K" : 14,
"KEY_L" : 15,
"KEY_SEMICOLON" : 51,
"KEY_APOSTROPHE" : 52,
"KEY_GRAVE" : 53,
"KEY_LEFTSHIFT" : 225,
"KEY_BACKSLASH" : 50,
"KEY_Z" : 29,
"KEY_X" : 27,
"KEY_C" : 6,
"KEY_V" : 25,
"KEY_B" : 5,
"KEY_N" : 17,
"KEY_M" : 16,
"KEY_COMMA" : 54,
"KEY_DOT" : 55,
"KEY_SLASH" : 56,
"KEY_RIGHTSHIFT" : 229,
"KEY_KPASTERISK" : 85,
"KEY_LEFTALT" : 226,
"KEY_SPACE" : 44,
"KEY_CAPSLOCK" : 57,
"KEY_F1" : 58,
"KEY_F2" : 59,
"KEY_F3" : 60,
"KEY_F4" : 61,
"KEY_F5" : 62,
"KEY_F6" : 63,
"KEY_F7" : 64,
"KEY_F8" : 65,
"KEY_F9" : 66,
"KEY_F10" : 67,
"KEY_NUMLOCK" : 83,
"KEY_SCROLLLOCK" : 71,
"KEY_KP7" : 95,
"KEY_KP8" : 96,
"KEY_KP9" : 97,
"KEY_KPMINUS" : 86,
"KEY_KP4" : 92,
"KEY_KP5" : 93,
"KEY_KP6" : 94,
"KEY_KPPLUS" : 87,
"KEY_KP1" : 89,
"KEY_KP2" : 90,
"KEY_KP3" : 91,
"KEY_KP0" : 98,
"KEY_KPDOT" : 99,
"KEY_ZENKAKUHANKAKU" : 148,
"KEY_102ND" : 100,
"KEY_F11" : 68,
"KEY_F12" : 69,
"KEY_RO" : 135,
"KEY_KATAKANA" : 146,
"KEY_HIRAGANA" : 147,
"KEY_HENKAN" : 138,
"KEY_KATAKANAHIRAGANA" : 136,
"KEY_MUHENKAN" : 139,
"KEY_KPJPCOMMA" : 140,
"KEY_KPENTER" : 88,
"KEY_RIGHTCTRL" : 228,
"KEY_KPSLASH" : 84,
"KEY_SYSRQ" : 70,
"KEY_RIGHTALT" : 230,
"KEY_HOME" : 74,
"KEY_UP" : 82,
"KEY_PAGEUP" : 75,
"KEY_LEFT" : 80,
"KEY_RIGHT" : 79,
"KEY_END" : 77,
"KEY_DOWN" : 81,
"KEY_PAGEDOWN" : 78,
"KEY_INSERT" : 73,
"KEY_DELETE" : 76,
"KEY_MUTE" : 239,
"KEY_VOLUMEDOWN" : 238,
"KEY_VOLUMEUP" : 237,
"KEY_POWER" : 102,
"KEY_KPEQUAL" : 103,
"KEY_PAUSE" : 72,
"KEY_KPCOMMA" : 133,
"KEY_HANGEUL" : 144,
"KEY_HANJA" : 145,
"KEY_YEN" : 137,
"KEY_LEFTMETA" : 227,
"KEY_RIGHTMETA" : 231,
"KEY_COMPOSE" : 101,
"KEY_STOP" : 243,
"KEY_AGAIN" : 121,
"KEY_PROPS" : 118,
"KEY_UNDO" : 122,
"KEY_FRONT" : 119,
"KEY_COPY" : 124,
"KEY_OPEN" : 116,
"KEY_PASTE" : 125,
"KEY_FIND" : 244,
"KEY_CUT" : 123,
"KEY_HELP" : 117,
"KEY_CALC" : 251,
"KEY_SLEEP" : 248,
"KEY_WWW" : 240,
"KEY_COFFEE" : 249,
"KEY_BACK" : 241,
"KEY_FORWARD" : 242,
"KEY_EJECTCD" : 236,
"KEY_NEXTSONG" : 235,
"KEY_PLAYPAUSE" : 232,
"KEY_PREVIOUSSONG" : 234,
"KEY_STOPCD" : 233,
"KEY_REFRESH" : 250,
"KEY_EDIT" : 247,
"KEY_SCROLLUP" : 245,
"KEY_SCROLLDOWN" : 246,
"KEY_F13" : 104,
"KEY_F14" : 105,
"KEY_F15" : 106,
"KEY_F16" : 107,
"KEY_F17" : 108,
"KEY_F18" : 109,
"KEY_F19" : 110,
"KEY_F20" : 111,
"KEY_F21" : 112,
"KEY_F22" : 113,
"KEY_F23" : 114,
"KEY_F24" : 115
}
# Map modifier keys to array element in the bit array
modkeys = {
"KEY_RIGHTMETA" : 0,
"KEY_RIGHTALT" : 1,
"KEY_RIGHTSHIFT" : 2,
"KEY_RIGHTCTRL" : 3,
"KEY_LEFTMETA" : 4,
"KEY_LEFTALT": 5,
"KEY_LEFTSHIFT": 6,
"KEY_LEFTCTRL": 7
}
def convert(evdev_keycode):
return keytable[evdev_keycode]
def modkey(evdev_keycode):
if evdev_keycode in modkeys:
return modkeys[evdev_keycode]
else:
return -1 # Return an invalid array element
| 4,239 | keymap | py | en | python | code | {"qsc_code_num_words": 586, "qsc_code_num_chars": 4239.0, "qsc_code_mean_word_length": 3.51877133, "qsc_code_frac_words_unique": 0.62457338, "qsc_code_frac_chars_top_2grams": 0.02909796, "qsc_code_frac_chars_top_3grams": 0.0, "qsc_code_frac_chars_top_4grams": 0.0, "qsc_code_frac_chars_dupe_5grams": 0.0, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.15311653, "qsc_code_frac_chars_whitespace": 0.30360934, "qsc_code_size_file_byte": 4239.0, "qsc_code_num_lines": 193.0, "qsc_code_num_chars_line_max": 79.0, "qsc_code_num_chars_line_mean": 21.96373057, "qsc_code_frac_chars_alphabet": 0.54539295, "qsc_code_frac_chars_comments": 0.07124322, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.37187978, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.01111111, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.0, "qsc_codepython_frac_lines_simplefunc": 0.005555555555555556, "qsc_codepython_score_lines_no_logic": 0.02777778, "qsc_codepython_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
007durgesh219/BTGamepad | Keyboard.py | from evdev import *
import keymap
from Bluetooth import *
class Keyboard:
def __init__(self):
self.state = [
0xA1,
0x01,
[
0,
0,
0,
0,
0,
0,
0,
0
],
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00
]
i = 0
while True:
try:
self.dev = InputDevice("/dev/input/event"+str(i))
if "keyboard" in str(self.dev):
break
except Exception, e:
sys.exit("Keyboard not found")
break
i += 1
print "Keyboard Detected "+str(self.dev)
def change_state(self,event):
evdev_code = ecodes.KEY[event.code]
modkey_element = keymap.modkey(evdev_code)
if modkey_element > 0:
if self.state[2][modkey_element] == 0:
self.state[2][modkey_element] = 1
else:
self.state[2][modkey_element] = 0
else:
hex_key = keymap.convert(evdev_code)
for i in range(4,10):
if self.state[i] == hex_key and event.value == 0:
self.state[i] = 0x00
elif self.state[i] == 0x00 and event.value == 1:
self.state[i] = hex_key
break
def event_loop(self,bt):
for event in self.dev.read_loop():
if event.type == ecodes.EV_KEY and event.value < 2:
self.change_state(event)
print self.state
bt.sendInput(self.state)
| 1,749 | Keyboard | py | en | python | code | {"qsc_code_num_words": 185, "qsc_code_num_chars": 1749.0, "qsc_code_mean_word_length": 3.95675676, "qsc_code_frac_words_unique": 0.32432432, "qsc_code_frac_chars_top_2grams": 0.12295082, "qsc_code_frac_chars_top_3grams": 0.02459016, "qsc_code_frac_chars_top_4grams": 0.0273224, "qsc_code_frac_chars_dupe_5grams": 0.18989071, "qsc_code_frac_chars_dupe_6grams": 0.1147541, "qsc_code_frac_chars_dupe_7grams": 0.01092896, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.06037322, "qsc_code_frac_chars_whitespace": 0.47913093, "qsc_code_size_file_byte": 1749.0, "qsc_code_num_lines": 60.0, "qsc_code_num_chars_line_max": 66.0, "qsc_code_num_chars_line_mean": 29.15, "qsc_code_frac_chars_alphabet": 0.74313941, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.30508475, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.03430532, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.02515723, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 0.0, "qsc_codepython_frac_lines_func_ratio": null, "qsc_codepython_cate_var_zero": null, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.05084746, "qsc_codepython_frac_lines_simplefunc": null, "qsc_codepython_score_lines_no_logic": null, "qsc_codepython_frac_lines_print": 0.03389831} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 1, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
000haoji/deep-student | src/components/UnifiedAnalysisView.css | /* UnifiedAnalysisView 组件样式 */
.unified-analysis-loading {
display: flex;
justify-content: center;
align-items: center;
min-height: 400px;
}
.loading-spinner {
font-size: 1.1rem;
color: #6c757d;
}
.unified-analysis-error {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 400px;
padding: 2rem;
}
.error-message {
font-size: 1.2rem;
color: #dc3545;
margin-bottom: 1rem;
}
.error-details {
font-size: 0.9rem;
color: #6c757d;
text-align: center;
}
/* 图片预览容器 */
.image-preview-container {
margin-bottom: 1rem;
padding: 1rem;
border: 2px dashed #e5e7eb;
border-radius: 8px;
background-color: #f9fafb;
}
.image-preview-header {
margin-bottom: 0.75rem;
font-size: 0.9rem;
font-weight: 600;
color: #374151;
}
.image-preview-grid {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
}
.image-preview-item {
position: relative;
width: 120px;
height: 120px;
border-radius: 8px;
overflow: hidden;
border: 2px solid #e5e7eb;
background-color: white;
}
.image-preview-item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.image-preview-info {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: linear-gradient(to top, rgba(0,0,0,0.8), transparent);
padding: 0.5rem;
display: flex;
justify-content: space-between;
align-items: center;
}
.image-name {
font-size: 0.75rem;
color: white;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
margin-right: 0.5rem;
}
.remove-image-btn {
background: rgba(220, 53, 69, 0.8);
color: white;
border: none;
border-radius: 50%;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.75rem;
cursor: pointer;
transition: background-color 0.2s;
}
.remove-image-btn:hover {
background: rgba(220, 53, 69, 1);
}
/* 输入行样式 */
.input-row {
display: flex;
align-items: center;
gap: 0.5rem;
}
.input-row input[type="text"] {
flex: 1;
padding: 0.75rem;
border: 2px solid #e5e7eb;
border-radius: 0.5rem;
font-size: 0.9rem;
transition: border-color 0.2s;
}
.input-row input[type="text"]:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.input-row input[type="text"]:disabled {
background-color: #f3f4f6;
color: #6b7280;
cursor: not-allowed;
}
/* 图片上传按钮 */
.image-upload-btn {
display: flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
background-color: #f3f4f6;
border: 2px solid #d1d5db;
border-radius: 0.5rem;
cursor: pointer;
transition: all 0.2s;
font-size: 1.2rem;
}
.image-upload-btn:hover {
background-color: #e5e7eb;
border-color: #9ca3af;
}
.image-upload-btn:active {
transform: scale(0.95);
}
/* 发送按钮 */
.send-button {
display: flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
background-color: #3b82f6;
color: white;
border: none;
border-radius: 0.5rem;
cursor: pointer;
transition: all 0.2s;
font-size: 1.2rem;
}
.send-button:hover:not(:disabled) {
background-color: #2563eb;
}
.send-button:disabled {
background-color: #9ca3af;
cursor: not-allowed;
}
.send-button:active:not(:disabled) {
transform: scale(0.95);
}
/* 保存按钮行 */
.save-buttons-row {
margin-top: 0.75rem;
padding-top: 0.75rem;
border-top: 1px solid #e5e7eb;
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.save-button-inline {
padding: 0.5rem 1rem;
background-color: #10b981;
color: white;
border: none;
border-radius: 0.375rem;
cursor: pointer;
font-size: 0.875rem;
font-weight: 500;
transition: background-color 0.2s;
}
.save-button-inline:hover:not(:disabled) {
background-color: #059669;
}
.save-button-inline:disabled {
background-color: #9ca3af;
cursor: not-allowed;
opacity: 0.5;
}
/* 保存按钮组 */
.save-buttons-group {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.save-button-primary {
padding: 0.75rem 1rem;
background-color: #10b981;
color: white;
border: none;
border-radius: 0.375rem;
cursor: pointer;
font-size: 0.875rem;
font-weight: 600;
transition: all 0.2s;
}
.save-button-primary:hover:not(:disabled) {
background-color: #059669;
transform: translateY(-1px);
}
.save-button-primary:disabled {
background-color: #9ca3af;
cursor: not-allowed;
opacity: 0.5;
}
.save-button-secondary {
padding: 0.75rem 1rem;
background-color: #6b7280;
color: white;
border: none;
border-radius: 0.375rem;
cursor: pointer;
font-size: 0.875rem;
transition: all 0.2s;
}
.save-button-secondary:hover:not(:disabled) {
background-color: #4b5563;
transform: translateY(-1px);
}
.save-button-secondary:disabled {
background-color: #9ca3af;
cursor: not-allowed;
opacity: 0.5;
}
/* 多模态内容渲染样式 */
.content-text-part {
margin-bottom: 0.5rem;
}
.content-image-part {
margin: 0.5rem 0;
}
.content-image-part img {
max-width: 100%;
max-height: 300px;
display: block;
border-radius: 8px;
border: 1px solid #e5e7eb;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.content-unknown {
padding: 1rem;
background-color: #fef3c7;
border: 1px solid #f59e0b;
border-radius: 0.5rem;
color: #92400e;
font-style: italic;
}
/* 聊天全屏模式 */
.chat-fullscreen .chat-container {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 9999;
background: white;
display: flex;
flex-direction: column;
}
.chat-fullscreen .chat-history {
flex: 1;
overflow-y: auto;
}
/* 响应式设计 */
@media (max-width: 768px) {
.image-preview-grid {
justify-content: center;
}
.image-preview-item {
width: 100px;
height: 100px;
}
.input-row {
flex-wrap: wrap;
}
.input-row input[type="text"] {
min-width: 200px;
}
.save-buttons-group {
width: 100%;
}
.save-button-primary,
.save-button-secondary {
flex: 1;
min-width: 120px;
}
}
/* 动画效果 */
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.image-preview-item {
animation: fadeIn 0.3s ease-out;
}
.content-image-part img {
animation: fadeIn 0.5s ease-out;
}
/* 悬停效果 */
.image-preview-item:hover {
transform: scale(1.05);
transition: transform 0.2s;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
.content-image-part img:hover {
transform: scale(1.02);
transition: transform 0.2s;
cursor: pointer;
} | 6,505 | UnifiedAnalysisView | css | en | css | data | {"qsc_code_num_words": 861, "qsc_code_num_chars": 6505.0, "qsc_code_mean_word_length": 4.92682927, "qsc_code_frac_words_unique": 0.22067364, "qsc_code_frac_chars_top_2grams": 0.07072136, "qsc_code_frac_chars_top_3grams": 0.04879774, "qsc_code_frac_chars_top_4grams": 0.02357379, "qsc_code_frac_chars_dupe_5grams": 0.3960396, "qsc_code_frac_chars_dupe_6grams": 0.29160773, "qsc_code_frac_chars_dupe_7grams": 0.24375295, "qsc_code_frac_chars_dupe_8grams": 0.22206506, "qsc_code_frac_chars_dupe_9grams": 0.21098538, "qsc_code_frac_chars_dupe_10grams": 0.1874116, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.07507109, "qsc_code_frac_chars_whitespace": 0.18908532, "qsc_code_size_file_byte": 6505.0, "qsc_code_num_lines": 386.0, "qsc_code_num_chars_line_max": 69.0, "qsc_code_num_chars_line_mean": 16.85233161, "qsc_code_frac_chars_alphabet": 0.72909953, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.44744745, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00245927, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 1, "qsc_code_mean_word_length": 0, "qsc_code_frac_words_unique": 1, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0} |
000haoji/deep-student | src/components/ImageViewer.tsx | import { useState, useEffect } from 'react';
interface ImageViewerProps {
images: string[];
currentIndex: number;
isOpen: boolean;
onClose: () => void;
onNext?: () => void;
onPrev?: () => void;
}
export const ImageViewer: React.FC<ImageViewerProps> = ({
images,
currentIndex,
isOpen,
onClose,
onNext,
onPrev
}) => {
const [scale, setScale] = useState(1);
const [rotation, setRotation] = useState(0);
const [position, setPosition] = useState({ x: 0, y: 0 });
const [isDragging, setIsDragging] = useState(false);
const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
// 重置状态当图片改变时
useEffect(() => {
setScale(1);
setRotation(0);
setPosition({ x: 0, y: 0 });
}, [currentIndex]);
// 键盘事件处理
useEffect(() => {
if (!isOpen) return;
const handleKeyDown = (e: KeyboardEvent) => {
switch (e.key) {
case 'Escape':
onClose();
break;
case 'ArrowLeft':
onPrev?.();
break;
case 'ArrowRight':
onNext?.();
break;
case '+':
case '=':
setScale(prev => Math.min(prev * 1.2, 5));
break;
case '-':
setScale(prev => Math.max(prev / 1.2, 0.1));
break;
case 'r':
case 'R':
setRotation(prev => (prev + 90) % 360);
break;
case '0':
setScale(1);
setRotation(0);
setPosition({ x: 0, y: 0 });
break;
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [isOpen, onClose, onNext, onPrev]);
const handleMouseDown = (e: React.MouseEvent) => {
setIsDragging(true);
setDragStart({
x: e.clientX - position.x,
y: e.clientY - position.y
});
};
const handleMouseMove = (e: React.MouseEvent) => {
if (!isDragging) return;
setPosition({
x: e.clientX - dragStart.x,
y: e.clientY - dragStart.y
});
};
const handleMouseUp = () => {
setIsDragging(false);
};
const handleWheel = (e: React.WheelEvent) => {
e.preventDefault();
const delta = e.deltaY > 0 ? 0.9 : 1.1;
setScale(prev => Math.max(0.1, Math.min(5, prev * delta)));
};
if (!isOpen || images.length === 0) return null;
const currentImage = images[currentIndex];
return (
<div className="image-viewer-overlay" onClick={onClose}>
<div className="image-viewer-container" onClick={(e) => e.stopPropagation()}>
{/* 工具栏 */}
<div className="image-viewer-toolbar">
<div className="toolbar-left">
<span className="image-counter">
{currentIndex + 1} / {images.length}
</span>
</div>
<div className="toolbar-center">
<button
onClick={() => setScale(prev => Math.max(prev / 1.2, 0.1))}
className="toolbar-button"
title="缩小 (-)"
>
🔍-
</button>
<span className="scale-indicator">{Math.round(scale * 100)}%</span>
<button
onClick={() => setScale(prev => Math.min(prev * 1.2, 5))}
className="toolbar-button"
title="放大 (+)"
>
🔍+
</button>
<button
onClick={() => setRotation(prev => (prev + 90) % 360)}
className="toolbar-button"
title="旋转 (R)"
>
🔄
</button>
<button
onClick={() => {
setScale(1);
setRotation(0);
setPosition({ x: 0, y: 0 });
}}
className="toolbar-button"
title="重置 (0)"
>
🏠
</button>
</div>
<div className="toolbar-right">
<button onClick={onClose} className="close-button" title="关闭 (Esc)">
✕
</button>
</div>
</div>
{/* 图片容器 */}
<div
className="image-viewer-content"
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseUp}
onWheel={handleWheel}
>
<img
src={currentImage}
alt={`图片 ${currentIndex + 1}`}
className="viewer-image"
style={{
transform: `translate(${position.x}px, ${position.y}px) scale(${scale}) rotate(${rotation}deg)`,
cursor: isDragging ? 'grabbing' : 'grab'
}}
draggable={false}
/>
</div>
{/* 导航按钮 */}
{images.length > 1 && (
<>
<button
onClick={onPrev}
className="nav-button nav-prev"
disabled={currentIndex === 0}
title="上一张 (←)"
>
‹
</button>
<button
onClick={onNext}
className="nav-button nav-next"
disabled={currentIndex === images.length - 1}
title="下一张 (→)"
>
›
</button>
</>
)}
{/* 缩略图栏 */}
{images.length > 1 && (
<div className="image-viewer-thumbnails">
{images.map((image, index) => (
<div
key={index}
className={`thumbnail ${index === currentIndex ? 'active' : ''}`}
onClick={() => {
// 这里需要父组件提供切换图片的方法
}}
>
<img src={image} alt={`缩略图 ${index + 1}`} />
</div>
))}
</div>
)}
{/* 快捷键提示 */}
<div className="keyboard-hints">
<div className="hint">ESC: 关闭</div>
<div className="hint">←→: 切换</div>
<div className="hint">+/-: 缩放</div>
<div className="hint">R: 旋转</div>
<div className="hint">0: 重置</div>
</div>
</div>
</div>
);
}; | 6,130 | ImageViewer | tsx | en | tsx | code | {"qsc_code_num_words": 525, "qsc_code_num_chars": 6130.0, "qsc_code_mean_word_length": 5.39047619, "qsc_code_frac_words_unique": 0.29714286, "qsc_code_frac_chars_top_2grams": 0.05936396, "qsc_code_frac_chars_top_3grams": 0.03180212, "qsc_code_frac_chars_top_4grams": 0.00706714, "qsc_code_frac_chars_dupe_5grams": 0.13144876, "qsc_code_frac_chars_dupe_6grams": 0.07561837, "qsc_code_frac_chars_dupe_7grams": 0.07561837, "qsc_code_frac_chars_dupe_8grams": 0.07561837, "qsc_code_frac_chars_dupe_9grams": 0.05724382, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01686874, "qsc_code_frac_chars_whitespace": 0.38107667, "qsc_code_size_file_byte": 6130.0, "qsc_code_num_lines": 226.0, "qsc_code_num_chars_line_max": 111.0, "qsc_code_num_chars_line_mean": 27.12389381, "qsc_code_frac_chars_alphabet": 0.72614655, "qsc_code_frac_chars_comments": 0.01484502, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.33823529, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.07251656, "qsc_code_frac_chars_long_word_length": 0.00745033, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
000haoji/deep-student | src/components/UniversalAppChatHost.tsx | import { useState, useEffect, useCallback, useRef } from 'react';
import { MessageWithThinking } from '../chat-core';
import { ImageViewer } from './ImageViewer';
import {
ChatMessage,
AnalysisResponse,
ContinueChatResponse
} from '../types/index';
// 移除不再使用的streamHandler import
import { TauriAPI } from '../utils/tauriApi';
import { useSubject } from '../contexts/SubjectContext';
import { getCurrentWindow } from '@tauri-apps/api/window';
import '../App.css';
import '../chat-core/styles/index.css';
import ModernSelect from './ModernSelect';
// UniversalAppChatHost Props接口定义
export type HostedChatMode =
| 'NEW_MISTAKE_ANALYSIS' // 对应原 App.tsx 的 'analysis' 视图,从零开始创建新错题分析
| 'EXISTING_MISTAKE_DETAIL' // 错题库详情:加载已有错题,进行追问
| 'EXISTING_BATCH_TASK_DETAIL'// 批量分析任务详情:加载已有分析,进行追问
| 'REVIEW_SESSION_DETAIL'; // 回顾分析会话详情:启动或继续回顾分析
// API 函数提供者接口,由父组件根据场景实现
export interface HostedChatApiProvider {
// 阶段一:获取用于流交互的ID及初始数据 (如OCR结果)
// 对于 NEW_MISTAKE_ANALYSIS: 调用原 App.tsx 中的 TauriAPI.analyzeStepByStep
// 对于其他模式: 可能直接返回传入的业务ID作为流ID,或调用特定API获取会话详情
initiateAndGetStreamId: (params: {
businessId?: string; // 外部业务ID (mistakeId, batchId, reviewSessionId)
subject?: string;
questionImages?: File[];
userQuestion?: string;
enableChainOfThought: boolean;
enableRag: boolean;
ragTopK: number;
}) => Promise<{
streamIdForEvents: string; // 后端用于流事件的ID (temp_id)
ocrResultData?: any; // OCR及初步分类结果
initialMessages?: ChatMessage[];// 可能由此阶段返回的初始消息
}>;
// 阶段二:使用阶段一获取的 streamIdForEvents,正式启动AI回答的流
startMainStreaming: (params: {
streamIdForEvents: string;
enableChainOfThought: boolean;
enableRag: boolean;
ragTopK: number;
}) => Promise<void>;
// 用于追问
continueUserChat: (params: {
streamIdForEvents: string; // 当前流ID
businessId: string; // 外部业务ID
fullChatHistory: ChatMessage[];// 包含新用户消息的完整历史
enableChainOfThought: boolean;
enableRag: boolean;
ragTopK: number;
}) => Promise<void>;
// (可选) 获取指定业务ID的完整聊天记录和相关数据
loadExistingSessionData?: (params: { businessId: string }) => Promise<{
chatHistory: ChatMessage[];
thinkingContent?: Map<number, string>;
ocrResultData?: any;
// ... other relevant data like subject, userQuestion for display
}>;
}
export interface UniversalAppChatHostProps {
mode: HostedChatMode;
// 外部传入的、代表当前业务实体的唯一ID (如 mistake.id, batchTask.id, reviewSession.id)
// 这个ID将传递给 apiProvider 中的函数。
businessSessionId: string;
// 预加载的初始数据 (通常用于 EXISTING_* 和 REVIEW_SESSION_DETAIL 模式)
// 如果未提供,组件可能会尝试通过 apiProvider.loadExistingSessionData 获取
preloadedData?: {
subject?: string;
userQuestion?: string; // 作为标题或问题描述
questionImages?: File[]; // 或图片URL列表
questionImageUrls?: string[];
ocrText?: string;
tags?: string[];
chatHistory?: ChatMessage[];
thinkingContent?: Map<number, string>;
status?: string; // 新增:允许传入会话状态
mistake_summary?: string | null; // 错题总结内容
user_error_analysis?: string | null; // 用户错误分析内容
// 添加原始错题对象引用,用于更新操作
originalMistake?: any; // 完整的原始错题对象
// ... 其他特定于该业务实体的数据
};
// 后端交互配置
serviceConfig: {
apiProvider: HostedChatApiProvider;
// 事件名生成函数,'id' 参数是 initiateAndGetStreamId 返回的 streamIdForEvents
streamEventNames: {
initialStream: (id: string) => { data: string; reasoning: string; ragSources?: string };
continuationStream: (id: string) => { data: string; reasoning: string; ragSources?: string };
};
defaultEnableChainOfThought: boolean;
defaultEnableRag: boolean;
defaultRagTopK: number;
defaultSelectedLibraries?: string[];
};
// 当内部核心状态(聊天记录、思维链、OCR结果)更新时回调
onCoreStateUpdate?: (data: {
chatHistory: ChatMessage[];
thinkingContent: Map<number, string>;
ocrResult?: any;
isAnalyzing?: boolean; // 当前分析状态
isChatting?: boolean; // 当前追问状态
}) => void;
// 当用户在组件内部触发保存操作时回调
onSaveRequest: (data: {
businessSessionId: string;
chatHistory: ChatMessage[];
thinkingContent: Map<number, string>;
ocrResult?: any; // OCR结果
temp_id?: string; // 直接传递的temp_id
// 总结内容 - 新增
summaryContent?: string;
// 原始输入数据,如 subject, userQuestion, questionImages,也应包含,因为保存时可能需要
originalInputs: { subject: string; userQuestion: string; questionImages: File[]; /*...*/ }
}) => Promise<void>;
onExitRequest?: () => void; // 如果组件有退出/返回按钮
}
// 真实API调用
const analyzeNewMistake = TauriAPI.analyzeNewMistake;
const continueChat = async (request: any): Promise<ContinueChatResponse> => {
return TauriAPI.continueChat(request);
};
function UniversalAppChatHost(props: UniversalAppChatHostProps) {
// 调试日志:检查接收到的props数据
console.log('🔍 UniversalAppChatHost 接收到的 props:', {
mode: props.mode,
businessSessionId: props.businessSessionId,
preloadedDataExists: !!props.preloadedData,
preloadedChatHistoryLength: props.preloadedData?.chatHistory?.length || 0,
preloadedChatHistoryData: props.preloadedData?.chatHistory,
preloadedOcrText: props.preloadedData?.ocrText?.substring(0, 100) + '...',
questionImageUrls: props.preloadedData?.questionImageUrls?.length || 0
});
console.log('🔍 [streamId] 组件模式和业务ID:', { mode: props.mode, businessSessionId: props.businessSessionId });
const [isChatFullscreen, setIsChatFullscreen] = useState(false);
// 使用全局科目状态
const { currentSubject, setCurrentSubject, getEnabledSubjects, loading: isLoadingSubjects } = useSubject();
// 分析相关状态 - 从props或全局状态获取初始值,但优先使用全局状态
const subject = currentSubject || props.preloadedData?.subject || '未选择科目';
const availableSubjects = getEnabledSubjects();
// 调试:监听科目变化
useEffect(() => {
console.log('📚 [UniversalAppChatHost] 科目状态变化:', {
currentSubject,
computedSubject: subject,
preloadedSubject: props.preloadedData?.subject,
mode: props.mode
});
}, [currentSubject, subject, props.preloadedData?.subject, props.mode]);
const [userQuestion, setUserQuestion] = useState(props.preloadedData?.userQuestion || '');
const [questionImages, setQuestionImages] = useState<File[]>(props.preloadedData?.questionImages || []);
const [questionImageUrls, setQuestionImageUrls] = useState<string[]>(props.preloadedData?.questionImageUrls || []);
const [imageViewerOpen, setImageViewerOpen] = useState(false);
const [currentImageIndex, setCurrentImageIndex] = useState(0);
const [isAnalyzing, setIsAnalyzing] = useState(false);
const [analysisResult, setAnalysisResult] = useState<AnalysisResponse | null>(
// 🎯 修复:为已存在的详情页面创建虚拟的analysisResult,确保输入框显示
props.mode !== 'NEW_MISTAKE_ANALYSIS' && props.preloadedData?.ocrText ? {
temp_id: props.businessSessionId,
initial_data: {
ocr_text: props.preloadedData.ocrText,
tags: props.preloadedData.tags || [],
mistake_type: '已加载的分析',
first_answer: typeof props.preloadedData.chatHistory?.[0]?.content === 'string'
? props.preloadedData.chatHistory[0].content
: '[多模态内容]'
}
} : null
);
// 过滤掉总结相关的消息,避免在页面刷新时显示
const filterSummaryMessages = (messages: ChatMessage[]) => {
console.log('🔍 [过滤器] 输入消息数量:', messages.length);
console.log('🔍 [过滤器] 原始消息列表:', messages.map((msg, i) => ({
index: i,
role: msg.role,
contentPreview: typeof msg.content === 'string' ? msg.content.substring(0, 100) + '...' : '[非文本内容]',
contentLength: typeof msg.content === 'string' ? msg.content.length : 0
})));
const filtered = messages.filter(msg => {
// 过滤掉总结请求消息
if (msg.role === 'user' && typeof msg.content === 'string' && msg.content.includes('[SUMMARY_REQUEST]')) {
console.log('🚫 [过滤] 移除总结请求消息:', msg.content.substring(0, 50) + '...');
return false;
}
// 过滤掉总结响应消息(通过内容特征识别)
if (msg.role === 'assistant' && typeof msg.content === 'string' &&
(msg.content.includes('核心知识点') && msg.content.includes('错误分析') && msg.content.includes('学习建议'))) {
console.log('🚫 [过滤] 移除总结响应消息:', msg.content.substring(0, 50) + '...');
return false;
}
return true;
});
console.log('✅ [过滤器] 过滤后消息数量:', filtered.length);
console.log('✅ [过滤器] 过滤后消息列表:', filtered.map((msg, i) => ({
index: i,
role: msg.role,
contentPreview: typeof msg.content === 'string' ? msg.content.substring(0, 100) + '...' : '[非文本内容]'
})));
return filtered;
};
const [chatHistory, setChatHistory] = useState<ChatMessage[]>(
filterSummaryMessages(props.preloadedData?.chatHistory || [])
);
// 调试日志:检查chatHistory初始化状态
console.log('🔍 UniversalAppChatHost chatHistory 初始化:', {
mode: props.mode,
businessSessionId: props.businessSessionId,
chatHistoryLength: chatHistory.length,
chatHistoryData: chatHistory,
preloadedDataChatHistory: props.preloadedData?.chatHistory,
preloadedDataChatHistoryLength: props.preloadedData?.chatHistory?.length || 0,
initialInputAllowed: props.mode !== 'NEW_MISTAKE_ANALYSIS' && props.preloadedData?.chatHistory && props.preloadedData.chatHistory.length > 0
});
const [currentMessage, setCurrentMessage] = useState('');
const [isChatting, setIsChatting] = useState(false);
const [streamingMessageIndex, setStreamingMessageIndex] = useState<number | null>(null);
const [isInputAllowed, setIsInputAllowed] = useState(
// 对于非NEW_MISTAKE_ANALYSIS模式,初始允许输入(等待流式处理完成后可以对话)
props.mode !== 'NEW_MISTAKE_ANALYSIS'
);
const [useStreamMode] = useState(true); // 固定启用流式模式
// 新增状态:用于立即显示OCR结果 - 从props获取初始值
const [ocrResult, setOcrResult] = useState<{
ocr_text: string;
tags: string[];
mistake_type: string;
} | null>(props.preloadedData?.ocrText ? {
ocr_text: props.preloadedData.ocrText,
tags: props.preloadedData.tags || [],
mistake_type: '已加载的分析'
} : null);
const [isOcrComplete, setIsOcrComplete] = useState(() => {
// 对于错题详情页面,如果有聊天记录,直接认为OCR已完成
// 🎯 修复:即使OCR结果为空,只要有聊天记录就应该显示聊天界面
const result = props.mode === 'EXISTING_MISTAKE_DETAIL' ?
!!(props.preloadedData?.chatHistory?.length) || !!props.preloadedData?.ocrText :
!!props.preloadedData?.ocrText;
console.log('🔍 [OCR状态] isOcrComplete 初始化:', {
mode: props.mode,
result,
hasOcrText: !!props.preloadedData?.ocrText,
chatHistoryLength: props.preloadedData?.chatHistory?.length || 0,
ocrText: props.preloadedData?.ocrText?.substring(0, 50) + '...',
logic: props.mode === 'EXISTING_MISTAKE_DETAIL' ?
`chatHistory(${props.preloadedData?.chatHistory?.length || 0}) || ocrText(${!!props.preloadedData?.ocrText})` :
`ocrText(${!!props.preloadedData?.ocrText})`
});
return result;
});
const [isOcrInProgress, setIsOcrInProgress] = useState(false); // 新增:OCR进行状态
const [enableChainOfThought] = useState(props.serviceConfig.defaultEnableChainOfThought);
const [thinkingContent, setThinkingContent] = useState<Map<number, string>>(props.preloadedData?.thinkingContent || new Map()); // 存储每条消息的思维链内容
// 总结流式内容状态 - 从数据库加载已有总结内容
const getInitialSummaryContent = () => {
if (props.mode === 'EXISTING_MISTAKE_DETAIL' && props.preloadedData) {
// 合并 mistake_summary 和 user_error_analysis 为显示内容
const mistakeSummary = props.preloadedData.mistake_summary;
const userErrorAnalysis = props.preloadedData.user_error_analysis;
console.log('📄 [总结加载] 检查数据库总结内容:', {
hasMistakeSummary: !!mistakeSummary,
hasUserErrorAnalysis: !!userErrorAnalysis,
mistakeSummaryLength: mistakeSummary?.length || 0,
userErrorAnalysisLength: userErrorAnalysis?.length || 0
});
if (mistakeSummary || userErrorAnalysis) {
let combined = '';
// 🎯 修复:保持原始格式,不添加硬编码标题
if (mistakeSummary) {
combined += mistakeSummary;
if (userErrorAnalysis) {
combined += '\n\n'; // 只在两部分都存在时添加分隔
}
}
if (userErrorAnalysis) {
combined += userErrorAnalysis;
}
console.log('📄 [总结加载] 合并后的总结内容:', {
combinedLength: combined.length,
combinedPreview: combined.substring(0, 200) + '...'
});
return combined.trim();
}
}
return '';
};
const [summaryStreamContent, setSummaryStreamContent] = useState(getInitialSummaryContent());
const [summaryStreamComplete, setSummaryStreamComplete] = useState(getInitialSummaryContent() !== '');
const [isGeneratingSummary, setIsGeneratingSummary] = useState(false);
// 使用useRef来确保事件处理器能访问到最新的isGeneratingSummary状态
const isGeneratingSummaryRef = useRef(isGeneratingSummary);
useEffect(() => {
isGeneratingSummaryRef.current = isGeneratingSummary;
console.log('🔄 [状态同步] isGeneratingSummary更新为:', isGeneratingSummary);
}, [isGeneratingSummary]);
// 当前流ID状态 - 用于API调用
const [currentStreamId, setCurrentStreamId] = useState<string | null>(null);
// 初始化streamId - 对于非NEW_MISTAKE_ANALYSIS模式,使用businessSessionId作为streamId
useEffect(() => {
if (props.mode !== 'NEW_MISTAKE_ANALYSIS' && !currentStreamId && props.businessSessionId) {
console.log('🔧 [初始化] 设置非新分析模式的streamId:', props.businessSessionId);
setCurrentStreamId(props.businessSessionId);
}
}, [props.mode, props.businessSessionId, currentStreamId]);
// RAG相关状态 - 从props获取初始值
const [enableRag, setEnableRag] = useState(props.serviceConfig.defaultEnableRag);
const [ragTopK, setRagTopK] = useState(props.serviceConfig.defaultRagTopK);
// 状态更新回调 - 使用useRef避免过度调用
const lastStateRef = useRef<string>('');
const updateTimeoutRef = useRef<number | null>(null);
useEffect(() => {
// 在总结生成期间,暂停状态更新回调以避免不必要的重渲染
if (isGeneratingSummary) {
console.log('📝 [状态更新] 总结生成中,暂停状态更新回调');
return;
}
// 创建状态指纹,只在真正有变化时才调用回调
const stateFingerprint = JSON.stringify({
chatHistoryLength: chatHistory.length,
thinkingContentSize: thinkingContent.size,
hasOcrResult: !!ocrResult,
isAnalyzing,
isChatting
});
if (lastStateRef.current !== stateFingerprint) {
lastStateRef.current = stateFingerprint;
// 恢复状态更新回调,但增加防抖机制
if (updateTimeoutRef.current) {
clearTimeout(updateTimeoutRef.current);
}
updateTimeoutRef.current = window.setTimeout(() => {
props.onCoreStateUpdate?.({
chatHistory,
thinkingContent,
ocrResult,
isAnalyzing,
isChatting
});
updateTimeoutRef.current = null;
}, 500); // 500ms防抖
}
}, [chatHistory, thinkingContent, ocrResult, isAnalyzing, isChatting, isGeneratingSummary]);
// 科目现在由全局状态管理,不再需要本地加载
// 监听preloadedData的变化,特别是chatHistory的实时更新
useEffect(() => {
// 🎯 关键修复:防止在流式处理期间或刚完成后错误同步状态
// 1. 仅当流式渲染未在进行时,才考虑从props同步chatHistory
if (streamingMessageIndex !== null) {
console.log('⚠️ [同步跳过] 正在流式渲染,暂不更新chatHistory');
return;
}
// 2. 如果正在分析或对话中,也跳过同步
if (isAnalyzing || isChatting) {
console.log('⚠️ [同步跳过] 正在分析或对话中,暂不更新chatHistory');
return;
}
// 3. 对于回顾分析模式,如果当前已有内容且preloaded为空,说明是流式处理完成后的状态,不应该同步
if (props.mode === 'REVIEW_SESSION_DETAIL' &&
chatHistory.length > 0 &&
(!props.preloadedData?.chatHistory || props.preloadedData.chatHistory.length === 0)) {
console.log('⚠️ [同步跳过] 回顾分析模式,保护已生成的内容');
return;
}
if (props.preloadedData?.chatHistory) {
const filteredPreloadedHistory = filterSummaryMessages(props.preloadedData.chatHistory);
// 使用JSON字符串比较来检测preloadedData和当前state是否有实质性差异
// 这比比较长度或时间戳更可靠
const preloadedHistoryStr = JSON.stringify(filteredPreloadedHistory);
const currentHistoryStr = JSON.stringify(chatHistory);
if (preloadedHistoryStr !== currentHistoryStr) {
console.log('🔄 [状态同步] 检测到 preloadedData.chatHistory 与内部状态不一致,检查是否需要同步。');
console.log(' - Preloaded 长度:', filteredPreloadedHistory.length);
console.log(' - 当前 State 长度:', chatHistory.length);
console.log(' - 模式:', props.mode);
console.log(' - 分析状态:', { isAnalyzing, isChatting });
console.log(' - 流式状态:', { streamingMessageIndex });
// 🎯 修复:智能同步逻辑,防止覆盖用户的追问对话
let shouldSync = false;
if (props.mode === 'EXISTING_MISTAKE_DETAIL') {
// 🎯 时间窗口保护:如果刚刚完成流式传输,给3秒保护时间
const now = Date.now();
const lastCompletionTime = eventListenersRef.current.lastStreamCompletionTime || 0;
const timeSinceCompletion = now - lastCompletionTime;
if (timeSinceCompletion < 3000) { // 3秒保护窗口
shouldSync = false;
console.log('🛡️ [状态同步] 流式完成后的保护窗口期,拒绝同步', {
timeSinceCompletion,
lastCompletionTime
});
} else if (chatHistory.length === 0) {
// 完全空的聊天记录,这是真正的初始加载
shouldSync = true;
console.log('🔄 [状态同步] 检测到初始加载,执行同步');
} else if (chatHistory.length < filteredPreloadedHistory.length) {
// 当前状态记录数少于预加载数据,可能是页面重新加载后需要恢复
shouldSync = true;
console.log('🔄 [状态同步] 检测到数据缺失,执行恢复同步');
} else {
// 🎯 关键:检查是否有用户追问的新消息
const currentUserMessages = chatHistory.filter(msg => msg.role === 'user').length;
const preloadedUserMessages = filteredPreloadedHistory.filter(msg => msg.role === 'user').length;
if (currentUserMessages > preloadedUserMessages) {
// 当前有更多用户消息,说明有新的追问,绝对不要同步
shouldSync = false;
console.log('🛡️ [状态同步] 检测到新的用户追问,保护追问对话,拒绝同步', {
currentUserMessages,
preloadedUserMessages,
currentTotal: chatHistory.length,
preloadedTotal: filteredPreloadedHistory.length
});
} else if (!isAnalyzing && !isChatting && streamingMessageIndex === null) {
// 没有新的用户消息,但仍有差异,且不在活动状态
shouldSync = false;
console.log('🛡️ [状态同步] 检测到其他内容差异,保护现有内容,暂不同步');
} else {
// 其他情况(如正在分析/聊天),保持不变
shouldSync = false;
console.log('🛡️ [状态同步] 检测到活动状态,暂不同步');
}
}
} else if (props.mode === 'REVIEW_SESSION_DETAIL') {
// 回顾分析:只有在初始加载时才同步
shouldSync = chatHistory.length === 0;
console.log(`🔄 [状态同步] 回顾分析模式:${shouldSync ? '执行' : '跳过'}同步`);
} else {
// 其他模式:按原逻辑,只有初始加载时同步
shouldSync = chatHistory.length === 0;
console.log(`🔄 [状态同步] 默认模式:${shouldSync ? '执行' : '跳过'}同步`);
}
if (shouldSync) {
setChatHistory(filteredPreloadedHistory);
console.log('✅ [状态同步] 已执行同步');
} else {
console.log('🛡️ [状态同步] 保护现有内容,跳过同步');
}
}
}
}, [props.preloadedData?.chatHistory, streamingMessageIndex, isAnalyzing, isChatting, props.mode]); // 🎯 移除chatHistory.length依赖,避免循环更新
// 🎯 新增:监听preloadedData的变化,同步总结状态 - 修复切换错题时总结状态持久化问题
useEffect(() => {
// 当切换到不同错题时,重新初始化总结状态
const newSummaryContent = getInitialSummaryContent();
const currentSummaryStr = summaryStreamContent;
// 只有当总结内容发生实质性变化时才更新
if (newSummaryContent !== currentSummaryStr) {
console.log('🔄 [总结同步] 检测到错题数据变化,更新总结状态');
console.log(' - 新总结内容长度:', newSummaryContent.length);
console.log(' - 当前总结内容长度:', currentSummaryStr.length);
console.log(' - 错题ID:', props.businessSessionId);
setSummaryStreamContent(newSummaryContent);
setSummaryStreamComplete(newSummaryContent !== '');
// 如果没有新的总结内容,确保生成状态被重置
if (newSummaryContent === '') {
setIsGeneratingSummary(false);
console.log('🔄 [总结同步] 重置生成状态,因为新错题无总结内容');
}
}
}, [props.preloadedData?.mistake_summary, props.preloadedData?.user_error_analysis, props.businessSessionId]);
// 🎯 新增:监听preloadedData的变化,同步图片URL - 修复切换错题时图片不显示问题
useEffect(() => {
console.log('🔄 [图片同步] preloadedData变化检测:', {
hasQuestionImageUrls: !!props.preloadedData?.questionImageUrls,
newImageUrlsLength: props.preloadedData?.questionImageUrls?.length || 0,
currentImageUrlsLength: questionImageUrls.length,
businessSessionId: props.businessSessionId,
newImageUrls: props.preloadedData?.questionImageUrls
});
if (props.preloadedData?.questionImageUrls && props.preloadedData.questionImageUrls.length > 0) {
const newImageUrls = props.preloadedData.questionImageUrls;
// 只有当图片URLs发生变化时才更新
if (JSON.stringify(newImageUrls) !== JSON.stringify(questionImageUrls)) {
console.log('🔄 [图片同步] 检测到图片数据变化,更新图片URLs');
console.log(' - 新图片数量:', newImageUrls.length);
console.log(' - 新图片URLs预览:', newImageUrls.map((url, i) => `${i+1}: ${url.substring(0, 50)}...`));
console.log(' - 当前图片数量:', questionImageUrls.length);
console.log(' - 错题ID:', props.businessSessionId);
setQuestionImageUrls(newImageUrls);
}
} else if (questionImageUrls.length > 0) {
// 如果新的错题没有图片,清空当前图片
console.log('🔄 [图片同步] 新错题无图片,清空图片URLs');
setQuestionImageUrls([]);
}
}, [props.preloadedData?.questionImageUrls, props.businessSessionId]);
// 🎯 新增:监听businessSessionId变化,重置关键状态 - 修复切换错题时状态混乱问题
// 这是保证组件在切换不同错题时能够完全重置的核心逻辑
useEffect(() => {
console.log('🔄 [会话重置] businessSessionId 变化,重置所有内部状态:', {
newId: props.businessSessionId,
mode: props.mode,
});
// 强制重置所有从 preloadedData 派生的状态
const { preloadedData } = props;
// 1. 重置聊天记录和思维链
const initialChatHistory = filterSummaryMessages(preloadedData?.chatHistory || []);
setChatHistory(initialChatHistory);
// 🎯 修复:正确恢复思维链数据
if (preloadedData?.thinkingContent && preloadedData.thinkingContent instanceof Map) {
console.log('🧠 [状态重置] 恢复思维链数据,条目数:', preloadedData.thinkingContent.size);
setThinkingContent(new Map(preloadedData.thinkingContent));
} else if (preloadedData?.chatHistory) {
// 🎯 修复:从聊天历史中恢复思维链数据
const recoveredThinkingContent = new Map<number, string>();
preloadedData.chatHistory.forEach((message, index) => {
if (message.role === 'assistant' && message.thinking_content) {
console.log(`🧠 [状态重置] 从聊天历史恢复思维链,索引${index}:`, message.thinking_content.substring(0, 50) + '...');
recoveredThinkingContent.set(index, message.thinking_content);
}
});
setThinkingContent(recoveredThinkingContent);
console.log('🧠 [状态重置] 从聊天历史恢复的思维链条目数:', recoveredThinkingContent.size);
} else {
console.log('🧠 [状态重置] 无思维链数据,初始化为空Map');
setThinkingContent(new Map());
}
// 2. 重置基础信息
// 科目现在由全局状态管理,不再需要本地设置
setUserQuestion(preloadedData?.userQuestion || '');
// 3. 重置图片
setQuestionImageUrls(preloadedData?.questionImageUrls || []);
setQuestionImages(preloadedData?.questionImages || []);
// 4. 重置OCR和分析结果
if (preloadedData?.ocrText) {
setOcrResult({
ocr_text: preloadedData.ocrText,
tags: preloadedData.tags || [],
mistake_type: '已加载的分析'
});
setIsOcrComplete(true);
// 为错题详情页面创建虚拟的analysisResult,确保输入框可用
setAnalysisResult({
temp_id: props.businessSessionId,
initial_data: {
ocr_text: preloadedData.ocrText,
tags: preloadedData.tags || [],
mistake_type: '已加载的分析',
first_answer: typeof preloadedData.chatHistory?.[0]?.content === 'string'
? preloadedData.chatHistory[0].content
: '[多模态内容]'
}
});
} else {
// 🎯 修复:即使OCR结果为空,如果有聊天记录也要设置为完成状态
if (props.mode === 'EXISTING_MISTAKE_DETAIL' && preloadedData?.chatHistory?.length) {
setOcrResult({
ocr_text: '',
tags: preloadedData.tags || [],
mistake_type: '已保存的错题'
});
setIsOcrComplete(true);
setAnalysisResult({
temp_id: props.businessSessionId,
initial_data: {
ocr_text: '',
tags: preloadedData.tags || [],
mistake_type: '已保存的错题',
first_answer: typeof preloadedData.chatHistory?.[0]?.content === 'string'
? preloadedData.chatHistory[0].content
: '[多模态内容]'
}
});
console.log('🔧 [OCR修复] OCR结果为空但有聊天记录,设置为完成状态以显示聊天界面');
} else {
setOcrResult(null);
setIsOcrComplete(false);
setAnalysisResult(null);
}
}
// 5. 重置总结状态
const newSummaryContent = getInitialSummaryContent();
setSummaryStreamContent(newSummaryContent);
setSummaryStreamComplete(newSummaryContent !== '');
setIsGeneratingSummary(false);
// 6. 重置流式处理和交互状态
setIsAnalyzing(false);
setIsChatting(false);
setStreamingMessageIndex(null);
setIsInputAllowed(props.mode !== 'NEW_MISTAKE_ANALYSIS'); // 允许非新分析模式初始输入
// 7. 重置流ID和自动启动标记
setCurrentStreamId(props.businessSessionId);
autoStartExecutedRef.current = false;
setAutoStartTriggered(false);
console.log('✅ [会话重置] 所有状态已根据新的 businessSessionId 重置完毕。');
}, [props.businessSessionId, props.preloadedData]); // 依赖项为 businessSessionId 和 preloadedData
// 自动启动分析逻辑 - 对于REVIEW_SESSION_DETAIL模式且聊天历史为空的情况
const [autoStartTriggered, setAutoStartTriggered] = useState(false);
// 处理聊天全屏切换 - 简化为直接状态切换
const handleChatFullscreenToggle = () => {
setIsChatFullscreen(!isChatFullscreen);
};
// 处理图片上传
const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []);
const remainingSlots = 9 - questionImages.length;
const filesToAdd = files.slice(0, remainingSlots);
if (filesToAdd.length > 0) {
setQuestionImages(prev => [...prev, ...filesToAdd]);
// URL管理由useEffect自动处理,不需要在这里手动创建
}
// 清空input
e.target.value = '';
};
// 删除图片
const removeImage = (index: number) => {
// 只需要更新questionImages状态,URL管理由useEffect自动处理
setQuestionImages(prev => prev.filter((_, i) => i !== index));
};
// 打开图片查看器
const openImageViewer = (index: number) => {
setCurrentImageIndex(index);
setImageViewerOpen(true);
};
// 优化的文件上传点击处理器
const handleFileUploadClick = useCallback(() => {
const fileInput = document.querySelector('.file-input') as HTMLInputElement;
if (fileInput) {
fileInput.click();
}
}, []);
// 保留聊天相关的键盘快捷键
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
// ESC键退出全屏
if (e.key === 'Escape' && isChatFullscreen) {
setIsChatFullscreen(false);
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [isChatFullscreen]);
// Tauri文件拖拽事件监听
useEffect(() => {
if (props.mode !== 'NEW_MISTAKE_ANALYSIS') {
return; // 只在新分析模式下启用拖拽
}
let unlisten: (() => void) | undefined;
const setupDragDropListener = async () => {
try {
const appWindow = getCurrentWindow();
console.log('🎯 设置Tauri文件拖拽监听器');
unlisten = await appWindow.onFileDropEvent(async (event) => {
console.log('🎯 Tauri拖拽事件:', event);
if (event.payload.type === 'drop' && event.payload.paths) {
console.log('🎯 文件拖拽路径:', event.payload.paths);
// 过滤图片文件
const imageFiles = event.payload.paths.filter((path: string) => {
const ext = path.toLowerCase().split('.').pop();
return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext || '');
});
console.log('🎯 过滤后的图片文件:', imageFiles);
if (imageFiles.length > 0) {
console.log('🎯 处理拖拽的图片文件:', imageFiles);
// 由于Tauri的文件系统API在当前配置下不可用,
// 我们暂时记录文件路径,提示用户使用文件选择器
alert(`检测到 ${imageFiles.length} 个图片文件,但拖拽功能需要额外配置。请使用"选择文件"按钮上传图片。`);
// 可以在这里添加将文件路径转换为File对象的逻辑
// 但需要先在Tauri配置中启用文件系统权限
}
} else if (event.payload.type === 'enter') {
console.log('🎯 文件进入拖拽区域');
// 可以在这里添加悬停效果
const uploadArea = document.getElementById('uploadArea');
if (uploadArea) {
uploadArea.classList.add('active');
}
} else if (event.payload.type === 'leave') {
console.log('🎯 文件离开拖拽区域');
// 移除悬停效果
const uploadArea = document.getElementById('uploadArea');
if (uploadArea) {
uploadArea.classList.remove('active');
}
}
});
} catch (error) {
console.error('🎯 设置拖拽监听器失败:', error);
}
};
setupDragDropListener();
return () => {
if (unlisten) {
unlisten();
console.log('🎯 清理Tauri文件拖拽监听器');
}
};
}, [props.mode, questionImages.length]);
// 管理题目图片URL的生命周期
useEffect(() => {
// 清理旧的URLs(避免在第一次渲染时清理不存在的URLs)
if (questionImageUrls.length > 0) {
questionImageUrls.forEach(url => {
try {
URL.revokeObjectURL(url);
} catch (error) {
console.warn('清理URL时出错:', error);
}
});
}
// 创建新的URLs
const newUrls = questionImages.map(file => {
try {
return URL.createObjectURL(file);
} catch (error) {
console.error('创建图片URL失败:', error);
return '';
}
}).filter(url => url !== '');
setQuestionImageUrls(newUrls);
// 清理函数
return () => {
newUrls.forEach(url => {
try {
URL.revokeObjectURL(url);
} catch (error) {
console.warn('清理URL时出错:', error);
}
});
};
}, [questionImages]); // 仅依赖questionImages,避免questionImageUrls导致循环
// 清理timeout防止内存泄漏
useEffect(() => {
return () => {
if (updateTimeoutRef.current) {
clearTimeout(updateTimeoutRef.current);
}
};
}, []);
// 开始分析 - 使用useCallback确保函数引用稳定
const handleAnalyze = useCallback(async () => {
// 对于非NEW_MISTAKE_ANALYSIS模式,可能不需要验证输入
if (props.mode === 'NEW_MISTAKE_ANALYSIS') {
if (!userQuestion.trim()) {
alert('请输入问题描述');
return;
}
if (questionImages.length === 0) {
alert('请上传至少一张题目图片');
return;
}
}
try {
if (useStreamMode) {
console.log('🚀 开始分步骤分析...');
// 设置初始状态:开始OCR
setIsOcrInProgress(true);
setIsAnalyzing(false); // OCR阶段还不是分析阶段
setStreamingMessageIndex(null);
setOcrResult(null);
setIsOcrComplete(false);
setAnalysisResult(null);
setChatHistory([]);
// 第一步:通过props的apiProvider获取流ID和初始数据
console.log('📝 第一步:OCR和获取流ID...');
const stepResult = await props.serviceConfig.apiProvider.initiateAndGetStreamId({
businessId: props.businessSessionId,
subject,
questionImages,
userQuestion,
enableChainOfThought,
enableRag,
ragTopK
});
// 关键修复:先完成异步操作,拿到所有数据后再统一更新状态,避免竞态条件
console.log('✅ 第一步完成,获得流ID:', stepResult.streamIdForEvents);
// OCR完成,开始AI分析阶段
setIsOcrInProgress(false);
setIsAnalyzing(true);
setCurrentStreamId(stepResult.streamIdForEvents);
// 🎯 重要:重置总结状态,避免显示上一个分析的总结内容
setSummaryStreamContent('');
setSummaryStreamComplete(false);
setIsGeneratingSummary(false);
console.log('🔄 [新分析] 总结状态已重置');
// 处理OCR结果(如果有)
if (stepResult.ocrResultData) {
setOcrResult(stepResult.ocrResultData);
setIsOcrComplete(true);
console.log('✅ OCR分析完成:', stepResult.ocrResultData);
} else if (props.mode === 'REVIEW_SESSION_DETAIL') {
// 关键修复:对于回顾分析模式,即使没有OCR数据也要创建虚拟结果以启用聊天界面
const virtualOcrResult = {
ocr_text: props.preloadedData?.ocrText || '统一回顾分析',
tags: props.preloadedData?.tags || ['回顾分析'],
mistake_type: '统一回顾分析'
};
setOcrResult(virtualOcrResult);
setIsOcrComplete(true);
console.log('✅ 回顾分析虚拟OCR结果已创建,启用聊天界面');
}
// 处理初始消息(如果有)
if (stepResult.initialMessages && stepResult.initialMessages.length > 0) {
setChatHistory(stepResult.initialMessages);
}
// 创建临时的分析结果对象
const tempAnalysisResult: AnalysisResponse = {
temp_id: stepResult.streamIdForEvents,
initial_data: {
ocr_text: stepResult.ocrResultData?.ocr_text || (props.mode === 'REVIEW_SESSION_DETAIL' ? '统一回顾分析' : ''),
tags: stepResult.ocrResultData?.tags || (props.mode === 'REVIEW_SESSION_DETAIL' ? ['回顾分析'] : []),
mistake_type: stepResult.ocrResultData?.mistake_type || (props.mode === 'REVIEW_SESSION_DETAIL' ? '统一回顾分析' : ''),
first_answer: '', // 暂时为空,等待流式填充
},
};
setAnalysisResult(tempAnalysisResult);
// 第二步:开始流式AI解答
console.log('🤖 第二步:开始流式AI解答...');
// 如果没有预设的初始消息,创建一个空的助手消息等待流式填充
if (!stepResult.initialMessages || stepResult.initialMessages.length === 0) {
const initialMessage: ChatMessage = {
role: 'assistant',
content: '',
timestamp: new Date().toISOString(),
};
console.log('🔧 [初始化] 创建空的助手消息等待流式填充');
setChatHistory([initialMessage]);
setStreamingMessageIndex(0);
} else {
console.log('🔧 [初始化] 使用预设消息,消息数量:', stepResult.initialMessages.length);
setChatHistory(stepResult.initialMessages);
// 如果有预设消息,准备流式更新最后一条助手消息
const lastIndex = stepResult.initialMessages.length - 1;
if (stepResult.initialMessages[lastIndex]?.role === 'assistant') {
console.log('🔧 [初始化] 设置streamingMessageIndex为:', lastIndex);
setStreamingMessageIndex(lastIndex);
} else {
// 如果最后一条不是助手消息,添加一条空的助手消息
const newMessage: ChatMessage = {
role: 'assistant',
content: '',
timestamp: new Date().toISOString(),
};
console.log('🔧 [初始化] 最后一条不是助手消息,添加新的助手消息');
setChatHistory([...stepResult.initialMessages, newMessage]);
setStreamingMessageIndex(stepResult.initialMessages.length);
}
}
// 启动流式解答
console.log(`🚀 启动流式解答,streamId: ${stepResult.streamIdForEvents}, enable_chain_of_thought: ${enableChainOfThought}, enable_rag: ${enableRag}`);
await props.serviceConfig.apiProvider.startMainStreaming({
streamIdForEvents: stepResult.streamIdForEvents,
enableChainOfThought,
enableRag,
ragTopK
});
// 注意:事件监听逻辑将被移到下面的useEffect中
} else {
// 使用传统非流式分析
console.log('📊 使用传统分析模式...');
// 传统分析模式暂不支持
throw new Error('传统分析模式暂不支持,请使用流式模式');
}
} catch (error) {
console.error('❌ 分析失败:', error);
alert('分析失败: ' + error);
setStreamingMessageIndex(null);
setOcrResult(null);
setIsOcrComplete(false);
setIsOcrInProgress(false);
setIsAnalyzing(false);
} finally {
// setIsAnalyzing(false); // isAnalyzing状态由事件监听器在流结束后设置
}
}, [
props.mode,
userQuestion,
questionImages,
useStreamMode,
subject,
enableChainOfThought,
enableRag,
ragTopK,
props.serviceConfig.apiProvider,
props.businessSessionId
]);
// 自动启动分析逻辑 - 🎯 修复:使用稳定的函数引用避免重复启动
const autoStartExecutedRef = useRef(false);
const handleAnalyzeRef = useRef(handleAnalyze);
handleAnalyzeRef.current = handleAnalyze; // 保持引用最新
useEffect(() => {
// 调试日志:检查自动启动条件
console.log('🔍 检查自动启动条件:', {
mode: props.mode,
status: props.preloadedData?.status,
autoStartTriggered,
autoStartExecutedRef: autoStartExecutedRef.current,
chatHistoryLength: chatHistory.length,
isAnalyzing,
isChatting
});
if (props.mode === 'REVIEW_SESSION_DETAIL' &&
props.preloadedData?.status === 'pending' &&
!autoStartTriggered &&
!autoStartExecutedRef.current &&
!isAnalyzing && // 🎯 新增:确保不在分析中
!isChatting && // 🎯 新增:确保不在对话中
chatHistory.length === 0) { // 🎯 新增:确保聊天记录为空(初始状态)
console.log('🚀 自动启动回顾分析流式处理 (条件满足)...');
setAutoStartTriggered(true);
autoStartExecutedRef.current = true;
// 🎯 使用 ref 调用函数,避免依赖不稳定的函数引用
console.log('🎯 执行自动启动handleAnalyze');
handleAnalyzeRef.current().catch(error => {
console.error('❌ 自动启动分析失败:', error);
setAutoStartTriggered(false); // 重置状态允许重试
autoStartExecutedRef.current = false; // 重置执行标记
});
} else if (autoStartExecutedRef.current && chatHistory.length > 0) {
// 🎯 新增:如果已经执行过自动启动且有聊天记录,说明流式处理已完成
console.log('✅ 自动启动的流式处理已完成,聊天记录长度:', chatHistory.length);
}
}, [
props.mode,
props.preloadedData?.status,
autoStartTriggered,
isAnalyzing, // 🎯 新增依赖:确保状态变化时重新检查
isChatting, // 🎯 新增依赖:确保状态变化时重新检查
chatHistory.length // 🎯 新增依赖:聊天记录变化时重新检查
// 🚨 移除 handleAnalyze 依赖!这是导致重复启动的根本原因
// handleAnalyze 函数因为依赖项变化会不断重新创建,导致这个 useEffect 重复触发
]);
// 使用useRef来保持事件监听器的稳定性
const eventListenersRef = useRef<{
unlistenContent?: () => void;
unlistenThinking?: () => void;
unlistenRag?: () => void;
currentStreamId?: string;
lastEventType?: 'initial' | 'continuation';
lastEventId?: string; // 🎯 新增:用于防止重复事件处理
isActivelyStreaming?: boolean; // 🎯 新增:用于保护正在进行的流式传输
lastStreamCompletionTime?: number; // 🎯 新增:记录上次流式完成时间,用于保护窗口
streamTimeoutId?: number; // 🎯 新增:流式超时定时器ID
}>({});
// 稳定的事件处理函数
const handleStreamEvent = useCallback((event: any, isThinking: boolean = false) => {
const currentIsGeneratingSummary = isGeneratingSummaryRef.current;
console.log(`💬 [Stable] 收到${isThinking ? '思维链' : '主内容'}流:`, event.payload);
console.log(`🔍 [Stable] 当前isGeneratingSummary状态 (ref):`, currentIsGeneratingSummary);
console.log(`🔍 [Stable] 事件类型: ${event.payload.is_complete ? '完成信号' : '流式内容'}`);
console.log(`🔍 [事件处理详情] 处理状态:`, {
isThinking,
streamingMessageIndex,
chatHistoryLength: chatHistory.length,
targetIndex: streamingMessageIndex ?? (chatHistory.length > 0 ? chatHistory.length - 1 : 0),
eventContentLength: event.payload.content?.length || 0,
isComplete: event.payload.is_complete || false,
mode: props.mode
});
if (isThinking) {
// 🎯 修复:改进思维链索引计算逻辑
let targetIndex;
// 🎯 关键修复:在追问场景中,优先验证streamingMessageIndex的有效性
if (streamingMessageIndex !== null && streamingMessageIndex >= 0 && streamingMessageIndex < chatHistory.length) {
// 🎯 进一步验证:确保目标索引对应的是assistant消息
const targetMessage = chatHistory[streamingMessageIndex];
if (targetMessage && targetMessage.role === 'assistant') {
targetIndex = streamingMessageIndex;
console.log(`🧠 [思维链] 使用已验证的streamingMessageIndex: ${targetIndex}, 对应消息角色: ${targetMessage.role}`);
} else {
console.warn(`🧠 [思维链] streamingMessageIndex(${streamingMessageIndex})对应的消息不是assistant或不存在,寻找替代索引`);
targetIndex = null; // 强制进入查找逻辑
}
} else {
console.log(`🧠 [思维链] streamingMessageIndex无效或为null: ${streamingMessageIndex}, 聊天历史长度: ${chatHistory.length}`);
targetIndex = null; // 强制进入查找逻辑
}
// 如果streamingMessageIndex无效,则查找最后一条assistant消息
if (targetIndex === null) {
console.log('🧠 [思维链] 开始查找最后一条assistant消息...');
let lastAssistantIndex = -1;
for (let i = chatHistory.length - 1; i >= 0; i--) {
console.log(`🧠 [思维链] 检查索引${i}: 角色=${chatHistory[i]?.role}, 内容长度=${chatHistory[i]?.content?.length || 0}`);
if (chatHistory[i]?.role === 'assistant') {
lastAssistantIndex = i;
console.log(`🧠 [思维链] 找到最后一条assistant消息,索引: ${lastAssistantIndex}`);
break;
}
}
if (lastAssistantIndex >= 0) {
targetIndex = lastAssistantIndex;
console.log(`🧠 [思维链] 使用找到的assistant消息索引: ${targetIndex}`);
} else {
// 兜底:如果没找到assistant消息,使用末尾索引,但要确保不越界
targetIndex = Math.max(0, Math.min(chatHistory.length - 1, chatHistory.length - 1));
console.warn(`🧠 [思维链] 未找到assistant消息,使用兜底索引: ${targetIndex}`);
}
}
// 🎯 新增:最终验证目标索引的合理性
if (targetIndex < 0 || targetIndex >= chatHistory.length) {
console.error(`🧠 [思维链] 最终计算的索引${targetIndex}超出范围[0, ${chatHistory.length-1}],丢弃此思维链事件`);
return;
}
const finalTargetMessage = chatHistory[targetIndex];
console.log(`🧠 [思维链] 最终使用索引: ${targetIndex}, 对应消息:`, {
role: finalTargetMessage?.role,
contentLength: finalTargetMessage?.content?.length || 0,
messageExists: !!finalTargetMessage,
isAssistant: finalTargetMessage?.role === 'assistant'
});
// 🎯 安全检查:如果目标消息不是assistant,记录警告但仍然处理
if (finalTargetMessage?.role !== 'assistant') {
console.warn(`🧠 [思维链] 警告:索引${targetIndex}对应的消息角色是'${finalTargetMessage?.role}',不是'assistant'`);
}
setThinkingContent(prev => {
const newMap = new Map(prev);
// 🎯 修复:根据事件类型决定是追加还是替换
if (event.payload.is_complete) {
// 如果是完成事件,使用完整内容
if (event.payload.content) {
console.log(`🧠 [思维链完成] 索引${targetIndex}设置完整内容,长度: ${event.payload.content.length}`);
newMap.set(targetIndex, event.payload.content);
}
} else {
// 如果是流式事件,追加内容
const currentContent = newMap.get(targetIndex) || '';
const newContent = currentContent + (event.payload.content || '');
console.log(`🧠 [思维链流式] 索引${targetIndex}追加内容,从${currentContent.length}到${newContent.length}`);
newMap.set(targetIndex, newContent);
}
console.log(`🧠 [思维链状态] 当前思维链映射:`, Array.from(newMap.entries()).map(([idx, content]) => `${idx}: ${content.length}字符`));
return newMap;
});
return;
}
// 处理主内容
if (event.payload.is_complete) {
console.log('🎉 [Stable] 流式完成');
// 检查是否为总结生成完成
if (currentIsGeneratingSummary) {
console.log('📝 [Stable] 总结生成完成');
if (event.payload.content) {
setSummaryStreamContent(event.payload.content);
// 🎯 新增:保存总结内容到数据库
handleSaveSummaryToDatabase(event.payload.content);
}
setSummaryStreamComplete(true);
setIsGeneratingSummary(false);
console.log('📝 [Stable] 总结状态重置完成');
return;
}
// 普通聊天完成处理 - 🎯 新策略:优先保护已累积的内容
console.log('🎉 [完成处理] 流式传输完成:', {
targetIndex: streamingMessageIndex ?? (chatHistory.length - 1),
hasCompletionContent: !!event.payload.content,
completionContentLength: event.payload.content?.length || 0,
completionContentPreview: event.payload.content?.substring(0, 100) || '[无内容]'
});
// 🎯 关键策略:完成事件主要用于标记流式结束,内容保护优先
setChatHistory(prev => {
const newHistory = [...prev];
const targetIndex = streamingMessageIndex ?? newHistory.length - 1;
if (newHistory[targetIndex]) {
const currentContent = newHistory[targetIndex].content as string || '';
let finalContent = currentContent; // 默认保持当前内容
// 只有在特定条件下才使用完成事件的内容
if (event.payload.content) {
// 策略1:如果当前内容为空,使用完成事件内容
if (currentContent.length === 0) {
finalContent = event.payload.content;
console.log('🔧 [完成处理] 当前内容为空,使用完成事件内容');
}
// 策略2:如果完成事件内容明显更完整(超过当前内容1.5倍),才考虑使用
else if (event.payload.content.length > currentContent.length * 1.5) {
finalContent = event.payload.content;
console.log('🔧 [完成处理] 完成事件内容更完整,使用完成事件内容');
}
// 策略3:默认保持当前累积内容
else {
console.log('🔧 [完成处理] 保护当前累积内容,忽略完成事件内容');
}
} else {
console.log('🔧 [完成处理] 完成事件无内容,保持当前累积内容');
}
console.log('🔧 [完成处理] 最终选择:', {
currentLength: currentContent.length,
completionLength: event.payload.content?.length || 0,
finalLength: finalContent.length,
strategy: finalContent === currentContent ? 'KEEP_CURRENT' : 'USE_COMPLETION'
});
newHistory[targetIndex] = { ...newHistory[targetIndex], content: finalContent };
} else {
console.warn('🚨 [完成处理] 目标索引不存在:', targetIndex);
}
return newHistory;
});
setIsAnalyzing(false);
setIsChatting(false);
setIsInputAllowed(true);
setStreamingMessageIndex(null);
// 🎯 记录流式完成时间,用于状态同步保护
eventListenersRef.current.lastStreamCompletionTime = Date.now();
// 🎯 清理流式超时定时器
if (eventListenersRef.current.streamTimeoutId) {
clearTimeout(eventListenersRef.current.streamTimeoutId);
eventListenersRef.current.streamTimeoutId = undefined;
console.log('🧹 [流式完成] 清理超时定时器');
}
} else if (event.payload.content) {
// 流式更新
if (currentIsGeneratingSummary) {
console.log(`📝 [Stable] 总结流式更新: "${event.payload.content.substring(0, 50)}..."`);
setSummaryStreamContent(prev => prev + event.payload.content);
return;
}
// 普通聊天流式更新
console.log(`💬 [Stable] 普通聊天流式更新:`, {
streamingMessageIndex,
eventContent: event.payload.content.substring(0, 50) + '...',
eventContentLength: event.payload.content.length
});
// 🎯 流式事件到达,清理超时定时器(避免误报)
if (eventListenersRef.current.streamTimeoutId) {
clearTimeout(eventListenersRef.current.streamTimeoutId);
eventListenersRef.current.streamTimeoutId = undefined;
console.log('🧹 [流式到达] 清理超时定时器');
}
setChatHistory(prev => {
const newHistory = [...prev];
const targetIndex = streamingMessageIndex ?? newHistory.length - 1;
console.log(`💬 [Stable] 更新目标索引: ${targetIndex}, 历史长度: ${newHistory.length}`);
if (newHistory[targetIndex]) {
const currentContent = newHistory[targetIndex].content as string || '';
newHistory[targetIndex] = {
...newHistory[targetIndex],
content: currentContent + event.payload.content
};
console.log(`💬 [Stable] 更新成功,新内容长度: ${newHistory[targetIndex].content.length}`);
} else {
console.warn(`💬 [Stable] 目标索引 ${targetIndex} 不存在于历史记录中`);
}
return newHistory;
});
}
}, [streamingMessageIndex, chatHistory.length]);
// 🎯 新增:保存总结内容到数据库的函数
const handleSaveSummaryToDatabase = useCallback(async (summaryContent: string) => {
try {
// 只有在错题详情模式下才保存总结内容
if (props.mode !== 'EXISTING_MISTAKE_DETAIL') {
console.log('📝 [总结保存] 非错题详情模式,跳过保存');
return;
}
// 确保有 businessSessionId(即错题ID)
if (!props.businessSessionId) {
console.error('❌ [总结保存] 缺少错题ID,无法保存');
return;
}
console.log('💾 [总结保存] 开始保存总结内容到数据库...');
console.log('📄 [总结保存] 总结内容长度:', summaryContent.length);
console.log('🆔 [总结保存] 错题ID:', props.businessSessionId);
// 🎯 修复:解析总结内容,保持原始格式
const parseSummaryContent = (content: string) => {
console.log('📄 [总结解析] 原始内容长度:', content.length);
console.log('📄 [总结解析] 原始内容预览:', content.substring(0, 200) + '...');
// 🎯 策略1:如果内容较短或者没有明显的分段标识,保存到第一个字段
const lines = content.split('\n');
const hasNumberedSections = lines.some(line => /^\s*\d+\.\s*(核心知识点|错误分析|学习建议)/.test(line));
const hasMarkdownSections = lines.some(line => /^#+\s*(核心知识点|错误分析|学习建议)/.test(line));
if (!hasNumberedSections && !hasMarkdownSections) {
console.log('📄 [总结解析] 无明确分段,保存到mistake_summary');
return {
mistakeSummary: content.trim(),
userErrorAnalysis: null,
};
}
// 🎯 策略2:尝试分段,但保持更完整的内容
let mistakeSummary = '';
let userErrorAnalysis = '';
let currentSection = '';
for (const line of lines) {
const trimmedLine = line.trim();
// 检测章节标题
if (/^\s*\d+\.\s*核心知识点|^#+\s*核心知识点|题目解析|正确解法/.test(trimmedLine)) {
currentSection = 'mistake_summary';
} else if (/^\s*\d+\.\s*错误分析|^#+\s*错误分析|^\s*\d+\.\s*学习建议|^#+\s*学习建议|薄弱环节/.test(trimmedLine)) {
currentSection = 'user_error_analysis';
}
if (currentSection === 'mistake_summary') {
mistakeSummary += line + '\n';
} else if (currentSection === 'user_error_analysis') {
userErrorAnalysis += line + '\n';
} else if (!currentSection) {
// 如果还没有检测到分段,先放到第一个字段
mistakeSummary += line + '\n';
}
}
// 🎯 策略3:如果分段后某个字段为空,将所有内容保存到第一个字段
if (!mistakeSummary.trim() && !userErrorAnalysis.trim()) {
console.log('📄 [总结解析] 分段失败,保存完整内容到mistake_summary');
return {
mistakeSummary: content.trim(),
userErrorAnalysis: null,
};
}
console.log('📄 [总结解析] 分段结果:', {
mistakeSummaryLength: mistakeSummary.trim().length,
userErrorAnalysisLength: userErrorAnalysis.trim().length
});
return {
mistakeSummary: mistakeSummary.trim() || null,
userErrorAnalysis: userErrorAnalysis.trim() || null,
};
};
// 解析总结内容,分离 mistake_summary 和 user_error_analysis
const { mistakeSummary, userErrorAnalysis } = parseSummaryContent(summaryContent);
// 使用原始错题对象作为基础,只更新总结字段
const originalMistake = props.preloadedData?.originalMistake;
if (!originalMistake) {
console.error('❌ [总结保存] 缺少原始错题对象,无法更新');
return;
}
const mistakeUpdate = {
...originalMistake,
// 更新总结字段
mistake_summary: mistakeSummary,
user_error_analysis: userErrorAnalysis,
status: "completed", // 🎯 修复:设置状态为已完成
updated_at: new Date().toISOString(),
};
// 调用后端 API 更新错题记录
const response = await TauriAPI.updateMistake(mistakeUpdate);
console.log('✅ [总结保存] 总结内容已成功保存到数据库');
console.log('📊 [总结保存] 更新后的错题数据:', response);
// 🎯 通过回调通知父组件更新 selectedMistake 状态
if (props.onSaveRequest) {
console.log('📢 [总结保存] 通知父组件更新错题状态...');
await props.onSaveRequest({
businessSessionId: props.businessSessionId,
chatHistory,
thinkingContent,
summaryContent, // 传递总结内容
originalInputs: {
subject: props.preloadedData?.subject || '',
userQuestion: props.preloadedData?.userQuestion || '',
questionImages: []
}
});
console.log('✅ [总结保存] 父组件状态更新完成');
}
} catch (error) {
console.error('❌ [总结保存] 保存总结内容失败:', error);
}
}, [props.mode, props.businessSessionId, props.preloadedData, chatHistory, thinkingContent, props.onSaveRequest]);
// 设置事件监听器(仅在streamId变化时)
useEffect(() => {
if (!currentStreamId) {
return;
}
// 检查是否需要重新设置监听器(考虑总结生成状态变化)
const listenerKey = `${currentStreamId}_${isGeneratingSummary ? 'summary' : 'normal'}`;
if (eventListenersRef.current.currentStreamId === listenerKey) {
console.log('🎧 [Stable] 监听器已存在且状态匹配,跳过重复设置:', {
listenerKey,
isGeneratingSummary
});
return;
}
// 🎯 错题详情和回顾分析页面保护:如果正在流式传输,不要重设监听器
if ((props.mode === 'EXISTING_MISTAKE_DETAIL' || props.mode === 'REVIEW_SESSION_DETAIL') &&
eventListenersRef.current.isActivelyStreaming) {
console.log('🛡️ [流式传输保护] 正在流式传输,跳过监听器重设:', {
mode: props.mode,
currentStreamId,
isActivelyStreaming: eventListenersRef.current.isActivelyStreaming,
streamingMessageIndex,
isChatting
});
return;
}
console.log('🎧 [Stable] 需要重新设置监听器:', {
oldListenerKey: eventListenersRef.current.currentStreamId,
newListenerKey: listenerKey,
currentStreamId,
isGeneratingSummary,
chatHistoryLength: chatHistory.length
});
const setupListeners = async () => {
// 清理旧的监听器
eventListenersRef.current.unlistenContent?.();
eventListenersRef.current.unlistenThinking?.();
eventListenersRef.current.unlistenRag?.();
const { listen } = await import('@tauri-apps/api/event');
// 🎯 重要修复:使用稳定的判断逻辑避免事件名称混乱
let shouldUseContinuation = false;
if (props.mode === 'NEW_MISTAKE_ANALYSIS') {
// 错题分析:基于聊天历史长度判断
const isInitialStream = chatHistory.length <= 1;
shouldUseContinuation = !isInitialStream || isGeneratingSummary;
console.log('🎯 [事件类型判断] 错题分析模式:', {
chatHistoryLength: chatHistory.length,
isInitialStream,
isGeneratingSummary,
shouldUseContinuation,
mode: props.mode
});
} else if (props.mode === 'REVIEW_SESSION_DETAIL') {
// 🎯 回顾分析:使用更精确的判断条件
// 如果是总结生成,总是使用continuation流
if (isGeneratingSummary) {
shouldUseContinuation = true;
} else {
// 🎯 修复:基于更可靠的条件判断事件类型
const hasUserMessages = chatHistory.filter(msg => msg.role === 'user').length > 0;
const hasAssistantContent = chatHistory.some(msg =>
msg.role === 'assistant' &&
typeof msg.content === 'string' &&
msg.content.trim().length > 0
);
// 🎯 关键修复:对于回顾分析,只有当确实需要追问时才使用continuation流
// 当有用户消息时,说明是追问场景,应该使用 review_chat_stream_*
// 当只有助手内容但没有用户消息时,说明是初始分析完成,仍应使用 review_analysis_stream_*
shouldUseContinuation = hasUserMessages;
console.log('🎯 [事件类型判断] 回顾分析模式(修复版):', {
hasUserMessages,
hasAssistantContent,
shouldUseContinuation,
chatHistoryLength: chatHistory.length,
autoStartExecutedRef: autoStartExecutedRef.current,
eventType: shouldUseContinuation ? 'review_chat_stream' : 'review_analysis_stream'
});
}
} else if (props.mode === 'EXISTING_MISTAKE_DETAIL') {
// 🎯 错题详情页面修复:使用更稳定的判断逻辑,避免监听器频繁重设
if (isGeneratingSummary) {
// 总结生成总是使用continuation流
shouldUseContinuation = true;
} else {
// 🎯 关键修复:使用预加载数据来判断是否为初始加载
// 如果有预加载的聊天记录,说明这是已存在的错题,应该使用continuation流
const hasPreloadedChat = props.preloadedData?.chatHistory && props.preloadedData.chatHistory.length > 0;
// 或者当前聊天记录已经有用户消息(追问场景)
const hasUserMessages = chatHistory.filter(msg => msg.role === 'user').length > 0;
// 错题详情页面几乎总是使用continuation流,因为:
// 1. 如果有预加载聊天记录,说明已有对话历史
// 2. 如果用户发起追问,也应该使用continuation流
shouldUseContinuation = hasPreloadedChat || hasUserMessages || chatHistory.length > 1;
console.log('🎯 [事件类型判断] 错题详情模式(修复版):', {
hasPreloadedChat,
hasUserMessages,
chatHistoryLength: chatHistory.length,
isGeneratingSummary,
shouldUseContinuation,
mode: props.mode
});
}
} else {
// 其他模式(EXISTING_BATCH_TASK_DETAIL等):基于聊天历史长度判断
const isInitialStream = chatHistory.length <= 1;
shouldUseContinuation = !isInitialStream || isGeneratingSummary;
console.log('🎯 [事件类型判断] 其他模式:', {
chatHistoryLength: chatHistory.length,
isInitialStream,
isGeneratingSummary,
shouldUseContinuation,
mode: props.mode
});
}
const eventNames = shouldUseContinuation
? props.serviceConfig.streamEventNames.continuationStream(currentStreamId)
: props.serviceConfig.streamEventNames.initialStream(currentStreamId);
console.log('🎧 [Stable] 设置新的事件监听器:', {
streamId: currentStreamId,
chatHistoryLength: chatHistory.length,
shouldUseContinuation,
isGeneratingSummary,
eventNames,
mode: props.mode,
status: props.preloadedData?.status,
eventType: shouldUseContinuation ? 'CONTINUATION' : 'INITIAL',
autoStartExecuted: autoStartExecutedRef.current,
isAnalyzing,
isChatting
});
// 设置主内容监听器
console.log('🎧 [Stable] 正在设置主内容监听器,事件名:', eventNames.data);
console.log('🎧 [Stable] 监听器设置时的状态:', {
currentStreamId,
isGeneratingSummary: isGeneratingSummaryRef.current,
mode: props.mode,
chatHistoryLength: chatHistory.length,
shouldUseContinuation,
eventType: shouldUseContinuation ? 'CONTINUATION' : 'INITIAL'
});
eventListenersRef.current.unlistenContent = await listen(eventNames.data, (event: any) => {
console.log('🎧 [Stable] 主内容监听器收到事件:', {
eventName: eventNames.data,
isGeneratingSummary: isGeneratingSummaryRef.current,
payload: event.payload,
payloadContentLength: event.payload?.content?.length || 0,
isComplete: event.payload?.is_complete || false,
timestamp: new Date().toISOString(),
// 🎯 新增:追踪重复接收
listenerKey: eventListenersRef.current.currentStreamId,
mode: props.mode,
// 🎯 新增:当前聊天状态
currentChatHistoryLength: chatHistory.length,
currentStreamingIndex: streamingMessageIndex,
isChatting,
isAnalyzing
});
// 🎯 新增:防止重复处理相同事件
const eventId = `${eventNames.data}_${event.payload?.content?.substring(0, 10) || 'empty'}_${event.payload?.is_complete}`;
if (eventListenersRef.current.lastEventId === eventId) {
console.warn('🚨 [Stable] 检测到重复事件,跳过处理:', eventId);
return;
}
eventListenersRef.current.lastEventId = eventId;
// 🎯 错题详情和回顾分析页面:标记流式传输状态
if (props.mode === 'EXISTING_MISTAKE_DETAIL' || props.mode === 'REVIEW_SESSION_DETAIL') {
if (!event.payload?.is_complete) {
eventListenersRef.current.isActivelyStreaming = true;
} else {
eventListenersRef.current.isActivelyStreaming = false;
}
}
// 🎯 新增:验证事件处理条件
console.log('🎯 [事件处理] 准备处理事件,当前状态:', {
hasValidStreamingIndex: streamingMessageIndex !== null,
chatHistoryLength: chatHistory.length,
targetIndex: streamingMessageIndex ?? (chatHistory.length - 1),
isActivelyStreaming: eventListenersRef.current.isActivelyStreaming
});
handleStreamEvent(event, false);
});
// 设置思维链监听器
if (enableChainOfThought) {
eventListenersRef.current.unlistenThinking = await listen(eventNames.reasoning, (event: any) => {
handleStreamEvent(event, true);
});
}
// 🎯 修复:重新添加被遗漏的RAG来源事件监听器
if (enableRag && eventNames.ragSources) {
console.log('🎧 [Stable] 正在设置RAG来源监听器,事件名:', eventNames.ragSources);
eventListenersRef.current.unlistenRag = await listen(eventNames.ragSources, (event: any) => {
console.log(`📚 [Stable] 收到RAG来源信息:`, event.payload);
if (event.payload && event.payload.sources) {
setChatHistory(prev => {
const newHistory = [...prev];
const targetIndex = streamingMessageIndex ?? newHistory.length - 1;
if (newHistory[targetIndex]) {
newHistory[targetIndex] = {
...newHistory[targetIndex],
rag_sources: event.payload.sources
};
console.log(`✅ [Stable] RAG来源信息已更新到消息索引: ${targetIndex}`);
} else {
console.warn(`⚠️ [Stable] RAG事件:找不到目标消息索引: ${targetIndex}`);
}
return newHistory;
});
}
});
}
eventListenersRef.current.currentStreamId = listenerKey;
// eventListenersRef.current.lastEventType = isInitialStream ? 'initial' : 'continuation'; // 临时简化
};
setupListeners();
return () => {
console.log('🧹 [Stable] 清理事件监听器:', { streamId: currentStreamId });
eventListenersRef.current.unlistenContent?.();
eventListenersRef.current.unlistenThinking?.();
eventListenersRef.current.unlistenRag?.();
eventListenersRef.current.currentStreamId = undefined;
// 🎯 清理流式超时定时器
if (eventListenersRef.current.streamTimeoutId) {
clearTimeout(eventListenersRef.current.streamTimeoutId);
eventListenersRef.current.streamTimeoutId = undefined;
console.log('🧹 [监听器清理] 清理超时定时器');
}
};
}, [
currentStreamId,
isGeneratingSummary,
// 🎯 修复:错题详情页面不再依赖chatHistory.length,但回顾分析页面需要依赖以确保事件名称切换
// NEW_MISTAKE_ANALYSIS和REVIEW_SESSION_DETAIL需要基于chatHistory.length判断事件类型
...(props.mode === 'NEW_MISTAKE_ANALYSIS' || props.mode === 'EXISTING_BATCH_TASK_DETAIL' || props.mode === 'REVIEW_SESSION_DETAIL'
? [chatHistory.length]
: [])
]); // 🎯 REVIEW_SESSION_DETAIL重新加入chatHistory.length依赖,确保初次分析->追问时监听器重设
// 处理总结生成请求 - 使用聊天API但添加特殊标识区分总结内容
const handleGenerateSummary = useCallback(async (summaryPrompt: string) => {
console.log('🔍 [总结生成] 检查streamId状态:', {
currentStreamId,
mode: props.mode,
businessSessionId: props.businessSessionId
});
if (!currentStreamId) {
console.error('❌ 无法生成总结:缺少streamId');
return;
}
// 重置总结状态
console.log('📝 [总结生成] 开始重置状态');
setSummaryStreamContent('');
setSummaryStreamComplete(false);
setIsGeneratingSummary(true);
console.log('📝 [总结生成] 状态重置完成,isGeneratingSummary=true');
// 在总结提示词中添加特殊标识
const specialSummaryPrompt = `[SUMMARY_REQUEST] ${summaryPrompt}`;
// 创建总结请求消息(仅用于内部处理,不显示在聊天记录中)
const summaryRequestMessage: ChatMessage = {
role: 'user',
content: specialSummaryPrompt,
timestamp: new Date().toISOString(),
};
try {
console.log('📝 开始流式生成总结(带特殊标识)...');
// 调用后端API - 使用临时的聊天历史,不保存总结请求到正式记录
console.log(`📡 准备调用 continueUserChat 生成总结,使用的 streamId: ${currentStreamId}`);
console.log('🚫 [总结请求] 使用临时聊天历史,不会保存到数据库');
// 创建临时聊天历史用于总结生成,但不影响实际的聊天记录
const tempChatHistory = [...chatHistory, summaryRequestMessage];
console.log('📡 [总结生成] 当前事件监听器状态:', {
currentStreamId,
chatHistoryLength: chatHistory.length,
tempChatHistoryLength: tempChatHistory.length,
currentEventType: eventListenersRef.current.lastEventType,
isGeneratingSummary: isGeneratingSummaryRef.current,
mode: props.mode,
businessSessionId: props.businessSessionId,
expectedEventName: `continue_chat_stream_${currentStreamId}`
});
await props.serviceConfig.apiProvider.continueUserChat({
streamIdForEvents: currentStreamId,
businessId: props.businessSessionId,
fullChatHistory: tempChatHistory, // 使用临时历史,包含总结请求
enableChainOfThought: false, // 总结不需要思维链
enableRag: false, // 总结不需要RAG
ragTopK: 0
});
} catch (error) {
console.error('❌ 总结生成失败:', error);
alert('总结生成失败: ' + error);
setIsGeneratingSummary(false);
setSummaryStreamComplete(true);
}
}, [currentStreamId, props.serviceConfig.apiProvider, props.businessSessionId, chatHistory]);
// 发送聊天消息 - 完全重写,修复所有流式问题
const handleSendMessage = async () => {
if (!currentMessage.trim() || !currentStreamId) return;
const userMessage: ChatMessage = {
role: 'user',
content: currentMessage,
timestamp: new Date().toISOString(),
};
const newChatHistory = [...chatHistory, userMessage];
setChatHistory(newChatHistory);
setCurrentMessage('');
setIsChatting(true);
try {
if (useStreamMode) {
// 流式对话 - 全新改进版本
console.log('💬 开始流式对话...');
// 创建空的助手消息等待流式填充
const assistantMessage: ChatMessage = {
role: 'assistant',
content: '',
timestamp: new Date().toISOString(),
};
const streamingHistory = [...newChatHistory, assistantMessage];
const newStreamingIndex = streamingHistory.length - 1;
// 🎯 关键修复:先更新聊天历史,再设置streamingMessageIndex
setChatHistory(streamingHistory);
// 🎯 延迟设置streamingMessageIndex,确保聊天历史已经更新
setTimeout(() => {
console.log(`🎯 [追问修复] 设置streamingMessageIndex: ${newStreamingIndex}, 聊天历史长度: ${streamingHistory.length}`);
console.log(`🎯 [追问修复] 目标消息验证:`, {
targetMessage: streamingHistory[newStreamingIndex],
role: streamingHistory[newStreamingIndex]?.role,
isAssistant: streamingHistory[newStreamingIndex]?.role === 'assistant'
});
setStreamingMessageIndex(newStreamingIndex);
}, 10); // 短暂延迟,让状态更新完成
// 调用后端API
console.log(`📡 准备调用 continueUserChat,使用的 streamId: ${currentStreamId}`);
console.log(`📡 [追问调试] 当前状态:`, {
newStreamingIndex: newStreamingIndex,
chatHistoryLength: newChatHistory.length,
fullHistoryLength: streamingHistory.length,
currentStreamId,
businessId: props.businessSessionId,
// 🎯 新增:追问时的关键状态
autoStartExecuted: autoStartExecutedRef.current,
currentEventListenerKey: eventListenersRef.current.currentStreamId,
expectedEventName: `review_chat_stream_${currentStreamId}`,
mode: props.mode
});
// 🎯 新增:确保在发送请求前监听器已正确设置
console.log(`🎧 [追问前检查] 监听器状态:`, {
hasContentListener: !!eventListenersRef.current.unlistenContent,
currentListenerKey: eventListenersRef.current.currentStreamId,
expectedListenerKey: `${currentStreamId}_${isGeneratingSummary ? 'summary' : 'normal'}`
});
await props.serviceConfig.apiProvider.continueUserChat({
streamIdForEvents: currentStreamId,
businessId: props.businessSessionId,
fullChatHistory: newChatHistory,
enableChainOfThought,
enableRag,
ragTopK
});
console.log(`✅ [追问调试] continueUserChat 调用完成`);
// 🎯 新增:设置超时机制,防止流式事件缺失导致永久等待
const streamTimeoutId = setTimeout(() => {
if (isChatting && streamingMessageIndex !== null) {
console.warn('⚠️ [流式超时] 10秒内未收到流式事件,强制清理状态');
setIsChatting(false);
setStreamingMessageIndex(null);
setIsInputAllowed(true);
}
}, 10000); // 10秒超时
// 将超时ID存储到ref中,以便在事件处理中清理
eventListenersRef.current.streamTimeoutId = streamTimeoutId;
} else {
// 传统非流式对话暂不支持
throw new Error('传统对话模式暂不支持,请使用流式模式');
}
} catch (error) {
console.error('❌ 对话失败:', error);
alert('对话失败: ' + error);
setStreamingMessageIndex(null);
setIsChatting(false);
setIsInputAllowed(true);
// 🎯 清理流式超时定时器
if (eventListenersRef.current.streamTimeoutId) {
clearTimeout(eventListenersRef.current.streamTimeoutId);
eventListenersRef.current.streamTimeoutId = undefined;
console.log('🧹 [错误处理] 清理超时定时器');
}
} finally {
// isChatting 状态由事件监听器在流结束后设置,或者在错误/超时时手动设置
}
};
// 保存到错题库
const handleSaveToLibrary = async () => {
try {
// 🎯 修复:正确处理思维链数据的保存
const chatHistoryWithThinking = chatHistory.map((message, index) => {
// 如果是assistant消息且有思维链,则添加thinking_content字段
if (message.role === 'assistant' && thinkingContent.has(index)) {
const thinkingText = thinkingContent.get(index);
console.log(`💾 [保存] 为索引${index}的assistant消息添加思维链,长度:`, thinkingText?.length || 0);
return {
...message,
thinking_content: thinkingText
};
}
return message;
});
console.log('💾 [保存] 处理后的聊天历史,包含思维链的消息数:',
chatHistoryWithThinking.filter(msg => msg.thinking_content).length);
console.log('💾 准备保存数据:', {
businessSessionId: props.businessSessionId,
chatHistoryLength: chatHistoryWithThinking.length,
thinkingContentSize: thinkingContent.size,
ocrResult: ocrResult,
temp_id: analysisResult?.temp_id || currentStreamId,
originalInputs: { subject, userQuestion, questionImagesCount: questionImages.length }
});
// 确保传递正确的temp_id
const temp_id = analysisResult?.temp_id || currentStreamId;
console.log('💾 UniversalAppChatHost传递的temp_id:', temp_id);
await props.onSaveRequest({
businessSessionId: props.businessSessionId,
chatHistory: chatHistoryWithThinking,
thinkingContent,
ocrResult: ocrResult || (analysisResult ? {
ocr_text: analysisResult.initial_data.ocr_text,
tags: analysisResult.initial_data.tags,
mistake_type: analysisResult.initial_data.mistake_type,
temp_id: temp_id === null ? undefined : temp_id
} : null),
temp_id: temp_id === null ? undefined : temp_id,
// 传递总结内容
summaryContent: summaryStreamContent && summaryStreamComplete ? summaryStreamContent : undefined,
originalInputs: {
subject,
userQuestion,
questionImages
}
});
// 只在NEW_MISTAKE_ANALYSIS模式下重置状态
if (props.mode === 'NEW_MISTAKE_ANALYSIS') {
handleReset();
}
} catch (error) {
console.error('保存失败:', error);
alert('保存失败: ' + error);
}
};
// 重置分析
const handleReset = () => {
// 清理timeout
if (updateTimeoutRef.current) {
clearTimeout(updateTimeoutRef.current);
updateTimeoutRef.current = null;
}
setAnalysisResult(null);
setChatHistory([]);
setCurrentMessage('');
setStreamingMessageIndex(null);
setOcrResult(null);
setIsOcrComplete(false);
setIsOcrInProgress(false);
setIsAnalyzing(false);
setUserQuestion('');
setQuestionImages([]);
// 🎯 重要:重置总结状态
setSummaryStreamContent('');
setSummaryStreamComplete(false);
setIsGeneratingSummary(false);
console.log('🔄 [重置分析] 总结状态已重置');
setThinkingContent(new Map());
setIsInputAllowed(false);
};
// 分库接口类型
interface SubLibrary {
id: string;
name: string;
description?: string;
created_at: string;
updated_at: string;
document_count: number;
chunk_count: number;
}
// 分库选择相关状态
const [subLibraries, setSubLibraries] = useState<SubLibrary[]>([]);
const [selectedLibraries, setSelectedLibraries] = useState<string[]>([]);
const [showLibrarySelector, setShowLibrarySelector] = useState(false);
const librarySelectorRef = useRef<HTMLDivElement>(null);
// 加载分库列表
const loadSubLibraries = useCallback(async () => {
try {
const libraries = await TauriAPI.getRagSubLibraries();
setSubLibraries(libraries);
console.log('🎯 加载分库列表完成,数量:', libraries.length);
} catch (error) {
console.error('加载分库列表失败:', error);
}
}, []); // 移除selectedLibraries.length依赖,避免循环触发
// 切换分库选择
const toggleLibrarySelection = (libraryId: string) => {
console.log('🎯 切换知识库选择:', libraryId);
setSelectedLibraries(prev => {
const newSelection = prev.includes(libraryId)
? prev.filter(id => id !== libraryId)
: [...prev, libraryId];
console.log('🎯 知识库选择更新:', prev, '->', newSelection);
return newSelection;
});
};
// 全选/取消全选分库
const toggleAllLibraries = () => {
if (selectedLibraries.length === subLibraries.length) {
// 当前全选状态,执行取消全选
setSelectedLibraries([]);
} else {
// 当前非全选状态,执行全选
setSelectedLibraries(subLibraries.map(lib => lib.id));
}
};
// 处理点击外部关闭分库选择器
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (librarySelectorRef.current && !librarySelectorRef.current.contains(event.target as Node)) {
setShowLibrarySelector(false);
}
};
if (showLibrarySelector) {
document.addEventListener('mousedown', handleClickOutside);
}
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [showLibrarySelector]);
// 组件挂载时加载分库列表
useEffect(() => {
if (enableRag) {
loadSubLibraries();
}
}, [enableRag, loadSubLibraries]);
// 初始化默认选中的分库 - 只在首次加载分库时执行
useEffect(() => {
if (subLibraries.length > 0 && selectedLibraries.length === 0) {
// 优先使用props中指定的默认分库
if (props.serviceConfig.defaultSelectedLibraries && props.serviceConfig.defaultSelectedLibraries.length > 0) {
console.log('🎯 使用props指定的默认分库');
setSelectedLibraries(props.serviceConfig.defaultSelectedLibraries);
} else {
// 否则默认选择所有分库(仅在初始化时)
console.log('🎯 初始化时默认选择所有分库');
setSelectedLibraries(subLibraries.map(lib => lib.id));
}
}
}, [subLibraries.length]); // 只在分库列表变化时触发,不依赖selectedLibraries
// 处理props传入的默认选中分库(用于组件重新加载的情况)
useEffect(() => {
if (props.serviceConfig.defaultSelectedLibraries && props.serviceConfig.defaultSelectedLibraries.length > 0) {
console.log('🎯 检测到props中的默认分库设置');
setSelectedLibraries(props.serviceConfig.defaultSelectedLibraries);
}
}, [props.serviceConfig.defaultSelectedLibraries]);
// 渲染分析界面 - 左右分栏布局
const renderAnalysisView = () => (
<div className="analysis-layout">
{/* 左侧上传栏 */}
<div className="left-panel">
<div className="cherry-app">
<div className="app-header">
<div className="app-title">
<img src="/dslogo1.png" alt="DeepStudent 深度学者" className="app-logo" />
</div>
<p className="app-subtitle">
{props.mode === 'NEW_MISTAKE_ANALYSIS' ? '上传多张题目图片获取AI增强解析' : '查看历史分析并进行深度追问'}
</p>
</div>
{/* 科目显示 - 只读 */}
<div className="readonly-subject-display">
<span className="subject-badge">{subject || '未选择科目'}</span>
</div>
{/* 图片上传区域 - 完全按照HTML模板 */}
{props.mode === 'NEW_MISTAKE_ANALYSIS' ? (
<div
className={`upload-card ${questionImages.length > 0 ? 'has-files' : ''}`}
id="uploadArea"
onClick={handleFileUploadClick}
>
<div className="upload-icon">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M18 15V18H6V15H4V18C4 19.1 4.9 20 6 20H18C19.1 20 20 19.1 20 18V15H18Z" fill="currentColor"/>
<path d="M12 5L7 10H10V14H14V10H17L12 5Z" fill="currentColor"/>
</svg>
</div>
<p className="upload-text">
{questionImages.length > 0 ? '已添加题目图片' : '拖放题目图片到此处'}
</p>
<p className="upload-hint">
{questionImages.length > 0 ? '可继续添加或拖放更多图片' : '或点击选择文件 (最多9张JPG/PNG)'}
</p>
{questionImages.length > 0 && (
<div className="counter-badge">{questionImages.length}/9</div>
)}
<input
type="file"
multiple
accept="image/*"
onChange={handleImageUpload}
className="file-input"
id="fileInput"
/>
</div>
) : (
// 错题详情模式:显示现有图片
<div className="upload-card readonly-mode">
<div className="upload-icon">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M18 15V18H6V15H4V18C4 19.1 4.9 20 6 20H18C19.1 20 20 19.1 20 18V15H18Z" fill="currentColor"/>
<path d="M12 5L7 10H10V14H14V10H17L12 5Z" fill="currentColor"/>
</svg>
</div>
<p className="upload-text">题目图片</p>
<p className="upload-hint">点击下方图片查看大图</p>
</div>
)}
{/* 图片预览列表 */}
<div className="preview-list" id="previewList">
{(() => {
const imagesToDisplay = props.mode === 'NEW_MISTAKE_ANALYSIS'
? questionImageUrls
: (questionImageUrls.length > 0 ? questionImageUrls : (props.preloadedData?.questionImageUrls || []));
return imagesToDisplay.map((url, index) => (
<div key={index} className="preview-item">
<img
src={url}
alt={`题目图片 ${index + 1}`}
className="preview-image"
onClick={() => openImageViewer(index)}
/>
{props.mode === 'NEW_MISTAKE_ANALYSIS' && (
<div
className="preview-remove"
onClick={(e) => {
e.stopPropagation();
removeImage(index);
}}
>
<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M18 6L6 18" stroke="white" strokeWidth="2" strokeLinecap="round"/>
<path d="M6 6L18 18" stroke="white" strokeWidth="2" strokeLinecap="round"/>
</svg>
</div>
)}
</div>
));
})()}
</div>
{/* 问题描述输入 */}
<div className="input-container">
<label className="input-label">问题描述 (可选)</label>
{props.mode === 'NEW_MISTAKE_ANALYSIS' ? (
<textarea
className="cherry-textarea"
value={userQuestion}
onChange={(e) => setUserQuestion(e.target.value)}
placeholder="例如:我需要这道微积分题的详细解题步骤..."
/>
) : (
<div className="cherry-textarea readonly">
{userQuestion || props.preloadedData?.userQuestion || '无问题描述'}
</div>
)}
</div>
{/* RAG开关 - 按照HTML模板 */}
{props.mode === 'NEW_MISTAKE_ANALYSIS' && (
<>
<div className="rag-controls-container">
<div className="rag-toggle" id="ragToggle" onClick={() => setEnableRag(!enableRag)}>
<input
type="checkbox"
id="ragCheckbox"
checked={enableRag}
readOnly
/>
<span className="rag-switch">
<span className="rag-slider"></span>
</span>
<span className="rag-label">启用RAG知识库增强</span>
</div>
{/* 分库选择下拉框 */}
{enableRag && (
<div className="rag-library-selector" ref={librarySelectorRef}>
<div
className="library-selector-trigger"
onClick={() => setShowLibrarySelector(!showLibrarySelector)}
>
<span className="library-selector-label">
知识库范围 ({selectedLibraries.length}/{subLibraries.length})
</span>
<span className="library-selector-arrow">
{showLibrarySelector ? '▲' : '▼'}
</span>
</div>
{showLibrarySelector && (
<div className="library-selector-dropdown">
<div className="library-selector-header">
<button
className="library-selector-action"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
toggleAllLibraries();
}}
>
{selectedLibraries.length === subLibraries.length ? '取消全选' : '全选'}
</button>
</div>
<div className="library-selector-list">
{subLibraries.length > 0 ? (
subLibraries.map(library => (
<div
key={library.id}
className={`library-selector-item ${selectedLibraries.includes(library.id) ? 'selected' : ''}`}
onClick={(e) => {
// 如果点击的是checkbox或其容器,不处理外层点击
if ((e.target as HTMLElement).closest('.library-checkbox')) {
console.log('🎯 点击了checkbox区域,跳过外层处理');
return;
}
console.log('🎯 点击了知识库项目外层区域:', library.id);
e.preventDefault();
e.stopPropagation();
toggleLibrarySelection(library.id);
}}
>
<div className="library-checkbox" onClick={(e) => e.stopPropagation()}>
<input
type="checkbox"
checked={selectedLibraries.includes(library.id)}
onChange={(e) => {
console.log('🎯 checkbox onChange事件:', library.id);
e.preventDefault();
e.stopPropagation();
toggleLibrarySelection(library.id);
}}
/>
</div>
<div className="library-info">
<div className="library-name">{library.name}</div>
<div className="library-stats">
📄 {library.document_count} | 📝 {library.chunk_count}
</div>
</div>
</div>
))
) : (
<div className="library-selector-empty">
<div style={{ padding: '20px', textAlign: 'center', color: 'var(--cherry-text-secondary)', fontSize: '13px' }}>
暂无可用的知识库分库
</div>
</div>
)}
</div>
</div>
)}
</div>
)}
</div>
<div className="rag-hint">
{enableRag
? `连接RAG知识库获取更精准的解析 (已选择 ${selectedLibraries.length} 个分库)`
: '连接RAG知识库获取更精准的解析'
}
</div>
</>
)}
{/* 主要操作按钮 */}
{props.mode === 'NEW_MISTAKE_ANALYSIS' ? (
<button
onClick={handleAnalyze}
disabled={isOcrInProgress || isAnalyzing}
className="analyze-btn"
>
<svg className="btn-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M20 7H4V5H20V7Z" fill="#111"/>
<path d="M20 11H4V9H20V11Z" fill="#111"/>
<path d="M4 15H20V13H4V15Z" fill="#111"/>
<path d="M4 19H20V17H4V19Z" fill="#111"/>
</svg>
{isOcrInProgress ? 'OCR进行中...' : isAnalyzing ? '深度分析中...' : '开始深度分析'}
</button>
) : (
<button
onClick={props.onExitRequest}
className="analyze-btn back-mode"
>
← 返回列表
</button>
)}
{/* 次要操作按钮 */}
{analysisResult && props.mode === 'NEW_MISTAKE_ANALYSIS' && (
<div className="secondary-buttons">
<button onClick={handleSaveToLibrary} className="save-btn-secondary">
💾 保存到错题库
</button>
<button onClick={handleReset} className="reset-btn-secondary">
🔄 重新分析
</button>
</div>
)}
</div>
</div>
{/* 右侧结果栏 */}
<div className="right-panel">
{!ocrResult && !analysisResult && props.mode === 'NEW_MISTAKE_ANALYSIS' ? (
<div className="empty-result">
<div className="empty-icon">
<img src="/dslogo2.png" alt="Deep Student" className="empty-logo" />
</div>
<h3>等待分析</h3>
<p>请在左侧上传题目图片并点击"开始分析"</p>
</div>
) : (
<div className="analysis-result">
<div className="result-header">
<h3>📊 分析结果</h3>
{isAnalyzing && (
<div className="analyzing-indicator">
<span className="spinner">⏳</span>
<span>分析中...</span>
</div>
)}
</div>
{/* OCR结果区域 - 立即显示 */}
{ocrResult && (
<div className="result-info">
<div className="info-item">
<strong>题目类型:</strong>
<span className="info-value">{ocrResult.mistake_type}</span>
</div>
<div className="info-item">
<strong>标签:</strong>
<div className="tags">
{ocrResult.tags.map((tag, index) => (
<span key={index} className="tag">{tag}</span>
))}
</div>
</div>
<div className="info-item">
<strong>OCR文本:</strong>
<div className="ocr-text">{ocrResult.ocr_text}</div>
</div>
</div>
)}
{/* AI解答区域 */}
{isOcrComplete && (
<div className={`chat-container ${isChatFullscreen ? 'chat-fullscreen' : ''}`}>
<div className="chat-history">
{chatHistory.map((message, index) => {
const isStreaming = streamingMessageIndex === index;
const thinking = thinkingContent.get(index);
// 检查是否为最后一条AI消息
const isLastAssistantMessage = message.role === 'assistant' &&
index === chatHistory.length - 1 &&
chatHistory.slice(index + 1).every(m => m.role !== 'assistant');
// 调试:总结框显示条件和聊天历史
if (message.role === 'assistant') {
console.log(`🎯 [总结框] 检查消息 ${index}:`, {
isLastAssistantMessage,
messageRole: message.role,
messageIndex: index,
chatHistoryLength: chatHistory.length,
isLastIndex: index === chatHistory.length - 1,
messageContent: typeof message.content === 'string' ? message.content.substring(0, 50) + '...' : '[多媒体内容]',
mode: props.mode,
summaryStreamContent: summaryStreamContent.substring(0, 50) + '...',
summaryStreamComplete
});
}
return (
<MessageWithThinking
key={index}
content={message.content}
thinkingContent={thinking}
isStreaming={isStreaming}
role={message.role as 'user' | 'assistant'}
timestamp={message.timestamp}
ragSources={message.rag_sources}
showSummaryBox={isLastAssistantMessage && props.mode !== 'REVIEW_SESSION_DETAIL'}
chatHistory={chatHistory}
subject={props.preloadedData?.subject}
mistakeId={props.mode === 'EXISTING_MISTAKE_DETAIL' ? props.businessSessionId :
props.mode === 'NEW_MISTAKE_ANALYSIS' ? 'new_analysis' : undefined}
reviewSessionId={props.mode === 'REVIEW_SESSION_DETAIL' ? props.businessSessionId : undefined}
onGenerateSummary={(prompt) => handleGenerateSummary(prompt)}
currentStreamId={currentStreamId ?? undefined}
isGenerating={isGeneratingSummary}
summaryStreamContent={summaryStreamContent}
summaryStreamComplete={summaryStreamComplete}
/>
);
})}
{isAnalyzing && chatHistory.length === 0 && (
<div className="message assistant">
<div className="message-content typing">
<span className="typing-indicator">
<span></span>
<span></span>
<span></span>
</span>
AI正在思考中...
</div>
</div>
)}
{isChatting && streamingMessageIndex === null && (
<div className="message assistant">
<div className="message-content typing">
<span className="typing-indicator">
<span></span>
<span></span>
<span></span>
</span>
正在思考中...
</div>
</div>
)}
</div>
{/* 在OCR开始后就显示输入框,但在分析过程中禁用发送功能 */}
{(analysisResult || isAnalyzing || isOcrInProgress) && (
<div className="chat-input">
<input
type="text"
value={currentMessage}
onChange={(e) => setCurrentMessage(e.target.value)}
placeholder={isOcrInProgress ? "OCR中,请等待..." : isAnalyzing ? "分析中,请等待..." : "继续提问..."}
onKeyDown={(e) => e.key === 'Enter' && !isOcrInProgress && !isAnalyzing && handleSendMessage()}
disabled={isChatting || isOcrInProgress || isAnalyzing}
/>
<button
onClick={handleSendMessage}
disabled={isChatting || !currentMessage.trim() || isOcrInProgress || isAnalyzing}
className="send-button"
>
{isChatting ? '⏳' : (isOcrInProgress || isAnalyzing) ? '⏸️' : '📤'}
</button>
<button
className="chat-fullscreen-toggle"
onClick={handleChatFullscreenToggle}
title={isChatFullscreen ? '退出全屏' : '全屏模式'}
>
{isChatFullscreen ? '🔲' : '📱'}
</button>
</div>
)}
</div>
)}
</div>
)}
</div>
</div>
);
return (
<>
{/* 始终渲染分析界面 */}
{renderAnalysisView()}
{/* 图片查看器 */}
<ImageViewer
images={questionImageUrls}
currentIndex={currentImageIndex}
isOpen={imageViewerOpen}
onClose={() => setImageViewerOpen(false)}
onNext={() => setCurrentImageIndex(prev => (prev + 1) % questionImageUrls.length)}
onPrev={() => setCurrentImageIndex(prev => (prev - 1 + questionImageUrls.length) % questionImageUrls.length)}
/>
</>
);
}
export default UniversalAppChatHost;
| 93,037 | UniversalAppChatHost | tsx | zh | tsx | code | {"qsc_code_num_words": 9927, "qsc_code_num_chars": 93037.0, "qsc_code_mean_word_length": 5.40817971, "qsc_code_frac_words_unique": 0.1318626, "qsc_code_frac_chars_top_2grams": 0.03129249, "qsc_code_frac_chars_top_3grams": 0.00905247, "qsc_code_frac_chars_top_4grams": 0.00707806, "qsc_code_frac_chars_dupe_5grams": 0.28349507, "qsc_code_frac_chars_dupe_6grams": 0.22765288, "qsc_code_frac_chars_dupe_7grams": 0.1802671, "qsc_code_frac_chars_dupe_8grams": 0.1438337, "qsc_code_frac_chars_dupe_9grams": 0.11418034, "qsc_code_frac_chars_dupe_10grams": 0.09469704, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00674469, "qsc_code_frac_chars_whitespace": 0.29562432, "qsc_code_size_file_byte": 93037.0, "qsc_code_num_lines": 2488.0, "qsc_code_num_chars_line_max": 151.0, "qsc_code_num_chars_line_mean": 37.3942926, "qsc_code_frac_chars_alphabet": 0.80834084, "qsc_code_frac_chars_comments": 0.08659995, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.40621814, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00050968, "qsc_code_frac_chars_string_length": 0.08590257, "qsc_code_frac_chars_long_word_length": 0.01705107, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
000haoji/deep-student | src/hooks/useSystemSettings.ts | /**
* Custom hook for managing system settings
* Extracted from Settings component to reduce complexity
*/
import { useState, useEffect, useCallback } from 'react';
import { invoke as tauriInvoke } from '@tauri-apps/api/core';
// 系统设置接口
export interface SystemSettings {
autoSave: boolean;
theme: string;
language: string;
enableNotifications: boolean;
maxChatHistory: number;
debugMode: boolean;
enableAnkiConnect: boolean;
}
// 检查是否在Tauri环境中
const isTauri = typeof window !== 'undefined' && window.__TAURI_INTERNALS__;
const invoke = isTauri ? tauriInvoke : null;
// 默认设置
const DEFAULT_SETTINGS: SystemSettings = {
autoSave: true,
theme: 'light',
language: 'zh-CN',
enableNotifications: true,
maxChatHistory: 100,
debugMode: false,
enableAnkiConnect: true
};
export const useSystemSettings = () => {
const [settings, setSettings] = useState<SystemSettings>(DEFAULT_SETTINGS);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
// 加载系统设置
const loadSettings = useCallback(async () => {
setLoading(true);
try {
if (invoke) {
const settingsPromises = Object.keys(DEFAULT_SETTINGS).map(async (key) => {
try {
const value = await invoke('get_setting', { key }) as string;
return { key, value };
} catch {
return { key, value: String(DEFAULT_SETTINGS[key as keyof SystemSettings]) };
}
});
const settingsResults = await Promise.all(settingsPromises);
const loadedSettings: SystemSettings = { ...DEFAULT_SETTINGS };
for (const { key, value } of settingsResults) {
const settingKey = key as keyof SystemSettings;
// 类型转换
switch (settingKey) {
case 'autoSave':
case 'enableNotifications':
case 'debugMode':
loadedSettings[settingKey] = value === 'true';
break;
case 'maxChatHistory':
loadedSettings[settingKey] = parseInt(value, 10) || DEFAULT_SETTINGS[settingKey];
break;
default:
(loadedSettings as any)[settingKey] = value;
}
}
setSettings(loadedSettings);
}
} catch (error) {
console.error('加载系统设置失败:', error);
setSettings(DEFAULT_SETTINGS);
} finally {
setLoading(false);
}
}, []);
// 保存单个设置
const saveSetting = useCallback(async (key: keyof SystemSettings, value: any) => {
setSaving(true);
try {
if (invoke) {
await invoke('save_setting', { key, value: String(value) });
setSettings(prev => ({ ...prev, [key]: value }));
return true;
}
return false;
} catch (error) {
console.error(`保存设置 ${key} 失败:`, error);
return false;
} finally {
setSaving(false);
}
}, []);
// 保存所有设置
const saveAllSettings = useCallback(async (newSettings: SystemSettings) => {
setSaving(true);
try {
if (invoke) {
const savePromises = Object.entries(newSettings).map(([key, value]) =>
invoke('save_setting', { key, value: String(value) })
);
await Promise.all(savePromises);
setSettings(newSettings);
return true;
}
return false;
} catch (error) {
console.error('保存系统设置失败:', error);
return false;
} finally {
setSaving(false);
}
}, []);
// 重置设置为默认值
const resetSettings = useCallback(async () => {
return await saveAllSettings(DEFAULT_SETTINGS);
}, [saveAllSettings]);
// 更新设置(本地状态,不保存)
const updateSetting = useCallback(<K extends keyof SystemSettings>(
key: K,
value: SystemSettings[K]
) => {
setSettings(prev => ({ ...prev, [key]: value }));
}, []);
// 批量更新设置(本地状态,不保存)
const updateSettings = useCallback((updates: Partial<SystemSettings>) => {
setSettings(prev => ({ ...prev, ...updates }));
}, []);
// 应用主题
const applyTheme = useCallback(async (theme: string) => {
const success = await saveSetting('theme', theme);
if (success) {
// 应用主题到DOM
document.documentElement.setAttribute('data-theme', theme);
document.body.className = theme === 'dark' ? 'dark-theme' : 'light-theme';
}
return success;
}, [saveSetting]);
// 验证设置
const validateSettings = useCallback((settingsToValidate: Partial<SystemSettings>) => {
const errors: string[] = [];
if (settingsToValidate.maxChatHistory !== undefined) {
if (settingsToValidate.maxChatHistory < 10 || settingsToValidate.maxChatHistory > 1000) {
errors.push('最大聊天历史记录数量必须在10-1000之间');
}
}
if (settingsToValidate.theme !== undefined) {
if (!['light', 'dark', 'auto'].includes(settingsToValidate.theme)) {
errors.push('主题必须是light、dark或auto');
}
}
if (settingsToValidate.language !== undefined) {
if (!['zh-CN', 'en-US'].includes(settingsToValidate.language)) {
errors.push('语言必须是zh-CN或en-US');
}
}
return errors;
}, []);
// 获取设置摘要(用于显示)
const getSettingsSummary = useCallback(() => {
return {
configuredItems: Object.keys(settings).length,
autoSaveEnabled: settings.autoSave,
currentTheme: settings.theme,
debugModeEnabled: settings.debugMode,
maxHistorySize: settings.maxChatHistory
};
}, [settings]);
// 初始化时加载设置
useEffect(() => {
loadSettings();
}, [loadSettings]);
// 应用主题到DOM
useEffect(() => {
if (!loading) {
document.documentElement.setAttribute('data-theme', settings.theme);
document.body.className = settings.theme === 'dark' ? 'dark-theme' : 'light-theme';
}
}, [settings.theme, loading]);
return {
// 状态
settings,
loading,
saving,
// 方法
loadSettings,
saveSetting,
saveAllSettings,
resetSettings,
updateSetting,
updateSettings,
applyTheme,
validateSettings,
getSettingsSummary,
// 便利属性
isAutoSaveEnabled: settings.autoSave,
isDarkTheme: settings.theme === 'dark',
isDebugMode: settings.debugMode
};
}; | 6,153 | useSystemSettings | ts | en | typescript | code | {"qsc_code_num_words": 519, "qsc_code_num_chars": 6153.0, "qsc_code_mean_word_length": 7.17726397, "qsc_code_frac_words_unique": 0.31021195, "qsc_code_frac_chars_top_2grams": 0.03221477, "qsc_code_frac_chars_top_3grams": 0.00724832, "qsc_code_frac_chars_top_4grams": 0.01208054, "qsc_code_frac_chars_dupe_5grams": 0.13503356, "qsc_code_frac_chars_dupe_6grams": 0.07731544, "qsc_code_frac_chars_dupe_7grams": 0.04241611, "qsc_code_frac_chars_dupe_8grams": 0.02308725, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00371666, "qsc_code_frac_chars_whitespace": 0.25662279, "qsc_code_size_file_byte": 6153.0, "qsc_code_num_lines": 225.0, "qsc_code_num_chars_line_max": 96.0, "qsc_code_num_chars_line_mean": 27.34666667, "qsc_code_frac_chars_alphabet": 0.810669, "qsc_code_frac_chars_comments": 0.04891923, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.23563218, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.05313514, "qsc_code_frac_chars_long_word_length": 0.00375876, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
000haoji/deep-student | src/hooks/useNotification.ts | /**
* Custom hook for managing notifications and messages
* Extracted from various components to reduce complexity
*/
import { useState, useCallback, useRef, useEffect } from 'react';
export interface NotificationMessage {
id: string;
type: 'success' | 'error' | 'warning' | 'info';
title?: string;
text: string;
duration?: number;
persistent?: boolean;
}
export const useNotification = () => {
const [notifications, setNotifications] = useState<NotificationMessage[]>([]);
const timeoutRefs = useRef<Map<string, any>>(new Map());
// 显示通知
const showNotification = useCallback((
type: NotificationMessage['type'],
text: string,
options?: {
title?: string;
duration?: number;
persistent?: boolean;
}
) => {
const id = `notification-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
const duration = options?.duration ?? (type === 'error' ? 5000 : 3000);
const notification: NotificationMessage = {
id,
type,
text,
title: options?.title,
duration,
persistent: options?.persistent || false
};
setNotifications(prev => [...prev, notification]);
// 自动删除(除非是持久化通知)
if (!notification.persistent && duration > 0) {
const timeoutId = setTimeout(() => {
removeNotification(id);
}, duration);
timeoutRefs.current.set(id, timeoutId);
}
return id;
}, []);
// 删除通知
const removeNotification = useCallback((id: string) => {
setNotifications(prev => prev.filter(n => n.id !== id));
// 清除定时器
const timeoutId = timeoutRefs.current.get(id);
if (timeoutId) {
clearTimeout(timeoutId);
timeoutRefs.current.delete(id);
}
}, []);
// 清除所有通知
const clearAllNotifications = useCallback(() => {
// 清除所有定时器
timeoutRefs.current.forEach(timeoutId => clearTimeout(timeoutId));
timeoutRefs.current.clear();
setNotifications([]);
}, []);
// 便利方法
const showSuccess = useCallback((text: string, options?: Omit<Parameters<typeof showNotification>[2], 'title'> & { title?: string }) => {
return showNotification('success', text, options);
}, [showNotification]);
const showError = useCallback((text: string, options?: Omit<Parameters<typeof showNotification>[2], 'title'> & { title?: string }) => {
return showNotification('error', text, options);
}, [showNotification]);
const showWarning = useCallback((text: string, options?: Omit<Parameters<typeof showNotification>[2], 'title'> & { title?: string }) => {
return showNotification('warning', text, options);
}, [showNotification]);
const showInfo = useCallback((text: string, options?: Omit<Parameters<typeof showNotification>[2], 'title'> & { title?: string }) => {
return showNotification('info', text, options);
}, [showNotification]);
// 显示加载通知
const showLoading = useCallback((text: string, options?: { title?: string }) => {
return showNotification('info', text, {
...options,
persistent: true,
duration: 0
});
}, [showNotification]);
// 更新现有通知
const updateNotification = useCallback((id: string, updates: Partial<Omit<NotificationMessage, 'id'>>) => {
setNotifications(prev => prev.map(notification =>
notification.id === id
? { ...notification, ...updates }
: notification
));
}, []);
// 检查是否有特定类型的通知
const hasNotificationType = useCallback((type: NotificationMessage['type']) => {
return notifications.some(n => n.type === type);
}, [notifications]);
// 获取特定类型的通知数量
const getNotificationCount = useCallback((type?: NotificationMessage['type']) => {
if (type) {
return notifications.filter(n => n.type === type).length;
}
return notifications.length;
}, [notifications]);
// 批量操作的便利方法
const showBatchResult = useCallback((
results: { success: number; failed: number; total: number },
operation: string
) => {
if (results.failed === 0) {
showSuccess(`${operation}成功完成,处理了 ${results.success} 项`);
} else if (results.success === 0) {
showError(`${operation}失败,${results.failed} 项处理失败`);
} else {
showWarning(
`${operation}部分完成:${results.success} 项成功,${results.failed} 项失败`
);
}
}, [showSuccess, showError, showWarning]);
// 显示操作确认
const showOperationProgress = useCallback((operation: string, current: number, total: number) => {
const id = `progress-${operation}`;
updateNotification(id, {
type: 'info',
text: `${operation}中... (${current}/${total})`,
persistent: true
});
return id;
}, [updateNotification]);
// 清理函数
useEffect(() => {
return () => {
// 组件卸载时清理所有定时器
timeoutRefs.current.forEach(timeoutId => clearTimeout(timeoutId));
timeoutRefs.current.clear();
};
}, []);
return {
// 状态
notifications,
hasNotifications: notifications.length > 0,
// 基础方法
showNotification,
removeNotification,
clearAllNotifications,
updateNotification,
// 便利方法
showSuccess,
showError,
showWarning,
showInfo,
showLoading,
// 查询方法
hasNotificationType,
getNotificationCount,
// 特殊用途方法
showBatchResult,
showOperationProgress
};
}; | 5,277 | useNotification | ts | en | typescript | code | {"qsc_code_num_words": 444, "qsc_code_num_chars": 5277.0, "qsc_code_mean_word_length": 7.42567568, "qsc_code_frac_words_unique": 0.29054054, "qsc_code_frac_chars_top_2grams": 0.02335456, "qsc_code_frac_chars_top_3grams": 0.03093722, "qsc_code_frac_chars_top_4grams": 0.04246285, "qsc_code_frac_chars_dupe_5grams": 0.24021838, "qsc_code_frac_chars_dupe_6grams": 0.19138611, "qsc_code_frac_chars_dupe_7grams": 0.19138611, "qsc_code_frac_chars_dupe_8grams": 0.17227783, "qsc_code_frac_chars_dupe_9grams": 0.17227783, "qsc_code_frac_chars_dupe_10grams": 0.12496209, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00509338, "qsc_code_frac_chars_whitespace": 0.21868486, "qsc_code_size_file_byte": 5277.0, "qsc_code_num_lines": 188.0, "qsc_code_num_chars_line_max": 140.0, "qsc_code_num_chars_line_mean": 28.06914894, "qsc_code_frac_chars_alphabet": 0.79456706, "qsc_code_frac_chars_comments": 0.0587455, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.23703704, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01972625, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
000haoji/deep-student | src/hooks/useApiConfig.ts | /**
* Custom hook for managing API configurations
* Extracted from Settings component to reduce complexity
*/
import { useState, useEffect, useCallback } from 'react';
import { invoke as tauriInvoke } from '@tauri-apps/api/core';
// API配置接口
export interface ApiConfig {
id: string;
name: string;
apiKey: string;
baseUrl: string;
model: string;
isMultimodal: boolean;
isReasoning: boolean;
enabled: boolean;
modelAdapter: string;
}
// 模型分配接口
export interface ModelAssignments {
model1_config_id: string | null;
model2_config_id: string | null;
review_analysis_model_config_id: string | null;
anki_card_model_config_id: string | null;
embedding_model_config_id: string | null;
reranker_model_config_id: string | null;
summary_model_config_id: string | null;
}
// 检查是否在Tauri环境中
const isTauri = typeof window !== 'undefined' && window.__TAURI_INTERNALS__;
const invoke = isTauri ? tauriInvoke : null;
export const useApiConfig = () => {
const [apiConfigs, setApiConfigs] = useState<ApiConfig[]>([]);
const [modelAssignments, setModelAssignments] = useState<ModelAssignments>({
model1_config_id: null,
model2_config_id: null,
review_analysis_model_config_id: null,
anki_card_model_config_id: null,
embedding_model_config_id: null,
reranker_model_config_id: null,
summary_model_config_id: null,
});
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [testingApi, setTestingApi] = useState<string | null>(null);
// 加载API配置
const loadApiConfigs = useCallback(async () => {
setLoading(true);
try {
if (invoke) {
const [configs, assignments] = await Promise.all([
invoke('get_api_configurations').catch(() => []) as Promise<ApiConfig[]>,
invoke('get_model_assignments').catch(() => ({
model1_config_id: null,
model2_config_id: null,
review_analysis_model_config_id: null,
anki_card_model_config_id: null,
embedding_model_config_id: null,
reranker_model_config_id: null,
summary_model_config_id: null,
})) as Promise<ModelAssignments>
]);
setApiConfigs(configs || []);
setModelAssignments(assignments || {
model1_config_id: null,
model2_config_id: null,
review_analysis_model_config_id: null,
anki_card_model_config_id: null,
embedding_model_config_id: null,
reranker_model_config_id: null,
summary_model_config_id: null,
});
}
} catch (error) {
console.error('加载API配置失败:', error);
} finally {
setLoading(false);
}
}, []);
// 保存API配置
const saveApiConfigs = useCallback(async (configs: ApiConfig[]) => {
setSaving(true);
try {
if (invoke) {
await invoke('save_api_configurations', { configs });
setApiConfigs(configs);
return true;
}
return false;
} catch (error) {
console.error('保存API配置失败:', error);
return false;
} finally {
setSaving(false);
}
}, []);
// 保存模型分配
const saveModelAssignments = useCallback(async (assignments: ModelAssignments) => {
setSaving(true);
try {
if (invoke) {
await invoke('save_model_assignments', { assignments });
setModelAssignments(assignments);
return true;
}
return false;
} catch (error) {
console.error('保存模型分配失败:', error);
return false;
} finally {
setSaving(false);
}
}, []);
// 测试API连接
const testApiConnection = useCallback(async (config: ApiConfig) => {
setTestingApi(config.id);
try {
if (invoke) {
const result = await invoke('test_api_connection', {
apiKey: config.apiKey,
baseUrl: config.baseUrl
}) as boolean;
return result;
}
return false;
} catch (error) {
console.error('API连接测试失败:', error);
return false;
} finally {
setTestingApi(null);
}
}, []);
// 添加API配置
const addApiConfig = useCallback((config: Omit<ApiConfig, 'id'>) => {
const newConfig: ApiConfig = {
...config,
id: Date.now().toString()
};
const updatedConfigs = [...apiConfigs, newConfig];
setApiConfigs(updatedConfigs);
return newConfig;
}, [apiConfigs]);
// 更新API配置
const updateApiConfig = useCallback((id: string, updates: Partial<ApiConfig>) => {
const updatedConfigs = apiConfigs.map(config =>
config.id === id ? { ...config, ...updates } : config
);
setApiConfigs(updatedConfigs);
return updatedConfigs.find(c => c.id === id);
}, [apiConfigs]);
// 删除API配置
const deleteApiConfig = useCallback((id: string) => {
const updatedConfigs = apiConfigs.filter(config => config.id !== id);
setApiConfigs(updatedConfigs);
// 如果删除的配置被分配给模型,清除分配
const updatedAssignments = { ...modelAssignments };
if (modelAssignments.model1_config_id === id) {
updatedAssignments.model1_config_id = null;
}
if (modelAssignments.model2_config_id === id) {
updatedAssignments.model2_config_id = null;
}
if (updatedAssignments.model1_config_id !== modelAssignments.model1_config_id ||
updatedAssignments.model2_config_id !== modelAssignments.model2_config_id) {
setModelAssignments(updatedAssignments);
}
return updatedConfigs;
}, [apiConfigs, modelAssignments]);
// 获取多模态配置(用于模型1)
const getMultimodalConfigs = useCallback(() => {
return apiConfigs.filter(config => config.isMultimodal && config.enabled);
}, [apiConfigs]);
// 获取所有启用的配置(用于模型2)
const getEnabledConfigs = useCallback(() => {
return apiConfigs.filter(config => config.enabled);
}, [apiConfigs]);
// 获取配置按ID
const getConfigById = useCallback((id: string | null) => {
if (!id) return null;
return apiConfigs.find(config => config.id === id) || null;
}, [apiConfigs]);
// 验证模型分配
const validateModelAssignments = useCallback(() => {
const errors: string[] = [];
if (modelAssignments.model1_config_id) {
const model1Config = getConfigById(modelAssignments.model1_config_id);
if (!model1Config) {
errors.push('模型1配置不存在');
} else if (!model1Config.isMultimodal) {
errors.push('模型1必须是多模态配置');
} else if (!model1Config.enabled) {
errors.push('模型1配置未启用');
}
}
if (modelAssignments.model2_config_id) {
const model2Config = getConfigById(modelAssignments.model2_config_id);
if (!model2Config) {
errors.push('模型2配置不存在');
} else if (!model2Config.enabled) {
errors.push('模型2配置未启用');
}
}
return errors;
}, [modelAssignments, getConfigById]);
// 初始化时加载配置
useEffect(() => {
loadApiConfigs();
}, [loadApiConfigs]);
return {
// 状态
apiConfigs,
modelAssignments,
loading,
saving,
testingApi,
// 方法
loadApiConfigs,
saveApiConfigs,
saveModelAssignments,
testApiConnection,
addApiConfig,
updateApiConfig,
deleteApiConfig,
// 便利方法
getMultimodalConfigs,
getEnabledConfigs,
getConfigById,
validateModelAssignments
};
};
| 7,273 | useApiConfig | ts | en | typescript | code | {"qsc_code_num_words": 660, "qsc_code_num_chars": 7273.0, "qsc_code_mean_word_length": 6.86212121, "qsc_code_frac_words_unique": 0.22121212, "qsc_code_frac_chars_top_2grams": 0.07948775, "qsc_code_frac_chars_top_3grams": 0.0609406, "qsc_code_frac_chars_top_4grams": 0.05630382, "qsc_code_frac_chars_dupe_5grams": 0.27003754, "qsc_code_frac_chars_dupe_6grams": 0.20269375, "qsc_code_frac_chars_dupe_7grams": 0.14683153, "qsc_code_frac_chars_dupe_8grams": 0.14683153, "qsc_code_frac_chars_dupe_9grams": 0.11062045, "qsc_code_frac_chars_dupe_10grams": 0.11062045, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00615496, "qsc_code_frac_chars_whitespace": 0.24047848, "qsc_code_size_file_byte": 7273.0, "qsc_code_num_lines": 257.0, "qsc_code_num_chars_line_max": 86.0, "qsc_code_num_chars_line_mean": 28.29961089, "qsc_code_frac_chars_alphabet": 0.81372194, "qsc_code_frac_chars_comments": 0.04399835, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.31884058, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.03236013, "qsc_code_frac_chars_long_word_length": 0.01265641, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
000haoji/deep-student | src/types/neovis.d.ts | declare module 'neovis.js' {
export interface Neo4jConfig {
serverUrl: string;
serverUser: string;
serverPassword: string;
serverDatabase?: string;
driverConfig?: {
encrypted?: string;
trust?: string;
};
}
export interface NeovisConfig {
containerId: string;
neo4j: Neo4jConfig;
labels?: {
[key: string]: {
label?: string;
value?: string;
color?: string;
size?: string;
community?: string;
caption?: string | string[];
title_properties?: string[];
font?: {
color?: string;
size?: number;
face?: string;
};
};
};
relationships?: {
[key: string]: {
thickness?: string;
color?: string;
caption?: boolean | string;
};
};
initialCypher?: string;
consoleDebug?: boolean;
visConfig?: any;
}
export interface NeovisNode {
id: string;
labels: string[];
properties: Record<string, any>;
}
export interface NeovisRelationship {
id: string;
type: string;
startNode: string;
endNode: string;
properties: Record<string, any>;
}
export class NeoVis {
constructor(config: NeovisConfig);
render(): void;
reload(): void;
clearNetwork(): void;
stabilize(): void;
renderWithCypher(cypher: string): void;
registerOnEvent(event: string, callback: (event: any) => void): void;
_addNode(nodeId: string, node: NeovisNode): void;
_addRelationship(relationshipId: string, relationship: NeovisRelationship): void;
// 网络实例(可选,有些版本可能暴露)
_network?: any;
_nodes?: any;
_edges?: any;
}
export default NeoVis;
} | 1,715 | neovis.d | ts | en | typescript | code | {"qsc_code_num_words": 145, "qsc_code_num_chars": 1715.0, "qsc_code_mean_word_length": 6.88275862, "qsc_code_frac_words_unique": 0.48965517, "qsc_code_frac_chars_top_2grams": 0.06012024, "qsc_code_frac_chars_top_3grams": 0.03406814, "qsc_code_frac_chars_top_4grams": 0.05611222, "qsc_code_frac_chars_dupe_5grams": 0.0741483, "qsc_code_frac_chars_dupe_6grams": 0.0741483, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00246711, "qsc_code_frac_chars_whitespace": 0.2909621, "qsc_code_size_file_byte": 1715.0, "qsc_code_num_lines": 76.0, "qsc_code_num_chars_line_max": 86.0, "qsc_code_num_chars_line_mean": 22.56578947, "qsc_code_frac_chars_alphabet": 0.81825658, "qsc_code_frac_chars_comments": 0.01166181, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.2173913, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0053066, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
000haoji/deep-student | src/types/cogni-graph.ts | export interface ProblemCard {
id: string;
content_problem: string;
content_insight: string;
status: 'unsolved' | 'solved';
embedding?: number[];
created_at: string;
last_accessed_at: string;
access_count: number;
source_excalidraw_path?: string;
}
export interface Tag {
id: string;
name: string;
tag_type: TagType;
level: number;
description?: string;
created_at: string;
}
export type TagType =
| 'KnowledgeArea'
| 'Topic'
| 'Concept'
| 'Method'
| 'Difficulty';
export type RelationshipType =
| 'HAS_TAG'
| 'IS_VARIATION_OF'
| 'USES_GENERAL_METHOD'
| 'CONTRASTS_WITH'
| 'PARENT_OF'
| 'CHILD_OF'
| 'RELATED_TO'
| 'PREREQUISITE_OF';
export interface Relationship {
from_id: string;
to_id: string;
relationship_type: RelationshipType;
}
export interface SearchRequest {
query: string;
limit?: number;
libraries?: string[];
}
export interface SearchResult {
card: ProblemCard;
score: number;
matched_by: string[];
}
export interface RecommendationRequest {
card_id: string;
limit?: number;
}
export interface Recommendation {
card: ProblemCard;
relationship_type: RelationshipType;
confidence: number;
reasoning: string;
}
export interface CreateCardRequest {
content_problem: string;
content_insight: string;
tags: string[];
source_excalidraw_path?: string;
}
export interface CreateTagRequest {
name: string;
tag_type: TagType;
parent_id?: string;
description?: string;
}
export interface TagHierarchy {
tag: Tag;
children: TagHierarchy[];
parent?: Tag;
}
export interface GraphNode {
id: string;
label: string;
type: 'ProblemCard' | 'Tag';
properties: Record<string, any>;
}
export interface GraphEdge {
id: string;
from: string;
to: string;
type: RelationshipType;
properties?: Record<string, any>;
}
export interface GraphData {
nodes: GraphNode[];
edges: GraphEdge[];
}
export interface Neo4jConfig {
uri: string;
username: string;
password: string;
database?: string;
}
export interface GraphConfig {
neo4j: Neo4jConfig;
vector_dimensions: number;
similarity_threshold: number;
max_search_results: number;
recommendation_limit: number;
}
// Tauri API types
export interface KnowledgeGraphAPI {
initializeKnowledgeGraph: (config: GraphConfig) => Promise<string>;
createProblemCard: (request: CreateCardRequest) => Promise<string>;
getProblemCard: (cardId: string) => Promise<ProblemCard | null>;
searchKnowledgeGraph: (request: SearchRequest) => Promise<SearchResult[]>;
getAiRecommendations: (request: RecommendationRequest) => Promise<Recommendation[]>;
searchSimilarCards: (cardId: string, limit?: number) => Promise<SearchResult[]>;
getCardsByTag: (tagName: string, limit?: number) => Promise<ProblemCard[]>;
getAllTags: () => Promise<Tag[]>;
getGraphConfig: () => Promise<GraphConfig>;
updateGraphConfig: (config: GraphConfig) => Promise<string>;
testNeo4jConnection: (config: GraphConfig) => Promise<string>;
processHandwrittenInput: (imageData: string) => Promise<CreateCardRequest>;
// Tag management APIs
createTag: (request: CreateTagRequest) => Promise<string>;
getTagHierarchy: (rootTagId?: string) => Promise<TagHierarchy[]>;
getTagsByType: (tagType: TagType) => Promise<Tag[]>;
initializeDefaultTagHierarchy: () => Promise<string>;
} | 3,357 | cogni-graph | ts | en | typescript | code | {"qsc_code_num_words": 317, "qsc_code_num_chars": 3357.0, "qsc_code_mean_word_length": 7.49842271, "qsc_code_frac_words_unique": 0.3785489, "qsc_code_frac_chars_top_2grams": 0.10096761, "qsc_code_frac_chars_top_3grams": 0.06184266, "qsc_code_frac_chars_top_4grams": 0.03786285, "qsc_code_frac_chars_dupe_5grams": 0.12200252, "qsc_code_frac_chars_dupe_6grams": 0.101809, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00141844, "qsc_code_frac_chars_whitespace": 0.15996425, "qsc_code_size_file_byte": 3357.0, "qsc_code_num_lines": 144.0, "qsc_code_num_chars_line_max": 87.0, "qsc_code_num_chars_line_mean": 23.3125, "qsc_code_frac_chars_alphabet": 0.84148936, "qsc_code_frac_chars_comments": 0.0119154, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.19354839, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.05003014, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
007/hashcash-js | crc32.js | var Crc32Tab = new Array( /* CRC polynomial 0xEDB88320 */
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,
0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,
0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,
0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,
0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,
0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,
0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,
0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,
0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,
0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,
0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,
0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,
0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,
0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,
0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,
0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,
0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D);
function Crc32Add(crc,c)
{
return Crc32Tab[(crc^c)&0xFF]^((crc>>8)&0x00FFFFFF);
}
function hc_crc32(str)
{
var n;
var crc;
crc=0xFFFFFFFF;
for (n = 0; n < str.length; n++)
{
crc=Crc32Add(crc,str.charCodeAt(n));
}
return (~crc)&0xFFFFFFFF;
}
function Hex32(val)
{
var n;
var str1;
var str2;
n=val&0xFFFF;
str1=n.toString(16).toLowerCase();
while (str1.length<4)
{
str1="0"+str1;
}
n=(val>>>16)&0xFFFF;
str2=n.toString(16).toLowerCase();
while (str2.length<4)
{
str2="0"+str2;
}
return ""+str2+str1;
}
function hc_HashFunc(x) { return Hex32(hc_crc32(x)); }
| 3,525 | crc32 | js | en | javascript | code | {"qsc_code_num_words": 353, "qsc_code_num_chars": 3525.0, "qsc_code_mean_word_length": 8.41926346, "qsc_code_frac_words_unique": 0.82152975, "qsc_code_frac_chars_top_2grams": 0.00740242, "qsc_code_frac_chars_top_3grams": 0.00471063, "qsc_code_frac_chars_top_4grams": 0.01480485, "qsc_code_frac_chars_dupe_5grams": 0.01816958, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.46369048, "qsc_code_frac_chars_whitespace": 0.04680851, "qsc_code_size_file_byte": 3525.0, "qsc_code_num_lines": 75.0, "qsc_code_num_chars_line_max": 90.0, "qsc_code_num_chars_line_mean": 47.0, "qsc_code_frac_chars_alphabet": 0.42083333, "qsc_code_frac_chars_comments": 0.00879433, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.02941176, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00057257, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.74606356, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.05882353, "qsc_codejavascript_num_statement_line": 0.07352941, "qsc_codejavascript_score_lines_no_logic": 0.13235294, "qsc_codejavascript_frac_words_legal_var_name": 0.83333333, "qsc_codejavascript_frac_words_legal_func_name": 0.5, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 1, "qsc_code_frac_chars_digital": 1, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 1, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0} |
007gzs/meeting | miniprogram/pages/meeting/detail.wxml | <wxs module="timeUtils" src="../../utils/timeUtils.wxs"></wxs>
<!--pages/meeting/detail.wxml-->
<view class="page">
<view class="page__hd">
<view class='weui-cell'>
<view class='weui-cell__bd'>
<view class="page__title">{{info.name}}</view>
<view class="page__desc">{{info.description}}</view>
</view>
<view class="weui-cell__ft" wx:if="{{show_home}}">
<button class="weui-btn" size="mini" bindtap='home'>返回首页</button>
</view>
</view>
</view>
<view class="page_bd page__bd_spacing body-with-footer">
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell">
<view class="weui-cell__bd">会议室</view>
<view class="weui-cell__ft">{{info.room.name}}</view>
</view>
<view class="weui-cell">
<view class="weui-cell__bd">时间</view>
<view class="weui-cell__ft">{{info.date}} {{timeUtils.formatTime(info.start_time)}} - {{timeUtils.formatTime(info.end_time)}}</view>
</view>
<view class="weui-cell">
<view class="weui-cell__bd">发起人</view>
<view class="weui-cell__ft"><image src="{{info.user.avatarurl}}" style="margin-right: 10rpx;vertical-align: middle;width:48rpx; height: 48rpx;"></image>{{info.user.nickname}}</view>
</view>
<view class="weui-cell" bindtap="attendees_show_change">
<view class="weui-cell__bd">参与人</view>
<view class="weui-cell__ft attendees {{attendees_show ? 'attendees_detail' : 'attendees_info'}}">
<view wx:for="{{info.attendees}}" wx:key="id" wx:if="{{item.avatarurl}}">
<image src="{{item.avatarurl}}" style="margin-right: 1rpx;vertical-align: middle;width:32rpx; height: 32rpx;"></image>
<block wx:if="{{attendees_show && item.nickname}}">
{{item.nickname}}
</block>
</view>
<view wx:if="{{!attendees_show}}">
({{info.attendees.length}})
</view>
<view wx:elif="{{no_icon_attendee_num > 0}}">
及其他{{no_icon_attendee_num}}人
</view>
</view>
</view>
</view>
</view>
<view class="weui-footer footer">
<view class="weui-flex">
<view class="weui-flex__item">
<button size="mini" open-type="share">分享</button>
</view>
<view class="weui-flex__item">
<button size="mini" bindtap='leave' wx:if="{{joined}}">取消参加</button>
<button size="mini" bindtap='join' wx:else>参加</button>
</view>
<block wx:if="{{owner}}">
<view class="weui-flex__item">
<button size="mini" bindtap='edit'>修改</button>
</view>
<view class="weui-flex__item">
<button size="mini" bindtap='del'>取消</button>
</view>
</block>
</view>
</view>
</view>
| 2,857 | detail | wxml | en | unknown | unknown | {} | 0 | {} |
007gzs/meeting | miniprogram/pages/meeting/edit.wxml | <wxs module="timeUtils" src="../../utils/timeUtils.wxs"></wxs>
<!--pages/meeting/edit.wxml-->
<view class="page">
<view class="page_bd page__bd_spacing weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">名称</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" placeholder="请输入名称" value="{{name}}" data-obj="name" bindinput='bindKeyInput'/>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">描述</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" placeholder="请输入描述" value="{{description}}" data-obj="description" bindinput='bindKeyInput'/>
</view>
</view>
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell">
<view class="weui-cell__bd">会议室</view>
<view class="weui-cell__ft">{{room.name}}</view>
</view>
<view class="weui-cell">
<view class="weui-cell__bd">时间</view>
<view class="weui-cell__ft">{{date}} {{timeUtils.formatTime(start_time)}} - {{timeUtils.formatTime(end_time)}}</view>
</view>
</view>
<block wx:if="{{!user_info.avatarurl}}">
<view class="weui-cells__title">需要通过微信授权获得你的微信名和头像</view>
<button class="weui-btn" open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="onGetUserInfo">授权登录</button>
</block>
<button class="weui-btn" type="primary" bindtap="save" wx:else>保存</button>
</view>
</view>
| 1,654 | edit | wxml | en | unknown | unknown | {} | 0 | {} |
007gzs/meeting | miniprogram/pages/meeting/detail.js | "use strict";
// pages/meeting/detail.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
meeting_id: 0,
owner: false,
joined: false,
attendees_show: false,
no_icon_attendee_num: 0,
info: {}
},
refresh: function () {
if (this.data.meeting_id <= 0) {
return
}
app.api.api_meeting_info({ meeting_id: this.data.meeting_id }).then(res => {
let no_icon_attendee_num = 0
for (let i in res.attendees) {
if (!res.attendees[i].avatarurl) {
no_icon_attendee_num += 1
}
}
this.setData({
info: res,
no_icon_attendee_num: no_icon_attendee_num,
owner: res.is_manager
})
app.userInfo().then(res => {
let joined = false
for(let i in this.data.info.attendees){
if (this.data.info.attendees[i].id == res.id){
joined = true
break
}
}
this.setData({
joined: joined
})
})
})
},
attendees_show_change: function(){
this.setData({ attendees_show: !this.data.attendees_show})
},
home: function () {
app.gotoHome()
},
join: function(){
app.api.api_meeting_join({ meeting_id: this.data.meeting_id }).then(res => {
this.refresh()
})
},
leave: function(){
app.api.api_meeting_leave({ meeting_id: this.data.meeting_id }).then(res => {
this.refresh()
})
},
edit: function(){
wx.navigateTo({
url: 'edit?meeting_id=' + this.data.meeting_id,
})
},
del: function(){
wx.showModal({
title: '提示',
content: '确定要删除吗?',
success: sm => {
if (sm.confirm) {
app.api.api_meeting_cancel({ meeting_id: this.data.meeting_id }).then(res => {
wx.navigateBack()
})
}
}
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({ show_home: getCurrentPages().length == 1})
let meeting_id = options.meeting_id
if(meeting_id){
this.setData({ meeting_id: meeting_id})
}else{
wx.showToast({
title: '参数错误',
icon: 'none'
})
wx.navigateBack()
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
this.refresh()
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
let title = '会议'
if (this.data.info.name){
title += " - " + this.data.info.name
}
return {
title: title,
path: '/pages/meeting/detail?meeting_id='+this.data.meeting_id
}
}
}) | 2,895 | detail | js | en | javascript | code | {"qsc_code_num_words": 299, "qsc_code_num_chars": 2895.0, "qsc_code_mean_word_length": 4.94314381, "qsc_code_frac_words_unique": 0.30769231, "qsc_code_frac_chars_top_2grams": 0.11569689, "qsc_code_frac_chars_top_3grams": 0.07036536, "qsc_code_frac_chars_top_4grams": 0.08051421, "qsc_code_frac_chars_dupe_5grams": 0.1962111, "qsc_code_frac_chars_dupe_6grams": 0.13937754, "qsc_code_frac_chars_dupe_7grams": 0.10419486, "qsc_code_frac_chars_dupe_8grams": 0.10419486, "qsc_code_frac_chars_dupe_9grams": 0.05953992, "qsc_code_frac_chars_dupe_10grams": 0.05953992, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00301811, "qsc_code_frac_chars_whitespace": 0.31329879, "qsc_code_size_file_byte": 2895.0, "qsc_code_num_lines": 157.0, "qsc_code_num_chars_line_max": 89.0, "qsc_code_num_chars_line_mean": 18.43949045, "qsc_code_frac_chars_alphabet": 0.74044266, "qsc_code_frac_chars_comments": 0.09810017, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.16071429, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.03101072, "qsc_code_frac_chars_long_word_length": 0.012634, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.0, "qsc_codejavascript_num_statement_line": 0.02678571, "qsc_codejavascript_score_lines_no_logic": 0.05357143, "qsc_codejavascript_frac_words_legal_var_name": 0.71428571, "qsc_codejavascript_frac_words_legal_func_name": null, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0} |
007gzs/meeting | miniprogram/pages/meeting/my.js | // pages/meeting/my.js
"use strict";
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
loading: true
},
check_td_data: function () {
this.data.td_data = app.meetings.getTdData(
this.data.rooms,
this.data.meetings,
this.data.time_range,
{ selected: false },
this.selectComponent("#date_select").data.select_date
)
this.selectComponent("#time_table").set_data({
titles: this.data.rooms, labels: this.data.time_range, td_data: this.data.td_data
})
if(this.data.loading){
this.setData({ loading: false})
}
},
data_click: function(e){
if (!e.detail.data_id){
return
}
wx.navigateTo({
url: '../meeting/detail?meeting_id=' + e.detail.data_id,
})
},
date_select_change: function (e) {
this.refresh()
},
refresh: function () {
app.api.api_meeting_my_meetings({
date: this.selectComponent("#date_select").data.select_date
}).then(res => {
const start_time = app.time.parseTime(res.start_time).value()
const end_time = app.time.parseTime(res.end_time).value()
let time_range = []
for (let time = start_time; time <= end_time; time += 1800) {
const t = app.time.valueToTime(time)
const id = t.string(2)
time_range.push({ id: id, text: t.minute == 0 ? id : "", data: t })
}
this.data.meetings = res.meetings
this.data.rooms = res.rooms
this.data.time_range = time_range
this.selectComponent("#date_select").setDateRange(res.start_date, res.end_date)
this.check_td_data()
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
this.refresh()
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
}
}) | 2,097 | my | js | en | javascript | code | {"qsc_code_num_words": 236, "qsc_code_num_chars": 2097.0, "qsc_code_mean_word_length": 5.0, "qsc_code_frac_words_unique": 0.33898305, "qsc_code_frac_chars_top_2grams": 0.07457627, "qsc_code_frac_chars_top_3grams": 0.03305085, "qsc_code_frac_chars_top_4grams": 0.04322034, "qsc_code_frac_chars_dupe_5grams": 0.11186441, "qsc_code_frac_chars_dupe_6grams": 0.07288136, "qsc_code_frac_chars_dupe_7grams": 0.07288136, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00384369, "qsc_code_frac_chars_whitespace": 0.25560324, "qsc_code_size_file_byte": 2097.0, "qsc_code_num_lines": 106.0, "qsc_code_num_chars_line_max": 88.0, "qsc_code_num_chars_line_mean": 19.78301887, "qsc_code_frac_chars_alphabet": 0.752082, "qsc_code_frac_chars_comments": 0.12207916, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.08955224, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.04668838, "qsc_code_frac_chars_long_word_length": 0.01574376, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.0, "qsc_codejavascript_num_statement_line": 0.04477612, "qsc_codejavascript_score_lines_no_logic": 0.02985075, "qsc_codejavascript_frac_words_legal_var_name": 0.57142857, "qsc_codejavascript_frac_words_legal_func_name": null, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0} |
007gzs/meeting | miniprogram/pages/meeting/edit.js | "use strict";
// pages/meeting/edit.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
user_info: {},
meeting_id: 0,
room_id: 0,
date: "",
start_time: "",
end_time: "",
room: {},
name: "",
description: ""
},
bindKeyInput(e) {
this.data[e.currentTarget.dataset.obj] = e.detail.value
},
onGetUserInfo: function (e) {
app.onGetUserInfo(e).then(res => {
this.setData({ user_info: res })
})
},
refresh: function(){
if(this.data.meeting_id > 0){
app.api.api_meeting_info({meeting_id: this.data.meeting_id}).then(res => {
this.setData({
date: res.date,
start_time: res.start_time,
end_time: res.end_time,
room: res.room,
name: res.name,
description: res.description
})
})
}else{
app.api.api_meeting_room_info({ room_id: this.data.room_id }).then(res => {
this.setData({ room: res })
})
}
},
save: function () {
if(!this.data.name.trim()){
wx.showToast({
icon: 'none',
title: '请输入名称',
})
return
}
wx.showLoading({
mask: true,
title: '加载中...',
})
if (this.data.meeting_id <= 0) {
app.api.api_meeting_reserve({
room_id: this.data.room_id,
name: this.data.name,
description: this.data.description,
date: this.data.date,
start_time: this.data.start_time,
end_time: this.data.end_time
}).then(res => {
wx.hideLoading()
wx.redirectTo({
url: "detail?meeting_id="+res.id
})
}).catch(res => {
wx.hideLoading()
})
}else{
app.api.api_meeting_edit({
meeting_id: this.data.meeting_id,
name: this.data.name,
description: this.data.description
}).then(res => {
wx.hideLoading()
wx.navigateBack()
}).catch(res => {
wx.hideLoading()
})
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
app.userInfo().then(res => {
this.setData({ user_info: res })
})
let meeting_id = options.meeting_id
if(meeting_id){
this.setData({meeting_id: parseInt(meeting_id)})
return
}
let room_id = options.room_id
if (room_id){
room_id = parseInt(room_id)
}else{
room_id = 0
}
let start_time = options.start_time
let end_time = options.end_time
let date = options.date
if (room_id <= 0 || !start_time || !end_time || !date){
wx.showToast({
title: '参数错误',
icon: 'none'
})
wx.navigateBack()
return
}
this.setData({ room_id: room_id, start_time: start_time, end_time: end_time, date: date })
return
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
this.refresh()
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
}) | 3,207 | edit | js | en | javascript | code | {"qsc_code_num_words": 348, "qsc_code_num_chars": 3207.0, "qsc_code_mean_word_length": 4.70689655, "qsc_code_frac_words_unique": 0.22988506, "qsc_code_frac_chars_top_2grams": 0.07326007, "qsc_code_frac_chars_top_3grams": 0.04029304, "qsc_code_frac_chars_top_4grams": 0.04884005, "qsc_code_frac_chars_dupe_5grams": 0.26495726, "qsc_code_frac_chars_dupe_6grams": 0.19169719, "qsc_code_frac_chars_dupe_7grams": 0.13797314, "qsc_code_frac_chars_dupe_8grams": 0.1025641, "qsc_code_frac_chars_dupe_9grams": 0.1025641, "qsc_code_frac_chars_dupe_10grams": 0.04395604, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00271862, "qsc_code_frac_chars_whitespace": 0.3118179, "qsc_code_size_file_byte": 3207.0, "qsc_code_num_lines": 162.0, "qsc_code_num_chars_line_max": 95.0, "qsc_code_num_chars_line_mean": 19.7962963, "qsc_code_frac_chars_alphabet": 0.73946534, "qsc_code_frac_chars_comments": 0.08044902, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.28225806, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01728814, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.0, "qsc_codejavascript_num_statement_line": 0.02419355, "qsc_codejavascript_score_lines_no_logic": 0.03225806, "qsc_codejavascript_frac_words_legal_var_name": 0.33333333, "qsc_codejavascript_frac_words_legal_func_name": null, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0} |
007gzs/meeting | miniprogram/pages/room/history.wxml | <wxs module="timeUtils" src="../../utils/timeUtils.wxs"></wxs>
<view class="page history">
<view class="page__hd">
<view class='weui-cell'>
<view class='weui-cell__bd'>
<view class="page__title">{{info.name}}</view>
<view class="page__desc">{{info.description}}</view>
</view>
</view>
</view>
<view class="weui-flex">
<view class="weui-flex__item" style="text-align:right">
<picker value="{{history_start}}" mode="date" bindchange="change_history_start" start="{{history_limit_start}}" end="{{history_end}}">
<input class="weui-input" value="{{history_start}}" disabled="true"></input>
</picker>
</view>
<view class="weui-flex__item" style="display: flex;justify-content: center;align-items: center;">至</view>
<view class="weui-flex__item" style="text-align:left">
<picker value="{{history_end}}" mode="date" bindchange="change_history_end" start="{{history_start}}" end="{{history_limit_end}}">
<input class="weui-input" value="{{history_end}}" disabled="true"></input>
</picker>
</view>
</view>
<view class="page_bd page__bd_spacing">
<view class='weui-cells'>
<block wx:for="{{meetings}}" wx:key="id">
<view class="flag" wx:if="{{index == 0 || meetings[index-1].date != item.date}}">{{item.date}}</view>
<view class="weui-cell weui-cell_access" bindtap='detail' hover-class="weui-cell_active" id="{{item.id}}">
<view class="weui-cell__bd">{{item.name}}</view>
<view class="weui-cell__ft">{{timeUtils.formatTime(item.start_time)}} - {{timeUtils.formatTime(item.end_time)}}</view>
</view>
</block>
</view>
</view>
</view>
| 1,702 | history | wxml | en | unknown | unknown | {} | 0 | {} |
007gzs/meeting | miniprogram/pages/room/history.js | "use strict";
// pages/room/history.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
room_id: 0,
info: {},
meetings: [],
history_start: '',
history_end: '',
history_limit_start: '',
history_limit_end: '',
},
refresh: function () {
app.api.api_meeting_room_info({ room_id: this.data.room_id }).then(res => {
this.setData({ info: res })
app.userInfo().then(res => {
this.setData({ owner: res.id == this.data.info.create_user })
})
})
app.api.api_meeting_history_meetings({
room_id: this.data.room_id,
start_date: this.data.history_start,
end_date: this.data.history_end
}).then(res => {
this.setData({
meetings: res.meetings,
history_limit_start: res.history_start_date,
history_limit_end: res.history_end_date
})
})
},
change_history: function(){
this.setData({
history_view: !this.data.history_view
})
this.refresh()
},
change_history_start: function(e){
this.setData({
history_start: e.detail.value
})
this.refresh()
},
change_history_end: function(e){
this.setData({
history_end: e.detail.value
})
this.refresh()
},
date_select_change: function (e) {
this.refresh()
},
detail: function (e) {
wx.navigateTo({
url: '../meeting/detail?meeting_id=' + e.currentTarget.id
})
},
formatNumber: function(n) {
n = n.toString()
return n[1] ? n : '0' + n
},
dateId: function(date){
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
return [year, month, day].map(this.formatNumber).join('-')
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let now = app.nowDate()
this.setData({
room_id: parseInt(options.room_id),
show_home: getCurrentPages().length == 1,
history_end: this.dateId(now),
history_start: this.dateId(new Date(now.setDate(now.getDate() - 7)))
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
this.refresh()
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
}
}) | 2,456 | history | js | en | javascript | code | {"qsc_code_num_words": 266, "qsc_code_num_chars": 2456.0, "qsc_code_mean_word_length": 5.10902256, "qsc_code_frac_words_unique": 0.31578947, "qsc_code_frac_chars_top_2grams": 0.03090508, "qsc_code_frac_chars_top_3grams": 0.02207506, "qsc_code_frac_chars_top_4grams": 0.0397351, "qsc_code_frac_chars_dupe_5grams": 0.10301692, "qsc_code_frac_chars_dupe_6grams": 0.02943341, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00330579, "qsc_code_frac_chars_whitespace": 0.26099349, "qsc_code_size_file_byte": 2456.0, "qsc_code_num_lines": 129.0, "qsc_code_num_chars_line_max": 80.0, "qsc_code_num_chars_line_mean": 19.03875969, "qsc_code_frac_chars_alphabet": 0.74545455, "qsc_code_frac_chars_comments": 0.10504886, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.22222222, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01864484, "qsc_code_frac_chars_long_word_length": 0.01318781, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.0, "qsc_codejavascript_num_statement_line": 0.03333333, "qsc_codejavascript_score_lines_no_logic": 0.0, "qsc_codejavascript_frac_words_legal_var_name": 1.0, "qsc_codejavascript_frac_words_legal_func_name": null, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0} |
007gzs/meeting | miniprogram/utils/time.js | "use strict";
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
const Time = function (hour = 0, minute = 0, second = 0) {
this.hour = hour
this.minute = minute
this.second = second
this.string = function (num = 2) {
let ret = []
if (num > 0) {
ret.push(this.hour)
}
if (num > 1) {
ret.push(this.minute)
}
if (num > 2) {
ret.push(this.second)
}
return ret.map(formatNumber).join(":")
}
this.value = function () {
return this.hour * 3600 + this.minute * 60 + this.second
}
return this
}
const valueToTime = function (value) {
const hour = Math.floor(value / 3600);
value %= 3600
const minute = Math.floor(value / 60);
value %= 60
return new Time(hour, minute, value)
}
const parseTime = function (str) {
const t = str.split(":")
return new Time(
t.length > 0 ? parseInt(t[0]) : 0,
t.length > 1 ? parseInt(t[1]) : 0,
t.length > 2 ? parseInt(t[2]) : 0
)
}
module.exports = {
formatNumber: formatNumber,
Time: Time,
valueToTime: valueToTime,
parseTime: parseTime
} | 1,094 | time | js | en | javascript | code | {"qsc_code_num_words": 147, "qsc_code_num_chars": 1094.0, "qsc_code_mean_word_length": 4.34693878, "qsc_code_frac_words_unique": 0.26530612, "qsc_code_frac_chars_top_2grams": 0.03755869, "qsc_code_frac_chars_top_3grams": 0.05164319, "qsc_code_frac_chars_top_4grams": 0.0, "qsc_code_frac_chars_dupe_5grams": 0.0, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.04449938, "qsc_code_frac_chars_whitespace": 0.26051188, "qsc_code_size_file_byte": 1094.0, "qsc_code_num_lines": 49.0, "qsc_code_num_chars_line_max": 61.0, "qsc_code_num_chars_line_mean": 22.32653061, "qsc_code_frac_chars_alphabet": 0.74536465, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01187215, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.0625, "qsc_codejavascript_num_statement_line": 0.125, "qsc_codejavascript_score_lines_no_logic": 0.0625, "qsc_codejavascript_frac_words_legal_var_name": 1.0, "qsc_codejavascript_frac_words_legal_func_name": 1.0, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0} |
007revad/ContainerManager_for_all_armv8 | README.md | # Container Manager for all armv8
<a href="https://github.com/007revad/ContainerManager_for_all_armv8/releases"><img src="https://img.shields.io/github/release/007revad/ContainerManager_for_all_armv8.svg"></a>

[](https://www.paypal.com/paypalme/007revad)
[](https://github.com/sponsors/007revad)
[](https://user-badge.committers.top/australia/007revad)
### Description
Script to install Container Manager on a RS819, DS119j, DS418, DS418j, DS218, DS218play or DS118
There is no technical reason why these NAS models with a Realtek RTD1296, or Marvell A3720, CPU are excluded from installing Container Manager when they have the same CPU as the DS220j, or DS120j.
So I made a script to install the ContainerManager-armv8 package on any model with a Realtek RTD1296 (or Marvell A3720?) CPU running DSM 7.2 or later.
v2 and later can now update Container Mananger if there's a newer version available.
### Confirmed working on
| Model | CPU | DSM version | Working | Notes |
| ---------- |-----|--------------------------|---------|-------|
| RS819 | Realtek RTD1296 | DSM 7.2.2-72803 | yes | |
| DS119j | Marvell A3720 | DSM 7.2.2-72806 Update 2 | yes | |
| DS418 | Realtek RTD1296 | DSM 7.3-81180 | yes | ContainerManager 24.0.2-1606 |
| DS418 | Realtek RTD1296 | DSM 7.2.2-72806 Update 3 | yes | |
| DS418 | Realtek RTD1296 | DSM 7.2.2-72806 Update 2 | yes | |
| DS418 | Realtek RTD1296 | DSM 7.2.1-69057 Update 5 | yes | |
| DS418 | Realtek RTD1296 | DSM 7.2.1-69057 Update 4 | yes | |
| DS418j | Realtek RTD129**3** | DSM 7.2.1-69057 Update 5 | yes | |
| DS218 | Realtek RTD1296 | DSM 7.3-81180 | yes | ContainerManager 24.0.2-1606 |
| DS218 | Realtek RTD1296 | DSM 7.2.1-69057 Update 5 | yes | |
| DS218 | Realtek RTD1296 | DSM 7.2.1-69057 Update 3 | yes | |
| DS218play | Realtek RTD1296 | DSM 7.3-81180 | yes | ContainerManager 24.0.2-1606 |
| DS218play | Realtek RTD1296 | DSM 7.2.2-72806 Update 3 | yes | |
| DS218play | Realtek RTD1296 | DSM 7.2.1-69057 Update 6 | yes | |
| DS218play | Realtek RTD1296 | DSM 7.2.1-69057 Update 5 | yes | |
| DS118 | Realtek RTD1296 | DSM 7.2.1-69057 Update 1 | yes | |
### Will NOT work on models with a 32 bit CPU
<details>
<summary>Click here to see list of models with a 32 bit armv71 CPU</summary>
<br>
| Model | CPU | Package Arch | | uname -m | Working |
| ---------- |-----|--------------|--|----------|---------|
| DS419slim | Marvell Armada 385 88F6820 | armada38x | 32 bit | armv71 | no |
| DS218j | Marvell Armada 385 88F6820 | armada38x | 32 bit | armv71 | no |
| RS217 | Marvell Armada 385 88F6820 | armada38x | 32 bit | armv71 | no |
| RS816 | Marvell Armada 385 88F6820 | armada38x | 32 bit | armv71 | no |
| DS416slim | Marvell Armada 385 88F6820 | armada38x | 32 bit | armv71 | no |
| DS416j | Marvell Armada 385 88F6820 | armada38x | 32 bit | armv71 | no |
| DS216j | Marvell Armada 385 88F6820 | armada38x | 32 bit | armv71 | no |
| DS216 | Marvell Armada 385 88F6820 | armada38x | 32 bit | armv71 | no |
| DS116 | Marvell Armada 385 88F6820 | armada38x | 32 bit | armv71 | no |
</details>
### Download the script
1. Download the latest version _Source code (zip)_ from https://github.com/007revad/ContainerManager_for_all_armv8/releases
2. Save the download zip file to a folder on the Synology.
3. Unzip the zip file.
### To run the script via SSH
[How to enable SSH and login to DSM via SSH](https://kb.synology.com/en-global/DSM/tutorial/How_to_login_to_DSM_with_root_permission_via_SSH_Telnet)
```YAML
sudo -s /volume1/scripts/install_container_manager.sh
```
**Note:** Replace /volume1/scripts/ with the path to where the script is located.
### When you run the script
The script will try to install Container Manager itself.
If you get a _"Failed to query package list from server"_ error the script will pause and wait for you to do a Manual Install, and then the script will continue after you type **yes**.
### Steps to do a Manual Install if the scripts asks you to: <br>
Do **NOT** exit the script or close the window.
1. Download the latest **ContainerManager-armv8** spk file from https://archive.synology.com/download/Package/ContainerManager
2. Open Package Center. If it is already open close it and re-open it.
3. Click on the Manual Install button.
4. Click on the Browse button.
5. Browse to where you saved the ContainerManager spk file.
6. Select the spk file and click Open.
7. Click Next and install Container Manager.
8. Close Package Center.
9. Return to the script window and type **yes** so the script can restore the correct model number.
<p align="center">Manual Install of Container Manager</p>
<p align="center"><img src="/images/package_manual_install.png"></p>
### What to do after running the script
1. Open Package Center (if Package Center is already open close it and re-open it).
2. Click on Settings.
3. Click on Auto Update.
4. Select "Only packages below".
5. Make sure "All Packages" is **NOT** ticked.
6. Make sure "Important Versions" is **NOT** ticked.
7. Click OK.
<p align="center">Prevent Container Manager from auto updating</p>
<p align="center"><img src="/images/disable_auto_updates.png"></p>
### Screenshots
<p align="center">Installing Container Manager</p>
<p align="center"><img src="/images/script_install_auto.png"></p>
<p align="center">Installing Container Manager via Manual Install</p>
<p align="center"><img src="/images/script_install_manual.png"></p>
<p align="center">Upgrading Container Manager to latest version</p>
<p align="center"><img src="/images/script_upgrade.png"></p>
| 6,117 | README | md | en | markdown | text | {"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.14837819, "qsc_doc_num_sentences": 119.0, "qsc_doc_num_words": 937, "qsc_doc_num_chars": 6117.0, "qsc_doc_num_lines": 122.0, "qsc_doc_mean_word_length": 4.51760939, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.2796158, "qsc_doc_entropy_unigram": 5.02938366, "qsc_doc_frac_words_all_caps": 0.0621118, "qsc_doc_frac_lines_dupe_lines": 0.0, "qsc_doc_frac_chars_dupe_lines": 0.0, "qsc_doc_frac_chars_top_2grams": 0.01606426, "qsc_doc_frac_chars_top_3grams": 0.01653674, "qsc_doc_frac_chars_top_4grams": 0.05953225, "qsc_doc_frac_chars_dupe_5grams": 0.41223718, "qsc_doc_frac_chars_dupe_6grams": 0.38317978, "qsc_doc_frac_chars_dupe_7grams": 0.3621545, "qsc_doc_frac_chars_dupe_8grams": 0.33545948, "qsc_doc_frac_chars_dupe_9grams": 0.30073234, "qsc_doc_frac_chars_dupe_10grams": 0.1221356, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 24.38589212, "qsc_doc_frac_chars_hyperlink_html_tag": 0.21170508, "qsc_doc_frac_chars_alphabet": 0.7226378, "qsc_doc_frac_chars_digital": 0.11062992, "qsc_doc_frac_chars_whitespace": 0.16952755, "qsc_doc_frac_chars_hex_words": 0.0} | 1 | {"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0} |
007/hashcash-js | hashcash.js |
// hash function abstraction:
// always call hc_HashFunc, and the behind-the-scenes
// hash function used can be changed easily
// currently crc32 for speed/convenience,
// needs to be defined in its native script
// include the hash script before this one
// make sure your hash function returns a hex string
// case does not matter, upper or lower for A..F
var g_ProcessFlag = 0;
var g_PageContract = 0;
var g_GenSize = 0;
var g_Col_Hash = '';
var g_PSBits = '';
function hc_SetFormData(x, y)
{
var z = document.getElementById(x);
if(z) z.value = y;
}
function hc_GetFormData(x)
{
var z = document.getElementById(x);
if(z)
return z.value;
else
return '';
}
// convert hex numbers to binary strings
function hc_HexInBin(x)
{
var ret = '';
switch(x.toUpperCase())
{ case '0': ret = '0000'; break; case '1': ret = '0001'; break;
case '2': ret = '0010'; break; case '3': ret = '0011'; break;
case '4': ret = '0100'; break; case '5': ret = '0101'; break;
case '6': ret = '0110'; break; case '7': ret = '0111'; break;
case '8': ret = '1000'; break; case '9': ret = '1001'; break;
case 'A': ret = '1010'; break; case 'B': ret = '1011'; break;
case 'C': ret = '1100'; break; case 'D': ret = '1101'; break;
case 'E': ret = '1110'; break; case 'F': ret = '1111'; break;
default : ret = '0000'; }
return ret;
}
function hc_ExtractBits(hex_string, num_bits)
{
var bit_string = "";
var num_chars = Math.ceil(num_bits / 4);
for(var i = 0; i < num_chars; i++)
bit_string = bit_string + "" + hc_HexInBin(hex_string.charAt(i));
bit_string = bit_string.substr(0, num_bits);
return bit_string;
}
function hc_CheckContract(pg_contract, pg_sbits, col_string)
{
// check that pContract bits of pStamp and cHash match
var col_hash = hc_HashFunc(col_string);
var check_bits = hc_ExtractBits(col_hash, pg_contract);
return (check_bits == pg_sbits);
}
function hc_GenChars(x)
{
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var randomstring = '';
for (var i = 0; i < x; i++)
randomstring += chars.substr(Math.floor(Math.random() * chars.length), 1);
return randomstring;
}
function hc_SpendHash()
{
if(g_ProcessFlag == 0)
{
// testdat = random_chars(8)
var Collision = hc_GenChars(g_GenSize);
var looper = 1;
while(!hc_CheckContract(g_PageContract, g_PSBits, Collision))
{
Collision = hc_GenChars(g_GenSize);
looper++;
}
hc_SetFormData('hc_collision', Collision);
}
return true;
}
function hc_SetupTimeout()
{
alert("we got the setup timed out!");
// retrieve stamp
// retrieve contract
var PageStamp = hc_GetFormData('hc_stamp');
g_PageContract = hc_GetFormData('hc_contract');
g_GenSize = hc_GetFormData('hc_collision');
g_PSBits = hc_ExtractBits(PageStamp, g_PageContract);
if(!(g_GenSize > 1)) g_GenSize = 8;
setTimeout("hc_TimeoutHash()",10);
}
function hc_TimeoutHash()
{
// testdat = random_chars(8)
var Collision = hc_GenChars(g_GenSize);
if(!hc_CheckContract(g_PageContract, g_PSBits, Collision))
setTimeout("hc_TimeoutHash()",10);
else
{
alert("found a value!");
hc_SetFormData('hc_collision', Collision);
g_ProcessFlag = 1;
}
}
function addLoadEvent(func)
{
var oldonload = window.onload;
if(typeof window.onload != 'function')
{
window.onload = func;
}
else
{
window.onload = function()
{
oldonload();
func();
}
}
}
function addLoadEventParm(func, parm)
{
var oldonload = window.onload;
if(typeof window.onload != 'function')
{
window.onload = function() { func(parm); };
}
else
{
window.onload = function()
{
oldonload();
func(parm);
}
}
}
addLoadEvent(hc_SetupTimeout);
// addLoadEventParm(hc_SetupTimeout, parm); | 3,700 | hashcash | js | en | javascript | code | {"qsc_code_num_words": 504, "qsc_code_num_chars": 3700.0, "qsc_code_mean_word_length": 4.82142857, "qsc_code_frac_words_unique": 0.31746032, "qsc_code_frac_chars_top_2grams": 0.05555556, "qsc_code_frac_chars_top_3grams": 0.04115226, "qsc_code_frac_chars_top_4grams": 0.02469136, "qsc_code_frac_chars_dupe_5grams": 0.24567901, "qsc_code_frac_chars_dupe_6grams": 0.18436214, "qsc_code_frac_chars_dupe_7grams": 0.15390947, "qsc_code_frac_chars_dupe_8grams": 0.09300412, "qsc_code_frac_chars_dupe_9grams": 0.09300412, "qsc_code_frac_chars_dupe_10grams": 0.09300412, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03570259, "qsc_code_frac_chars_whitespace": 0.17486486, "qsc_code_size_file_byte": 3700.0, "qsc_code_num_lines": 169.0, "qsc_code_num_chars_line_max": 79.0, "qsc_code_num_chars_line_mean": 21.89349112, "qsc_code_frac_chars_alphabet": 0.76023583, "qsc_code_frac_chars_comments": 0.15702703, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.15873016, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.09297852, "qsc_code_frac_chars_long_word_length": 0.01987817, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.08730159, "qsc_codejavascript_num_statement_line": 0.13492063, "qsc_codejavascript_score_lines_no_logic": 0.22222222, "qsc_codejavascript_frac_words_legal_var_name": 0.45454545, "qsc_codejavascript_frac_words_legal_func_name": 0.18181818, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0} |
007/hashcash-js | README.md | # Hashcash for PHP/JavaScript forms
Hashcash works by requiring the client to perform a complex calculation before the server will accept its input. Although the calculation may take the client several seconds to process, the server can check the results almost instantly.
The process is easiest to explain using square roots. Given the number 332,929, it takes about 36 steps for a computer to find its square root of 577. However, once the root is found, it only takes one step to test if the result is correct — check to see that 577 * 577 = 332,929. Hashcash doesn’t use square roots for its calculations, but it does work by the same principle.
In a Hashcash transaction, the server generates a string called a stamp that contains encoded information about the client. Specifically, it includes the current time at the server, and the IP address from which the client is accessing the server. The data also includes a salt value (described below), and is encoded using a hash function (in this case, CRC32).
Salt values, commonly used in encryption functions, are used to increase the amount of processing that an attacker would have to expend to "crack" some data. They are simply random data that is added to the information being encrypted to make reversing the process harder.
Without salts, an attacker will know their IP address and can calculate a large number of stamps before launching an attack.
With the addition of the salt value, the attacker would not have the information necessary to calculate correct stamp values, even if they could correctly identify the server time and their own IP address. Thusly, every time the server generates a new stamp, the attacker is forced to start over.
If the same salt value is used in two different implementations, the hash values generated will match between the two. An attacker who saw that two different sites that use this protection generated similar stamps, they would only have to expend effort to bypass one of the sites in order to gain access to both. If, instead, the two sites used different salts, the attacker would have to expend twice the effort to access both sites. With this property in mind, the salt values should be changed to a different random string for each client this script is installed upon.
## Step-by-step
There are two parties to a hashcash transaction, client and server.
* Step 1: The client requests a web page from the server. It can be any page that submits data with a form, or it can be a page with several forms included within.
* Step 2: The server calculates a stamp based on the client’s IP address, the current time on the server, and a user-defined salt value. The stamp is then scrambled using the function hc_HashFunc for security, and is embedded invisibly in the form.
* Step 3a: The client fills out the form and clicks the submit button.
* Step 3b: Before the client’s computer actually submits the data to the server, it gets the invisible stamp from the page, calculates a collision string and adds the string into the form.
* Step 4a: Before the server accepts the data from the client — blog comments, auction postings, etc. — it checks to see that there is a stamp on the page.
* Step 4b: If there is a stamp, the server checks to see that it is valid — it has been posted before the stamp expires, and that the calculated string and the stamp match up.
* Step 4c: If the stamp check fails or if there is no stamp, the server returns an error, and can either ignore the submitted data, request that the user try again, or present some alternate way for the client to authenticate itself — a captcha or log in mechanism.
* Step 4d: If the stamp check succeeds, the server accepts the data and processes it as appropriate.
### Hc config file — 4 params
TODO: what is this?
## JAVASCRIPT DOCUMENTATION
hc_HashFunc should be defined in its own script, wherever the function itself is created. It should take one parameter (a string) and return a hex string as its output. In the current implementation I use CRC32, but any hash function that has both a JavaScript and a server-side implementation that return the same results for the same input data will work. MD5 was tested, but was too slow for the client side. Depending on your exact circumstances you may want to use some other function, but the included version should work for most implementations.
// set form element x to value y
function hc_SetFormData(x, y)
// return value of form element x
function hc_GetFormData(x)
// convert hex numbers to binary strings
function hc_HexInBin(x)
// returns a string of num_bits from hex_string
function hc_ExtractBits(hex_string, num_bits)
// checks col_string vs. pg_sbits for pg_contract bits
function hc_CheckContract(pg_contract, pg_sbits, col_string)
// generate a random string of length x using [0-9A-Za-z]
function hc_GenChars(x)
// extracts data from page to calculate hash collision
function hc_SpendHash()
## PHP DOCUMENTATION
// define generic hash function (currently crc32)
function hc_HashFunc($x) { return sprintf("%08x", crc32($x)); }
// convert hex numbers to binary strings
function hc_HexInBin($x)
// get the first $num_bits bits of $hex_string
function hc_ExtractBits($hex_string, $num_bits)
// generate a stamp based on IP, time and salt
// embeds hc_stamp, hc_contract and hc_collision in the form
function hc_CreateStamp()
// hc_CheckExpiration - true = valid, false = expired
function hc_CheckExpiration($a_stamp)
// check for collision of $stamp_contract bits for $stamp and $collision
function hc_CheckContract($stamp, $collision, $stamp_contract)
// checks validity, expiration, and contract obligations for a stamp
function hc_CheckStamp()
## Still ToDo
* Make hashcash javascript functions run in the background
* As-is, they run only onsubmit, they should take advantage of the time that a user needs to fill out a form. Instead of letting the user fill out a form for 3 minutes and then wait another 10 seconds to calculate the stamp, the JavaScript should start when the page loads and be finished before the user is done with their input.
* Make hashcash javascript function run on page load
* The interface should be as simple as possible, requiring at most one line per form. If it can be included automatically using something like addLoadEvent, that would be ideal.
* Complete documentation
* There should be more information on how to implement this script, including a step-by-step tutorial. This should be done last, so that the onload and background functionality described above can be included.
| 6,935 | README | md | en | markdown | text | {"qsc_doc_frac_chars_curly_bracket": 0.00028839, "qsc_doc_frac_words_redpajama_stop": 0.39552814, "qsc_doc_num_sentences": 43.0, "qsc_doc_num_words": 1115, "qsc_doc_num_chars": 6935.0, "qsc_doc_num_lines": 120.0, "qsc_doc_mean_word_length": 4.63408072, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.33721973, "qsc_doc_entropy_unigram": 5.21683951, "qsc_doc_frac_words_all_caps": 0.01233616, "qsc_doc_frac_lines_dupe_lines": 0.03389831, "qsc_doc_frac_chars_dupe_lines": 0.01226994, "qsc_doc_frac_chars_top_2grams": 0.02612735, "qsc_doc_frac_chars_top_3grams": 0.00522547, "qsc_doc_frac_chars_top_4grams": 0.00735436, "qsc_doc_frac_chars_dupe_5grams": 0.05651248, "qsc_doc_frac_chars_dupe_6grams": 0.03793304, "qsc_doc_frac_chars_dupe_7grams": 0.03793304, "qsc_doc_frac_chars_dupe_8grams": 0.03793304, "qsc_doc_frac_chars_dupe_9grams": 0.03793304, "qsc_doc_frac_chars_dupe_10grams": 0.02012773, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 41.29268293, "qsc_doc_frac_chars_hyperlink_html_tag": 0.0, "qsc_doc_frac_chars_alphabet": 0.93644689, "qsc_doc_frac_chars_digital": 0.00879121, "qsc_doc_frac_chars_whitespace": 0.21268926, "qsc_doc_frac_chars_hex_words": 0.0} | 1 | {"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0} |
007gzs/meeting | miniprogram/pages/meeting/reserve.js | "use strict";
// pages/meeting/reserve.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
room_ids: "",
loading: true,
select:{
selected: false,
click: false,
start: "",
end: "",
room: {}
}
},
date_select_change: function (e) {
this.setData({
select: {selected: false, click: false, start: "", end: "", room: {}}, td_data: {}
})
this.refresh()
},
title_click: function(e){
wx.showActionSheet({
itemList: ['查看详情', '从列表移出'],
success: r => {
if (r.tapIndex == 0){
wx.navigateTo({
url: '../room/detail?room_id=' + e.detail.title_id + '&date=' + this.selectComponent("#date_select").data.select_date,
})
} else if (r.tapIndex == 1){
let select_rooms = this.data.room_ids.split(",")
const index = select_rooms.indexOf(e.detail.title_id)
if (index >= 0) {
select_rooms.splice(index, 1)
const room_ids_str = select_rooms.join(",")
wx.setStorageSync('RESERVE_ROOM_IDS', room_ids_str)
this.setData({ room_ids: room_ids_str })
this.refresh()
}
}
}
})
},
title_label_click: function () {
const select_rooms = this.data.room_ids.split(",")
if(select_rooms.length >= 5){
wx.showToast({
title: '超过上限',
icon: 'none'
})
return
}
app.api.api_meeting_follow_rooms().then(res => {
let room_ids = []
let room_names = []
for(let i in res){
let room = res[i]
if (select_rooms.indexOf(room.id.toString()) < 0){
room_ids.push(room.id.toString())
room_names.push(room.name)
}
}
if(room_ids.length == 0){
wx.showToast({
title: '已没有关注的会议室',
icon: 'none'
})
return
}
wx.showActionSheet({
itemList: room_names,
success: r => {
room_ids.push(room_ids[r.tapIndex])
let room_ids_str = select_rooms
if (room_ids_str != ''){
room_ids_str += ","
}
room_ids_str += room_ids[r.tapIndex]
wx.setStorageSync('RESERVE_ROOM_IDS', room_ids_str)
this.setData({ room_ids: room_ids_str })
this.refresh()
}
})
})
},
data_click: function (e) {
const meeting_id = e.detail.data_id
if(meeting_id != null){
wx.navigateTo({
url: '../meeting/detail?meeting_id=' + meeting_id,
})
return
}
const room_id = e.detail.title_id
const time = e.detail.label_id
if (!this.data.td_data || !this.data.td_data[room_id]){
return
}
const td_data = this.data.td_data[room_id][time]
if (td_data.expire || td_data.meeting_status != 0){
return
}
if (td_data.selected_status != 0){
// if (this.data.select.click) {
this.data.select.click = false
this.data.select.selected = false
this.setData({ select: this.data.select })
this.check_td_data()
// }
return
}
if (!this.data.select.selected || this.data.select.room.id != room_id) {
this.data.select.click = false
this.data.select.selected = false
}
this.data.select.room = this.data.rooms.find(r => {return r.id == room_id})
if (!this.data.select.click) {
this.data.select.selected = true
this.data.select.click = true
this.data.select.start = time
this.data.select.end = time
} else {
this.data.select.click = false
if (this.data.select.start == time){
this.data.select.selected = false
} else if (app.time.parseTime(this.data.select.start).value() > app.time.parseTime(time).value()){
this.data.select.start = time
}else{
this.data.select.end = time
}
}
this.data.select.end_real = app.time.valueToTime(app.time.parseTime(this.data.select.end).value() + 30 * 60).string(2)
this.setData({ select: this.data.select })
this.check_td_data()
},
check_td_data: function(){
this.data.td_data = app.meetings.getTdData(
this.data.rooms,
this.data.meetings,
this.data.time_range,
this.data.select,
this.selectComponent("#date_select").data.select_date
)
this.selectComponent("#time_table").set_data({
titles: this.data.rooms, labels: this.data.time_range, td_data: this.data.td_data
})
this.setData({ select: this.data.select, loading: false })
},
reserve: function(){
wx.navigateTo({
url: 'edit?room_id=' + this.data.select.room.id + "&start_time=" + this.data.select.start + "&end_time=" + this.data.select.end_real + "&date=" + this.selectComponent("#date_select").data.select_date
})
},
refresh: function () {
if (!this.data.room_ids) {
this.setData({ meetings: [], rooms: [], td_data: {}, loading: false })
return
}
app.api.api_meeting_room_meetings({
room_ids: this.data.room_ids,
date: this.selectComponent("#date_select").data.select_date
}).then(res => {
const start_time = app.time.parseTime(res.start_time).value()
const end_time = app.time.parseTime(res.end_time).value()
let time_range = []
for (let time = start_time; time <= end_time; time += 1800) {
const t = app.time.valueToTime(time)
const id = t.string(2)
time_range.push({ id: id, text: t.minute == 0 ? id : "", data: t })
}
this.data.meetings = res.meetings
this.data.rooms = res.rooms
this.data.time_range = time_range
this.selectComponent("#date_select").setDateRange(res.start_date, res.end_date)
this.check_td_data()
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let room_ids = options.room_ids
if(!room_ids){
try {
room_ids = wx.getStorageSync('RESERVE_ROOM_IDS')
} catch (e) {
room_ids = ""
}
}
if(!room_ids){
room_ids = ""
}
if (options.date) {
this.selectComponent("#date_select").setData({select_date: options.date})
}
this.setData({ room_ids: room_ids })
this.refresh()
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
this.refresh()
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
}) | 6,619 | reserve | js | en | javascript | code | {"qsc_code_num_words": 791, "qsc_code_num_chars": 6619.0, "qsc_code_mean_word_length": 4.59418458, "qsc_code_frac_words_unique": 0.15676359, "qsc_code_frac_chars_top_2grams": 0.10126582, "qsc_code_frac_chars_top_3grams": 0.10787012, "qsc_code_frac_chars_top_4grams": 0.04788112, "qsc_code_frac_chars_dupe_5grams": 0.41386901, "qsc_code_frac_chars_dupe_6grams": 0.31232801, "qsc_code_frac_chars_dupe_7grams": 0.26389653, "qsc_code_frac_chars_dupe_8grams": 0.21959274, "qsc_code_frac_chars_dupe_9grams": 0.09796368, "qsc_code_frac_chars_dupe_10grams": 0.09796368, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00416927, "qsc_code_frac_chars_whitespace": 0.27526817, "qsc_code_size_file_byte": 6619.0, "qsc_code_num_lines": 247.0, "qsc_code_num_chars_line_max": 206.0, "qsc_code_num_chars_line_mean": 26.79757085, "qsc_code_frac_chars_alphabet": 0.75338753, "qsc_code_frac_chars_comments": 0.04487083, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.29126214, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.04333386, "qsc_code_frac_chars_long_word_length": 0.00822394, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.0, "qsc_codejavascript_num_statement_line": 0.01456311, "qsc_codejavascript_score_lines_no_logic": 0.04854369, "qsc_codejavascript_frac_words_legal_var_name": 0.38095238, "qsc_codejavascript_frac_words_legal_func_name": null, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0} |
007idc/GoEdgeKeyGen | third/encode/test.go | package encode
import (
"fmt"
"log"
)
func Decode(data []byte) []byte {
method, err := NewMethodInstance("aes-256-cfb", "41100c93a65cfb71d5b0672c0d60d7ec", "70ba69d67bf7e61e17ac565c6093a325")
if err != nil {
fmt.Println("[MagicKeyEncode]" + err.Error())
return data
}
src, err := method.Decrypt(data)
if err != nil {
fmt.Println("[MagicKeyEncode]" + err.Error())
return data
}
return src
}
func Encode(data []byte) []byte {
method, err := NewMethodInstance("aes-256-cfb", "41100c93a65cfb71d5b0672c0d60d7ec", "70ba69d67bf7e61e17ac565c6093a325")
if err != nil {
fmt.Println("[MagicKeyEncode]" + err.Error())
return data
}
dst, err := method.Encrypt(data)
if err != nil {
fmt.Println("[MagicKeyEncode]" + err.Error())
return data
}
return dst
}
func Test() {
method, err := NewMethodInstance("aes-256-cfb", "abc", "123")
if err != nil {
log.Fatal(err)
}
src := []byte("Hello, World")
dst, err := method.Encrypt(src)
if err != nil {
log.Fatal(err)
}
dst = dst[:len(src)]
fmt.Println("dst:", string(dst))
src, err = method.Decrypt(dst)
if err != nil {
log.Fatal(err)
}
fmt.Println("src:", string(src))
}
| 1,156 | test | go | en | go | code | {"qsc_code_num_words": 141, "qsc_code_num_chars": 1156.0, "qsc_code_mean_word_length": 5.34751773, "qsc_code_frac_words_unique": 0.24822695, "qsc_code_frac_chars_top_2grams": 0.0464191, "qsc_code_frac_chars_top_3grams": 0.07427056, "qsc_code_frac_chars_top_4grams": 0.05835544, "qsc_code_frac_chars_dupe_5grams": 0.70822281, "qsc_code_frac_chars_dupe_6grams": 0.70822281, "qsc_code_frac_chars_dupe_7grams": 0.5862069, "qsc_code_frac_chars_dupe_8grams": 0.5862069, "qsc_code_frac_chars_dupe_9grams": 0.5862069, "qsc_code_frac_chars_dupe_10grams": 0.5862069, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0977131, "qsc_code_frac_chars_whitespace": 0.16782007, "qsc_code_size_file_byte": 1156.0, "qsc_code_num_lines": 55.0, "qsc_code_num_chars_line_max": 121.0, "qsc_code_num_chars_line_mean": 21.01818182, "qsc_code_frac_chars_alphabet": 0.68607069, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.40816327, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.22231834, "qsc_code_frac_chars_long_word_length": 0.11072664, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codego_cate_testfile": 0.0, "qsc_codego_frac_lines_func_ratio": 0.06122449, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.20408163, "qsc_codego_frac_lines_print": 0.12244898} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 1, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_codego_cate_testfile": 0, "qsc_codego_frac_lines_func_ratio": 0, "qsc_codego_cate_var_zero": 0, "qsc_codego_score_lines_no_logic": 0, "qsc_codego_frac_lines_print": 0} |
007idc/GoEdgeKeyGen | third/encode/aes-256.go | package encode
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
type AES256CFBMethod struct {
block cipher.Block
iv []byte
}
func (a *AES256CFBMethod) Init(key, iv []byte) error {
// 判断key是否为32长度
l := len(key)
if l > 32 {
key = key[:32]
} else if l < 32 {
key = append(key, bytes.Repeat([]byte{' '}, 32-l)...)
}
block, err := aes.NewCipher(key)
if err != nil {
return err
}
a.block = block
// 判断iv长度
l2 := len(iv)
if l2 > aes.BlockSize {
iv = iv[:aes.BlockSize]
} else if l2 < aes.BlockSize {
iv = append(iv, bytes.Repeat([]byte{' '}, aes.BlockSize-l2)...)
}
a.iv = iv
return nil
}
func (a *AES256CFBMethod) Encrypt(src []byte) (dst []byte, err error) {
if len(src) == 0 {
return
}
defer func() {
err = RecoverMethodPanic(recover())
}()
dst = make([]byte, len(src))
encrypter := cipher.NewCFBEncrypter(a.block, a.iv)
encrypter.XORKeyStream(dst, src)
return
}
func (a *AES256CFBMethod) Decrypt(dst []byte) (src []byte, err error) {
if len(dst) == 0 {
return
}
defer func() {
err = RecoverMethodPanic(recover())
}()
src = make([]byte, len(dst))
decrypter := cipher.NewCFBDecrypter(a.block, a.iv)
decrypter.XORKeyStream(src, dst)
return
}
| 1,208 | aes-256 | go | en | go | code | {"qsc_code_num_words": 164, "qsc_code_num_chars": 1208.0, "qsc_code_mean_word_length": 4.57317073, "qsc_code_frac_words_unique": 0.28658537, "qsc_code_frac_chars_top_2grams": 0.064, "qsc_code_frac_chars_top_3grams": 0.08, "qsc_code_frac_chars_top_4grams": 0.02133333, "qsc_code_frac_chars_dupe_5grams": 0.21066667, "qsc_code_frac_chars_dupe_6grams": 0.11733333, "qsc_code_frac_chars_dupe_7grams": 0.11733333, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0290758, "qsc_code_frac_chars_whitespace": 0.20281457, "qsc_code_size_file_byte": 1208.0, "qsc_code_num_lines": 72.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 16.77777778, "qsc_code_frac_chars_alphabet": 0.74974039, "qsc_code_frac_chars_comments": 0.01986755, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.18181818, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.02533784, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codego_cate_testfile": 0.0, "qsc_codego_frac_lines_func_ratio": 0.05454545, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.2, "qsc_codego_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_codego_cate_testfile": 0, "qsc_codego_frac_lines_func_ratio": 0, "qsc_codego_cate_var_zero": 0, "qsc_codego_score_lines_no_logic": 0, "qsc_codego_frac_lines_print": 0} |
007/hashcash-js | hashcash.php | <?php
include "hc_config.php";
//////////////////////
// helper functions //
//////////////////////
function DEBUG_OUT($x) { echo "<pre>$x</pre>\n"; }
// define generic hash function (currently md5)
function hc_HashFunc($x) { return sprintf("%08x", crc32($x)); }
// convert hex numbers to decimal
function hc_HexInDec($x)
{
if(($x >= "0") && ($x <= "9"))
$ret = $x * 1;
else
switch($x)
{
case "A": $ret = 10;
case "B": $ret = 11;
case "C": $ret = 12;
case "D": $ret = 13;
case "E": $ret = 14;
case "F": $ret = 15;
default: $ret = 0;
}
}
// convert hex numbers to binary strings
function hc_HexInBin($x)
{
switch($x)
{
case '0': $ret = '0000'; break;
case '1': $ret = '0001'; break;
case '2': $ret = '0010'; break;
case '3': $ret = '0011'; break;
case '4': $ret = '0100'; break;
case '5': $ret = '0101'; break;
case '6': $ret = '0110'; break;
case '7': $ret = '0111'; break;
case '8': $ret = '1000'; break;
case '9': $ret = '1001'; break;
case 'A': $ret = '1010'; break;
case 'B': $ret = '1011'; break;
case 'C': $ret = '1100'; break;
case 'D': $ret = '1101'; break;
case 'E': $ret = '1110'; break;
case 'F': $ret = '1111'; break;
default: $ret = '0000';
}
// DEBUG_OUT("ret = " . $ret);
return $ret;
}
function hc_ExtractBits($hex_string, $num_bits)
{
$bit_string = "";
$num_chars = ceil($num_bits / 4);
for($i = 0; $i < $num_chars; $i++)
$bit_string .= hc_HexInBin(substr($hex_string, $i, 1));
// DEBUG_OUT("requested $num_bits from $hex_string, returned $bit_string as " . substr($bit_string, 0, $num_bits));
return substr($bit_string, 0, $num_bits);
}
/////////////////////////////
// stamp creation function //
/////////////////////////////
// generate a stamp
function hc_CreateStamp()
{
global $hc_salt, $hc_contract, $hc_maxcoll;
$ip = $_SERVER['REMOTE_ADDR'];
$now = intval(time() / 60);
// create stamp
// stamp = hash of time (in minutes) . user ip . salt value
$stamp = hc_HashFunc($now . $ip . $hc_salt);
//embed stamp in page
echo "<input type=\"hidden\" name=\"hc_stamp\" id=\"hc_stamp\" value=\"" . $stamp . "\" />\n";
echo "<input type=\"hidden\" name=\"hc_contract\" id=\"hc_contract\" value=\"" . $hc_contract . "\" />\n";
echo "<input type=\"hidden\" name=\"hc_collision\" id=\"hc_collision\" value=\"" . $hc_maxcoll . "\" />\n";
}
//////////////////////////////
// stamp checking functions //
//////////////////////////////
// hc_CheckExpiration - true = valid, false = expired
function hc_CheckExpiration($a_stamp)
{
global $hc_salt, $hc_tolerance;
$expired = true;
$tempnow = intval(time() / 60);
$ip = $_SERVER['REMOTE_ADDR'];
// gen hashes for $tempnow ... $tempnow - $tolerance
for($i = 0; $i < $hc_tolerance; $i++)
{
// DEBUG_OUT("checking $a_stamp versus " . hc_HashFunc(($tempnow - $i) . $ip . $hc_salt));
if($a_stamp === hc_HashFunc(($tempnow - $i) . $ip . $hc_salt))
{
// DEBUG_OUT("stamp matched at T-Minus-" . $i);
$expired = false;
break;
}
}
return !($expired);
}
// check for collision of $stamp_contract bits for $stamp and $collision
function hc_CheckContract($stamp, $collision, $stamp_contract)
{
if($stamp_contract >= 32)
return false;
// get hash of $collision to compare to $stamp
$maybe_sum = hc_HashFunc($collision);
// DEBUG_OUT("checking contract of $stamp versus $maybe_sum for $stamp_contract bits");
$partone = hc_ExtractBits($stamp, $stamp_contract);
$parttwo = hc_ExtractBits($maybe_sum, $stamp_contract);
// DEBUG_OUT("checking $stamp_contract bits for $partone versus $parttwo");
return (strcmp($partone, $parttwo) == 0);
}
// check a stamp
// checks validity, expiration, and contract obligations for a stamp
function hc_CheckStamp()
{
global $hc_contract, $hc_maxcoll, $hc_stampsize;
$validstamp = true;
// used for debugging
/*
echo "<pre>";
print_r($_POST);
echo "</pre>";
*/
// get stamp from input
// todo: use is_notnull?
$stamp = $_POST['hc_stamp'];
$client_con = $_POST['hc_contract'];
$collision = $_POST['hc_collision'];
// DEBUG_OUT("got variables!");
// DEBUG_OUT("stamp: $stamp");
// DEBUG_OUT("hc_contract: $client_con");
// DEBUG_OUT("collision text: $collision");
// DEBUG_OUT("before all checks, valid stamp is $validstamp");
// optimized, fastest-test-first order
if($client_con != $hc_contract) $validstamp = false; // valid contract?
// DEBUG_OUT("contract comparison: $client_con and $hc_contract : $validstamp");
if($validstamp) if(strlen($stamp) != $hc_stampsize) $validstamp = false; // valid stamp?
// DEBUG_OUT("stamp size: " . strlen($stamp) . " and $hc_stampsize : $validstamp");
if($validstamp) if(strlen($collision) > $hc_maxcoll) $validstamp = false; // valid collision?
// DEBUG_OUT("collision size " . strlen($collision) . " <= $hc_maxcoll : $validstamp");
if($validstamp) $validstamp = hc_CheckExpiration($stamp); // stamp expired?
// DEBUG_OUT("checked expiration: $validstamp");
if($validstamp) $validstamp = hc_CheckContract($stamp, $collision, $contract); // collision meets contract?
// DEBUG_OUT("FINAL checked contract: $validstamp");
return $validstamp;
}
?> | 5,161 | hashcash | php | en | php | code | {"qsc_code_num_words": 659, "qsc_code_num_chars": 5161.0, "qsc_code_mean_word_length": 4.63125948, "qsc_code_frac_words_unique": 0.27465857, "qsc_code_frac_chars_top_2grams": 0.04456094, "qsc_code_frac_chars_top_3grams": 0.02228047, "qsc_code_frac_chars_top_4grams": 0.01867628, "qsc_code_frac_chars_dupe_5grams": 0.11631717, "qsc_code_frac_chars_dupe_6grams": 0.05733945, "qsc_code_frac_chars_dupe_7grams": 0.03407602, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02610114, "qsc_code_frac_chars_whitespace": 0.16857198, "qsc_code_size_file_byte": 5161.0, "qsc_code_num_lines": 185.0, "qsc_code_num_chars_line_max": 116.0, "qsc_code_num_chars_line_mean": 27.8972973, "qsc_code_frac_chars_alphabet": 0.68515498, "qsc_code_frac_chars_comments": 0.4053478, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.03921569, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.11009772, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.00540541, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
0015/map_tiles_projects | espressif_esp32_p4_function_ev_board/components/bsp_extra/src/bsp_board_extra.c | /*
* SPDX-FileCopyrightText: 2015-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "esp_log.h"
#include "esp_check.h"
#include "esp_codec_dev_defaults.h"
#include "esp_err.h"
#include "esp_log.h"
#include "esp_vfs_fat.h"
#include "driver/i2c.h"
#include "driver/i2s_std.h"
#include "driver/gpio.h"
#include "driver/ledc.h"
#include "bsp/esp-bsp.h"
#include "bsp_board_extra.h"
static const char *TAG = "bsp_extra_board";
static esp_codec_dev_handle_t play_dev_handle;
static esp_codec_dev_handle_t record_dev_handle;
static bool _is_audio_init = false;
static bool _is_player_init = false;
static int _vloume_intensity = CODEC_DEFAULT_VOLUME;
static audio_player_cb_t audio_idle_callback = NULL;
static void *audio_idle_cb_user_data = NULL;
static char audio_file_path[128];
/**************************************************************************************************
*
* Extra Board Function
*
**************************************************************************************************/
static esp_err_t audio_mute_function(AUDIO_PLAYER_MUTE_SETTING setting)
{
// Volume saved when muting and restored when unmuting. Restoring volume is necessary
// as es8311_set_voice_mute(true) results in voice volume (REG32) being set to zero.
bsp_extra_codec_mute_set(setting == AUDIO_PLAYER_MUTE ? true : false);
// restore the voice volume upon unmuting
if (setting == AUDIO_PLAYER_UNMUTE) {
ESP_RETURN_ON_ERROR(esp_codec_dev_set_out_vol(play_dev_handle, _vloume_intensity), TAG, "Set Codec volume failed");
}
return ESP_OK;
}
static void audio_callback(audio_player_cb_ctx_t *ctx)
{
if (audio_idle_callback) {
ctx->user_ctx = audio_idle_cb_user_data;
audio_idle_callback(ctx);
}
}
esp_err_t bsp_extra_i2s_read(void *audio_buffer, size_t len, size_t *bytes_read, uint32_t timeout_ms)
{
esp_err_t ret = ESP_OK;
ret = esp_codec_dev_read(record_dev_handle, audio_buffer, len);
*bytes_read = len;
return ret;
}
esp_err_t bsp_extra_i2s_write(void *audio_buffer, size_t len, size_t *bytes_written, uint32_t timeout_ms)
{
esp_err_t ret = ESP_OK;
ret = esp_codec_dev_write(play_dev_handle, audio_buffer, len);
*bytes_written = len;
return ret;
}
esp_err_t bsp_extra_codec_set_fs(uint32_t rate, uint32_t bits_cfg, i2s_slot_mode_t ch)
{
esp_err_t ret = ESP_OK;
esp_codec_dev_sample_info_t fs = {
.sample_rate = rate,
.channel = ch,
.bits_per_sample = bits_cfg,
};
if (play_dev_handle) {
ret = esp_codec_dev_close(play_dev_handle);
}
if (record_dev_handle) {
ret |= esp_codec_dev_close(record_dev_handle);
ret |= esp_codec_dev_set_in_gain(record_dev_handle, CODEC_DEFAULT_ADC_VOLUME);
}
if (play_dev_handle) {
ret |= esp_codec_dev_open(play_dev_handle, &fs);
}
if (record_dev_handle) {
ret |= esp_codec_dev_open(record_dev_handle, &fs);
}
return ret;
}
esp_err_t bsp_extra_codec_volume_set(int volume, int *volume_set)
{
ESP_RETURN_ON_ERROR(esp_codec_dev_set_out_vol(play_dev_handle, volume), TAG, "Set Codec volume failed");
_vloume_intensity = volume;
ESP_LOGI(TAG, "Setting volume: %d", volume);
return ESP_OK;
}
int bsp_extra_codec_volume_get(void)
{
return _vloume_intensity;
}
esp_err_t bsp_extra_codec_mute_set(bool enable)
{
esp_err_t ret = ESP_OK;
ret = esp_codec_dev_set_out_mute(play_dev_handle, enable);
return ret;
}
esp_err_t bsp_extra_codec_dev_stop(void)
{
esp_err_t ret = ESP_OK;
if (play_dev_handle) {
ret = esp_codec_dev_close(play_dev_handle);
}
if (record_dev_handle) {
ret = esp_codec_dev_close(record_dev_handle);
}
return ret;
}
esp_err_t bsp_extra_codec_dev_resume(void)
{
return bsp_extra_codec_set_fs(CODEC_DEFAULT_SAMPLE_RATE, CODEC_DEFAULT_BIT_WIDTH, CODEC_DEFAULT_CHANNEL);
}
esp_err_t bsp_extra_codec_init()
{
if (_is_audio_init) {
return ESP_OK;
}
play_dev_handle = bsp_audio_codec_speaker_init();
assert((play_dev_handle) && "play_dev_handle not initialized");
record_dev_handle = bsp_audio_codec_microphone_init();
assert((record_dev_handle) && "record_dev_handle not initialized");
bsp_extra_codec_set_fs(CODEC_DEFAULT_SAMPLE_RATE, CODEC_DEFAULT_BIT_WIDTH, CODEC_DEFAULT_CHANNEL);
_is_audio_init = true;
return ESP_OK;
}
esp_err_t bsp_extra_player_init(void)
{
if (_is_player_init) {
return ESP_OK;
}
audio_player_config_t config = { .mute_fn = audio_mute_function,
.write_fn = bsp_extra_i2s_write,
.clk_set_fn = bsp_extra_codec_set_fs,
.priority = 5
};
ESP_RETURN_ON_ERROR(audio_player_new(config), TAG, "audio_player_init failed");
audio_player_callback_register(audio_callback, NULL);
_is_player_init = true;
return ESP_OK;
}
esp_err_t bsp_extra_player_del(void)
{
_is_player_init = false;
ESP_RETURN_ON_ERROR(audio_player_delete(), TAG, "audio_player_delete failed");
return ESP_OK;
}
esp_err_t bsp_extra_file_instance_init(const char *path, file_iterator_instance_t **ret_instance)
{
ESP_RETURN_ON_FALSE(path, ESP_FAIL, TAG, "path is NULL");
ESP_RETURN_ON_FALSE(ret_instance, ESP_FAIL, TAG, "ret_instance is NULL");
file_iterator_instance_t *file_iterator = file_iterator_new(path);
ESP_RETURN_ON_FALSE(file_iterator, ESP_FAIL, TAG, "file_iterator_new failed, %s", path);
*ret_instance = file_iterator;
return ESP_OK;
}
esp_err_t bsp_extra_player_play_index(file_iterator_instance_t *instance, int index)
{
ESP_RETURN_ON_FALSE(instance, ESP_FAIL, TAG, "instance is NULL");
ESP_LOGI(TAG, "play_index(%d)", index);
char filename[128];
int retval = file_iterator_get_full_path_from_index(instance, index, filename, sizeof(filename));
ESP_RETURN_ON_FALSE(retval != 0, ESP_FAIL, TAG, "file_iterator_get_full_path_from_index failed");
ESP_LOGI(TAG, "opening file '%s'", filename);
FILE *fp = fopen(filename, "rb");
ESP_RETURN_ON_FALSE(fp, ESP_FAIL, TAG, "unable to open file");
ESP_LOGI(TAG, "Playing '%s'", filename);
ESP_RETURN_ON_ERROR(audio_player_play(fp), TAG, "audio_player_play failed");
memcpy(audio_file_path, filename, sizeof(audio_file_path));
return ESP_OK;
}
esp_err_t bsp_extra_player_play_file(const char *file_path)
{
ESP_LOGI(TAG, "opening file '%s'", file_path);
FILE *fp = fopen(file_path, "rb");
ESP_RETURN_ON_FALSE(fp, ESP_FAIL, TAG, "unable to open file");
ESP_LOGI(TAG, "Playing '%s'", file_path);
ESP_RETURN_ON_ERROR(audio_player_play(fp), TAG, "audio_player_play failed");
memcpy(audio_file_path, file_path, sizeof(audio_file_path));
return ESP_OK;
}
void bsp_extra_player_register_callback(audio_player_cb_t cb, void *user_data)
{
audio_idle_callback = cb;
audio_idle_cb_user_data = user_data;
}
bool bsp_extra_player_is_playing_by_path(const char *file_path)
{
return (strcmp(audio_file_path, file_path) == 0);
}
bool bsp_extra_player_is_playing_by_index(file_iterator_instance_t *instance, int index)
{
return (index == file_iterator_get_index(instance));
} | 7,419 | bsp_board_extra | c | en | c | code | {"qsc_code_num_words": 1103, "qsc_code_num_chars": 7419.0, "qsc_code_mean_word_length": 4.2574796, "qsc_code_frac_words_unique": 0.15231188, "qsc_code_frac_chars_top_2grams": 0.05366269, "qsc_code_frac_chars_top_3grams": 0.02832198, "qsc_code_frac_chars_top_4grams": 0.02768313, "qsc_code_frac_chars_dupe_5grams": 0.47614991, "qsc_code_frac_chars_dupe_6grams": 0.41034923, "qsc_code_frac_chars_dupe_7grams": 0.34795571, "qsc_code_frac_chars_dupe_8grams": 0.29620954, "qsc_code_frac_chars_dupe_9grams": 0.24126917, "qsc_code_frac_chars_dupe_10grams": 0.21358603, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00638193, "qsc_code_frac_chars_whitespace": 0.17630408, "qsc_code_size_file_byte": 7419.0, "qsc_code_num_lines": 259.0, "qsc_code_num_chars_line_max": 124.0, "qsc_code_num_chars_line_mean": 28.64478764, "qsc_code_frac_chars_alphabet": 0.7620684, "qsc_code_frac_chars_comments": 0.07602103, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.19047619, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0926196, "qsc_code_frac_chars_long_word_length": 0.00904317, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.01058201, "qsc_codec_frac_lines_func_ratio": 0.10582011, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.26984127, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": 0.07936508} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/map_tiles_projects | espressif_esp32_p4_function_ev_board/components/bsp_extra/include/bsp_board_extra.h | /*
* SPDX-FileCopyrightText: 2015-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <sys/cdefs.h>
#include <stdbool.h>
#include "esp_codec_dev.h"
#include "esp_err.h"
#include "driver/gpio.h"
#include "driver/i2s_std.h"
#include "audio_player.h"
#include "file_iterator.h"
#ifdef __cplusplus
extern "C" {
#endif
#define CODEC_DEFAULT_SAMPLE_RATE (16000)
#define CODEC_DEFAULT_BIT_WIDTH (16)
#define CODEC_DEFAULT_ADC_VOLUME (24.0)
#define CODEC_DEFAULT_CHANNEL (2)
#define CODEC_DEFAULT_VOLUME (60)
#define BSP_LCD_BACKLIGHT_BRIGHTNESS_MAX (95)
#define BSP_LCD_BACKLIGHT_BRIGHTNESS_MIN (0)
#define LCD_LEDC_CH (CONFIG_BSP_DISPLAY_BRIGHTNESS_LEDC_CH)
/**************************************************************************************************
* BSP Extra interface
* Mainly provided some I2S Codec interfaces.
**************************************************************************************************/
/**
* @brief Player set mute.
*
* @param enable: true or false
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_codec_mute_set(bool enable);
/**
* @brief Player set volume.
*
* @param volume: volume set
* @param volume_set: volume set response
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_codec_volume_set(int volume, int *volume_set);
/**
* @brief Player get volume.
*
* @return
* - volume: volume get
*/
int bsp_extra_codec_volume_get(void);
/**
* @brief Stop I2S function.
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_codec_dev_stop(void);
/**
* @brief Resume I2S function.
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_codec_dev_resume(void);
/**
* @brief Set I2S format to codec.
*
* @param rate: Sample rate of sample
* @param bits_cfg: Bit lengths of one channel data
* @param ch: Channels of sample
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_codec_set_fs(uint32_t rate, uint32_t bits_cfg, i2s_slot_mode_t ch);
/**
* @brief Read data from recoder.
*
* @param audio_buffer: The pointer of receiving data buffer
* @param len: Max data buffer length
* @param bytes_read: Byte number that actually be read, can be NULL if not needed
* @param timeout_ms: Max block time
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_i2s_read(void *audio_buffer, size_t len, size_t *bytes_read, uint32_t timeout_ms);
/**
* @brief Write data to player.
*
* @param audio_buffer: The pointer of sent data buffer
* @param len: Max data buffer length
* @param bytes_written: Byte number that actually be sent, can be NULL if not needed
* @param timeout_ms: Max block time
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_i2s_write(void *audio_buffer, size_t len, size_t *bytes_written, uint32_t timeout_ms);
/**
* @brief Initialize codec play and record handle.
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_codec_init();
/**
* @brief Initialize audio player task.
*
* @param path file path
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_player_init(void);
/**
* @brief Delete audio player task.
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_player_del(void);
/**
* @brief Initialize a file iterator instance
*
* @param path The file path for the iterator.
* @param ret_instance A pointer to the file iterator instance to be returned.
* @return
* - ESP_OK: Successfully initialized the file iterator instance.
* - ESP_FAIL: Failed to initialize the file iterator instance due to invalid parameters or memory allocation failure.
*/
esp_err_t bsp_extra_file_instance_init(const char *path, file_iterator_instance_t **ret_instance);
/**
* @brief Play the audio file at the specified index in the file iterator
*
* @param instance The file iterator instance.
* @param index The index of the file to play within the iterator.
* @return
* - ESP_OK: Successfully started playing the audio file.
* - ESP_FAIL: Failed to play the audio file due to invalid parameters or file access issues.
*/
esp_err_t bsp_extra_player_play_index(file_iterator_instance_t *instance, int index);
/**
* @brief Play the audio file specified by the file path
*
* @param file_path The path to the audio file to be played.
* @return
* - ESP_OK: Successfully started playing the audio file.
* - ESP_FAIL: Failed to play the audio file due to file access issues.
*/
esp_err_t bsp_extra_player_play_file(const char *file_path);
/**
* @brief Register a callback function for the audio player
*
* @param cb The callback function to be registered.
* @param user_data User data to be passed to the callback function.
*/
void bsp_extra_player_register_callback(audio_player_cb_t cb, void *user_data);
/**
* @brief Check if the specified audio file is currently playing
*
* @param file_path The path to the audio file to check.
* @return
* - true: The specified audio file is currently playing.
* - false: The specified audio file is not currently playing.
*/
bool bsp_extra_player_is_playing_by_path(const char *file_path);
/**
* @brief Check if the audio file at the specified index is currently playing
*
* @param instance The file iterator instance.
* @param index The index of the file to check.
* @return
* - true: The audio file at the specified index is currently playing.
* - false: The audio file at the specified index is not currently playing.
*/
bool bsp_extra_player_is_playing_by_index(file_iterator_instance_t *instance, int index);
#ifdef __cplusplus
}
#endif
| 5,915 | bsp_board_extra | h | en | c | code | {"qsc_code_num_words": 839, "qsc_code_num_chars": 5915.0, "qsc_code_mean_word_length": 4.55542312, "qsc_code_frac_words_unique": 0.21096544, "qsc_code_frac_chars_top_2grams": 0.03767661, "qsc_code_frac_chars_top_3grams": 0.03741497, "qsc_code_frac_chars_top_4grams": 0.03401361, "qsc_code_frac_chars_dupe_5grams": 0.53244375, "qsc_code_frac_chars_dupe_6grams": 0.45002616, "qsc_code_frac_chars_dupe_7grams": 0.42752486, "qsc_code_frac_chars_dupe_8grams": 0.39900576, "qsc_code_frac_chars_dupe_9grams": 0.3689168, "qsc_code_frac_chars_dupe_10grams": 0.35164835, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00885329, "qsc_code_frac_chars_whitespace": 0.19797126, "qsc_code_size_file_byte": 5915.0, "qsc_code_num_lines": 219.0, "qsc_code_num_chars_line_max": 123.0, "qsc_code_num_chars_line_mean": 27.00913242, "qsc_code_frac_chars_alphabet": 0.79679595, "qsc_code_frac_chars_comments": 0.68199493, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.1, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.04412547, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.425, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 1.0, "qsc_codec_score_lines_no_logic": 0.625, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 1, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/map_tiles_projects | waveshare_esp32_p4_wifi6_touch_lcd_xc/main/main.cpp | #include "nvs_flash.h"
#include "esp_check.h"
#include "esp_log.h"
#include "esp_err.h"
#include "bsp_board_extra.h"
#include "bsp/esp-bsp.h"
#include "lvgl.h"
#include "simple_map.hpp"
extern "C" void app_main(void)
{
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
bsp_i2c_init();
esp_err_t err = bsp_sdcard_mount();
if (err != ESP_OK) {
printf("Failed to mount SD card, error: %s\n", esp_err_to_name(err));
}
bsp_display_cfg_t cfg = {
.lvgl_port_cfg = ESP_LVGL_PORT_INIT_CONFIG(),
.buffer_size = BSP_LCD_DRAW_BUFF_SIZE,
.double_buffer = BSP_LCD_DRAW_BUFF_DOUBLE,
.flags = {
.buff_dma = true,
.buff_spiram = false,
.sw_rotate = false,
}
};
bsp_display_start_with_config(&cfg);
bsp_display_backlight_on();
bsp_display_brightness_set(100);
bsp_display_lock(0);
// Initialize the simple map
if (!SimpleMap::init(lv_screen_active())) {
printf("Failed to initialize map\n");
return;
}
// Show a location (example coordinates)
SimpleMap::show_location( 37.77490, -122.41942, 16);
SimpleMap::center_map_on_gps();
bsp_display_unlock();
} | 1,390 | main | cpp | en | cpp | code | {"qsc_code_num_words": 197, "qsc_code_num_chars": 1390.0, "qsc_code_mean_word_length": 4.10659898, "qsc_code_frac_words_unique": 0.45685279, "qsc_code_frac_chars_top_2grams": 0.06922126, "qsc_code_frac_chars_top_3grams": 0.0407911, "qsc_code_frac_chars_top_4grams": 0.03708282, "qsc_code_frac_chars_dupe_5grams": 0.0, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02065728, "qsc_code_frac_chars_whitespace": 0.23381295, "qsc_code_size_file_byte": 1390.0, "qsc_code_num_lines": 54.0, "qsc_code_num_chars_line_max": 84.0, "qsc_code_num_chars_line_mean": 25.74074074, "qsc_code_frac_chars_alphabet": 0.73896714, "qsc_code_frac_chars_comments": 0.05035971, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.11582135, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.18604651, "qsc_codecpp_frac_lines_func_ratio": 0.02325581, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.23255814, "qsc_codecpp_frac_lines_print": 0.04651163} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0} |
0015/map_tiles_projects | waveshare_esp32_p4_wifi6_touch_lcd_xc/components/bsp_extra/src/bsp_board_extra.c | /*
* SPDX-FileCopyrightText: 2015-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "esp_log.h"
#include "esp_check.h"
#include "esp_codec_dev_defaults.h"
#include "esp_err.h"
#include "esp_log.h"
#include "esp_vfs_fat.h"
#include "driver/i2c.h"
#include "driver/i2s_std.h"
#include "driver/gpio.h"
#include "driver/ledc.h"
#include "bsp/esp-bsp.h"
#include "bsp_board_extra.h"
static const char *TAG = "bsp_extra_board";
static esp_codec_dev_handle_t play_dev_handle;
static esp_codec_dev_handle_t record_dev_handle;
static bool _is_audio_init = false;
static bool _is_player_init = false;
static int _vloume_intensity = CODEC_DEFAULT_VOLUME;
static audio_player_cb_t audio_idle_callback = NULL;
static void *audio_idle_cb_user_data = NULL;
static char audio_file_path[128];
/**************************************************************************************************
*
* Extra Board Function
*
**************************************************************************************************/
static esp_err_t audio_mute_function(AUDIO_PLAYER_MUTE_SETTING setting)
{
// Volume saved when muting and restored when unmuting. Restoring volume is necessary
// as es8311_set_voice_mute(true) results in voice volume (REG32) being set to zero.
bsp_extra_codec_mute_set(setting == AUDIO_PLAYER_MUTE ? true : false);
// restore the voice volume upon unmuting
if (setting == AUDIO_PLAYER_UNMUTE) {
ESP_RETURN_ON_ERROR(esp_codec_dev_set_out_vol(play_dev_handle, _vloume_intensity), TAG, "Set Codec volume failed");
}
return ESP_OK;
}
static void audio_callback(audio_player_cb_ctx_t *ctx)
{
if (audio_idle_callback) {
ctx->user_ctx = audio_idle_cb_user_data;
audio_idle_callback(ctx);
}
}
esp_err_t bsp_extra_i2s_read(void *audio_buffer, size_t len, size_t *bytes_read, uint32_t timeout_ms)
{
esp_err_t ret = ESP_OK;
ret = esp_codec_dev_read(record_dev_handle, audio_buffer, len);
*bytes_read = len;
return ret;
}
esp_err_t bsp_extra_i2s_write(void *audio_buffer, size_t len, size_t *bytes_written, uint32_t timeout_ms)
{
esp_err_t ret = ESP_OK;
ret = esp_codec_dev_write(play_dev_handle, audio_buffer, len);
*bytes_written = len;
return ret;
}
esp_err_t bsp_extra_codec_set_fs(uint32_t rate, uint32_t bits_cfg, i2s_slot_mode_t ch)
{
esp_err_t ret = ESP_OK;
esp_codec_dev_sample_info_t fs = {
.sample_rate = rate,
.channel = ch,
.bits_per_sample = bits_cfg,
};
if (play_dev_handle) {
ret = esp_codec_dev_close(play_dev_handle);
}
if (record_dev_handle) {
ret |= esp_codec_dev_close(record_dev_handle);
ret |= esp_codec_dev_set_in_gain(record_dev_handle, CODEC_DEFAULT_ADC_VOLUME);
}
if (play_dev_handle) {
ret |= esp_codec_dev_open(play_dev_handle, &fs);
}
if (record_dev_handle) {
ret |= esp_codec_dev_open(record_dev_handle, &fs);
}
return ret;
}
esp_err_t bsp_extra_codec_volume_set(int volume, int *volume_set)
{
ESP_RETURN_ON_ERROR(esp_codec_dev_set_out_vol(play_dev_handle, volume), TAG, "Set Codec volume failed");
_vloume_intensity = volume;
ESP_LOGI(TAG, "Setting volume: %d", volume);
return ESP_OK;
}
int bsp_extra_codec_volume_get(void)
{
return _vloume_intensity;
}
esp_err_t bsp_extra_codec_mute_set(bool enable)
{
esp_err_t ret = ESP_OK;
ret = esp_codec_dev_set_out_mute(play_dev_handle, enable);
return ret;
}
esp_err_t bsp_extra_codec_dev_stop(void)
{
esp_err_t ret = ESP_OK;
if (play_dev_handle) {
ret = esp_codec_dev_close(play_dev_handle);
}
if (record_dev_handle) {
ret = esp_codec_dev_close(record_dev_handle);
}
return ret;
}
esp_err_t bsp_extra_codec_dev_resume(void)
{
return bsp_extra_codec_set_fs(CODEC_DEFAULT_SAMPLE_RATE, CODEC_DEFAULT_BIT_WIDTH, CODEC_DEFAULT_CHANNEL);
}
esp_err_t bsp_extra_codec_init()
{
if (_is_audio_init) {
return ESP_OK;
}
play_dev_handle = bsp_audio_codec_speaker_init();
assert((play_dev_handle) && "play_dev_handle not initialized");
record_dev_handle = bsp_audio_codec_microphone_init();
assert((record_dev_handle) && "record_dev_handle not initialized");
bsp_extra_codec_set_fs(CODEC_DEFAULT_SAMPLE_RATE, CODEC_DEFAULT_BIT_WIDTH, CODEC_DEFAULT_CHANNEL);
_is_audio_init = true;
return ESP_OK;
}
esp_err_t bsp_extra_player_init(void)
{
if (_is_player_init) {
return ESP_OK;
}
audio_player_config_t config = { .mute_fn = audio_mute_function,
.write_fn = bsp_extra_i2s_write,
.clk_set_fn = bsp_extra_codec_set_fs,
.priority = 5
};
ESP_RETURN_ON_ERROR(audio_player_new(config), TAG, "audio_player_init failed");
audio_player_callback_register(audio_callback, NULL);
_is_player_init = true;
return ESP_OK;
}
esp_err_t bsp_extra_player_del(void)
{
_is_player_init = false;
ESP_RETURN_ON_ERROR(audio_player_delete(), TAG, "audio_player_delete failed");
return ESP_OK;
}
esp_err_t bsp_extra_file_instance_init(const char *path, file_iterator_instance_t **ret_instance)
{
ESP_RETURN_ON_FALSE(path, ESP_FAIL, TAG, "path is NULL");
ESP_RETURN_ON_FALSE(ret_instance, ESP_FAIL, TAG, "ret_instance is NULL");
file_iterator_instance_t *file_iterator = file_iterator_new(path);
ESP_RETURN_ON_FALSE(file_iterator, ESP_FAIL, TAG, "file_iterator_new failed, %s", path);
*ret_instance = file_iterator;
return ESP_OK;
}
esp_err_t bsp_extra_player_play_index(file_iterator_instance_t *instance, int index)
{
ESP_RETURN_ON_FALSE(instance, ESP_FAIL, TAG, "instance is NULL");
ESP_LOGI(TAG, "play_index(%d)", index);
char filename[128];
int retval = file_iterator_get_full_path_from_index(instance, index, filename, sizeof(filename));
ESP_RETURN_ON_FALSE(retval != 0, ESP_FAIL, TAG, "file_iterator_get_full_path_from_index failed");
ESP_LOGI(TAG, "opening file '%s'", filename);
FILE *fp = fopen(filename, "rb");
ESP_RETURN_ON_FALSE(fp, ESP_FAIL, TAG, "unable to open file");
ESP_LOGI(TAG, "Playing '%s'", filename);
ESP_RETURN_ON_ERROR(audio_player_play(fp), TAG, "audio_player_play failed");
memcpy(audio_file_path, filename, sizeof(audio_file_path));
return ESP_OK;
}
esp_err_t bsp_extra_player_play_file(const char *file_path)
{
ESP_LOGI(TAG, "opening file '%s'", file_path);
FILE *fp = fopen(file_path, "rb");
ESP_RETURN_ON_FALSE(fp, ESP_FAIL, TAG, "unable to open file");
ESP_LOGI(TAG, "Playing '%s'", file_path);
ESP_RETURN_ON_ERROR(audio_player_play(fp), TAG, "audio_player_play failed");
memcpy(audio_file_path, file_path, sizeof(audio_file_path));
return ESP_OK;
}
void bsp_extra_player_register_callback(audio_player_cb_t cb, void *user_data)
{
audio_idle_callback = cb;
audio_idle_cb_user_data = user_data;
}
bool bsp_extra_player_is_playing_by_path(const char *file_path)
{
return (strcmp(audio_file_path, file_path) == 0);
}
bool bsp_extra_player_is_playing_by_index(file_iterator_instance_t *instance, int index)
{
return (index == file_iterator_get_index(instance));
} | 7,419 | bsp_board_extra | c | en | c | code | {"qsc_code_num_words": 1103, "qsc_code_num_chars": 7419.0, "qsc_code_mean_word_length": 4.2574796, "qsc_code_frac_words_unique": 0.15231188, "qsc_code_frac_chars_top_2grams": 0.05366269, "qsc_code_frac_chars_top_3grams": 0.02832198, "qsc_code_frac_chars_top_4grams": 0.02768313, "qsc_code_frac_chars_dupe_5grams": 0.47614991, "qsc_code_frac_chars_dupe_6grams": 0.41034923, "qsc_code_frac_chars_dupe_7grams": 0.34795571, "qsc_code_frac_chars_dupe_8grams": 0.29620954, "qsc_code_frac_chars_dupe_9grams": 0.24126917, "qsc_code_frac_chars_dupe_10grams": 0.21358603, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00638193, "qsc_code_frac_chars_whitespace": 0.17630408, "qsc_code_size_file_byte": 7419.0, "qsc_code_num_lines": 259.0, "qsc_code_num_chars_line_max": 124.0, "qsc_code_num_chars_line_mean": 28.64478764, "qsc_code_frac_chars_alphabet": 0.7620684, "qsc_code_frac_chars_comments": 0.07602103, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.19047619, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0926196, "qsc_code_frac_chars_long_word_length": 0.00904317, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.01058201, "qsc_codec_frac_lines_func_ratio": 0.10582011, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.26984127, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": 0.07936508} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/map_tiles_projects | waveshare_esp32_p4_wifi6_touch_lcd_xc/components/bsp_extra/include/bsp_board_extra.h | /*
* SPDX-FileCopyrightText: 2015-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <sys/cdefs.h>
#include <stdbool.h>
#include "esp_codec_dev.h"
#include "esp_err.h"
#include "driver/gpio.h"
#include "driver/i2s_std.h"
#include "audio_player.h"
#include "file_iterator.h"
#ifdef __cplusplus
extern "C" {
#endif
#define CODEC_DEFAULT_SAMPLE_RATE (16000)
#define CODEC_DEFAULT_BIT_WIDTH (16)
#define CODEC_DEFAULT_ADC_VOLUME (24.0)
#define CODEC_DEFAULT_CHANNEL (2)
#define CODEC_DEFAULT_VOLUME (60)
#define BSP_LCD_BACKLIGHT_BRIGHTNESS_MAX (95)
#define BSP_LCD_BACKLIGHT_BRIGHTNESS_MIN (0)
#define LCD_LEDC_CH (CONFIG_BSP_DISPLAY_BRIGHTNESS_LEDC_CH)
/**************************************************************************************************
* BSP Extra interface
* Mainly provided some I2S Codec interfaces.
**************************************************************************************************/
/**
* @brief Player set mute.
*
* @param enable: true or false
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_codec_mute_set(bool enable);
/**
* @brief Player set volume.
*
* @param volume: volume set
* @param volume_set: volume set response
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_codec_volume_set(int volume, int *volume_set);
/**
* @brief Player get volume.
*
* @return
* - volume: volume get
*/
int bsp_extra_codec_volume_get(void);
/**
* @brief Stop I2S function.
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_codec_dev_stop(void);
/**
* @brief Resume I2S function.
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_codec_dev_resume(void);
/**
* @brief Set I2S format to codec.
*
* @param rate: Sample rate of sample
* @param bits_cfg: Bit lengths of one channel data
* @param ch: Channels of sample
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_codec_set_fs(uint32_t rate, uint32_t bits_cfg, i2s_slot_mode_t ch);
/**
* @brief Read data from recoder.
*
* @param audio_buffer: The pointer of receiving data buffer
* @param len: Max data buffer length
* @param bytes_read: Byte number that actually be read, can be NULL if not needed
* @param timeout_ms: Max block time
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_i2s_read(void *audio_buffer, size_t len, size_t *bytes_read, uint32_t timeout_ms);
/**
* @brief Write data to player.
*
* @param audio_buffer: The pointer of sent data buffer
* @param len: Max data buffer length
* @param bytes_written: Byte number that actually be sent, can be NULL if not needed
* @param timeout_ms: Max block time
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_i2s_write(void *audio_buffer, size_t len, size_t *bytes_written, uint32_t timeout_ms);
/**
* @brief Initialize codec play and record handle.
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_codec_init();
/**
* @brief Initialize audio player task.
*
* @param path file path
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_player_init(void);
/**
* @brief Delete audio player task.
*
* @return
* - ESP_OK: Success
* - Others: Fail
*/
esp_err_t bsp_extra_player_del(void);
/**
* @brief Initialize a file iterator instance
*
* @param path The file path for the iterator.
* @param ret_instance A pointer to the file iterator instance to be returned.
* @return
* - ESP_OK: Successfully initialized the file iterator instance.
* - ESP_FAIL: Failed to initialize the file iterator instance due to invalid parameters or memory allocation failure.
*/
esp_err_t bsp_extra_file_instance_init(const char *path, file_iterator_instance_t **ret_instance);
/**
* @brief Play the audio file at the specified index in the file iterator
*
* @param instance The file iterator instance.
* @param index The index of the file to play within the iterator.
* @return
* - ESP_OK: Successfully started playing the audio file.
* - ESP_FAIL: Failed to play the audio file due to invalid parameters or file access issues.
*/
esp_err_t bsp_extra_player_play_index(file_iterator_instance_t *instance, int index);
/**
* @brief Play the audio file specified by the file path
*
* @param file_path The path to the audio file to be played.
* @return
* - ESP_OK: Successfully started playing the audio file.
* - ESP_FAIL: Failed to play the audio file due to file access issues.
*/
esp_err_t bsp_extra_player_play_file(const char *file_path);
/**
* @brief Register a callback function for the audio player
*
* @param cb The callback function to be registered.
* @param user_data User data to be passed to the callback function.
*/
void bsp_extra_player_register_callback(audio_player_cb_t cb, void *user_data);
/**
* @brief Check if the specified audio file is currently playing
*
* @param file_path The path to the audio file to check.
* @return
* - true: The specified audio file is currently playing.
* - false: The specified audio file is not currently playing.
*/
bool bsp_extra_player_is_playing_by_path(const char *file_path);
/**
* @brief Check if the audio file at the specified index is currently playing
*
* @param instance The file iterator instance.
* @param index The index of the file to check.
* @return
* - true: The audio file at the specified index is currently playing.
* - false: The audio file at the specified index is not currently playing.
*/
bool bsp_extra_player_is_playing_by_index(file_iterator_instance_t *instance, int index);
#ifdef __cplusplus
}
#endif
| 5,915 | bsp_board_extra | h | en | c | code | {"qsc_code_num_words": 839, "qsc_code_num_chars": 5915.0, "qsc_code_mean_word_length": 4.55542312, "qsc_code_frac_words_unique": 0.21096544, "qsc_code_frac_chars_top_2grams": 0.03767661, "qsc_code_frac_chars_top_3grams": 0.03741497, "qsc_code_frac_chars_top_4grams": 0.03401361, "qsc_code_frac_chars_dupe_5grams": 0.53244375, "qsc_code_frac_chars_dupe_6grams": 0.45002616, "qsc_code_frac_chars_dupe_7grams": 0.42752486, "qsc_code_frac_chars_dupe_8grams": 0.39900576, "qsc_code_frac_chars_dupe_9grams": 0.3689168, "qsc_code_frac_chars_dupe_10grams": 0.35164835, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00885329, "qsc_code_frac_chars_whitespace": 0.19797126, "qsc_code_size_file_byte": 5915.0, "qsc_code_num_lines": 219.0, "qsc_code_num_chars_line_max": 123.0, "qsc_code_num_chars_line_mean": 27.00913242, "qsc_code_frac_chars_alphabet": 0.79679595, "qsc_code_frac_chars_comments": 0.68199493, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.1, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.04412547, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.425, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 1.0, "qsc_codec_score_lines_no_logic": 0.625, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 1, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
007LiZhen/FFmpeg-QT-rtsp | mainwindow.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="enabled">
<bool>true</bool>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>506</width>
<height>399</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<property name="layoutDirection">
<enum>Qt::LeftToRight</enum>
</property>
<property name="iconSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<widget class="QWidget" name="centralwidget"/>
<widget class="QMenuBar" name="menuBar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>506</width>
<height>23</height>
</rect>
</property>
<widget class="QMenu" name="menu">
<property name="title">
<string>红色分量开关</string>
</property>
<addaction name="Open_red"/>
<addaction name="Close_Red"/>
</widget>
<addaction name="menu"/>
</widget>
<action name="actionOpen">
<property name="text">
<string>Open</string>
</property>
</action>
<action name="Open_red">
<property name="text">
<string>Open(&O)</string>
</property>
</action>
<action name="Close_Red">
<property name="text">
<string>Close(&C)</string>
</property>
</action>
</widget>
<resources/>
<connections/>
</ui>
| 1,640 | mainwindow | ui | en | xml | data | {"qsc_code_num_words": 183, "qsc_code_num_chars": 1640.0, "qsc_code_mean_word_length": 5.46448087, "qsc_code_frac_words_unique": 0.33879781, "qsc_code_frac_chars_top_2grams": 0.132, "qsc_code_frac_chars_top_3grams": 0.1, "qsc_code_frac_chars_top_4grams": 0.066, "qsc_code_frac_chars_dupe_5grams": 0.238, "qsc_code_frac_chars_dupe_6grams": 0.098, "qsc_code_frac_chars_dupe_7grams": 0.098, "qsc_code_frac_chars_dupe_8grams": 0.098, "qsc_code_frac_chars_dupe_9grams": 0.098, "qsc_code_frac_chars_dupe_10grams": 0.098, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01941748, "qsc_code_frac_chars_whitespace": 0.18353659, "qsc_code_size_file_byte": 1640.0, "qsc_code_num_lines": 71.0, "qsc_code_num_chars_line_max": 60.0, "qsc_code_num_chars_line_mean": 23.09859155, "qsc_code_frac_chars_alphabet": 0.72740851, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 1.0, "qsc_code_frac_lines_dupe_lines": 0.45070423, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.13780488, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_words_unique": 1, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 1, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0} |
007LiZhen/FFmpeg-QT-rtsp | videoplayer.cpp | /**
* 李震
* 我的码云:https://git.oschina.net/git-lizhen
* 我的CSDN博客:http://blog.csdn.net/weixin_38215395
* 联系:QQ1039953685
*/
#include "videoplayer.h"
extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/pixfmt.h"
#include "libswscale/swscale.h"
}
#include <stdio.h>
#include<iostream>
using namespace std;
VideoPlayer::VideoPlayer()
{
}
VideoPlayer::~VideoPlayer()
{
}
void VideoPlayer::startPlay()
{
///调用 QThread 的start函数 将会自动执行下面的run函数 run函数是一个新的线程
this->start();
}
void VideoPlayer::run()
{
AVFormatContext *pFormatCtx;
AVCodecContext *pCodecCtx;
AVCodec *pCodec;
AVFrame *pFrame, *pFrameRGB;
AVPacket *packet;
uint8_t *out_buffer;
static struct SwsContext *img_convert_ctx;
int videoStream, i, numBytes;
int ret, got_picture;
avformat_network_init(); ///初始化FFmpeg网络模块,2017.8.5---lizhen
av_register_all(); //初始化FFMPEG 调用了这个才能正常适用编码器和解码器
//Allocate an AVFormatContext.
pFormatCtx = avformat_alloc_context();
///2017.8.5---lizhen
AVDictionary *avdic=NULL;
char option_key[]="rtsp_transport";
char option_value[]="tcp";
av_dict_set(&avdic,option_key,option_value,0);
char option_key2[]="max_delay";
char option_value2[]="100";
av_dict_set(&avdic,option_key2,option_value2,0);
///rtsp地址,可根据实际情况修改
char url[]="rtsp://admin:admin@192.168.1.18:554/h264/ch1/main/av_stream";
if (avformat_open_input(&pFormatCtx, url, NULL, &avdic) != 0) {
printf("can't open the file. \n");
return;
}
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
printf("Could't find stream infomation.\n");
return;
}
videoStream = -1;
///循环查找视频中包含的流信息,直到找到视频类型的流
///便将其记录下来 保存到videoStream变量中
///这里我们现在只处理视频流 音频流先不管他
for (i = 0; i < pFormatCtx->nb_streams; i++) {
if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
videoStream = i;
}
}
///如果videoStream为-1 说明没有找到视频流
if (videoStream == -1) {
printf("Didn't find a video stream.\n");
return;
}
///查找解码器
pCodecCtx = pFormatCtx->streams[videoStream]->codec;
pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
///2017.8.9---lizhen
pCodecCtx->bit_rate =0; //初始化为0
pCodecCtx->time_base.num=1; //下面两行:一秒钟25帧
pCodecCtx->time_base.den=10;
pCodecCtx->frame_number=1; //每包一个视频帧
if (pCodec == NULL) {
printf("Codec not found.\n");
return;
}
///打开解码器
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
printf("Could not open codec.\n");
return;
}
pFrame = av_frame_alloc();
pFrameRGB = av_frame_alloc();
///这里我们改成了 将解码后的YUV数据转换成RGB32
img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height,
pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height,
PIX_FMT_RGB32, SWS_BICUBIC, NULL, NULL, NULL);
numBytes = avpicture_get_size(PIX_FMT_RGB32, pCodecCtx->width,pCodecCtx->height);
out_buffer = (uint8_t *) av_malloc(numBytes * sizeof(uint8_t));
avpicture_fill((AVPicture *) pFrameRGB, out_buffer, PIX_FMT_RGB32,
pCodecCtx->width, pCodecCtx->height);
int y_size = pCodecCtx->width * pCodecCtx->height;
packet = (AVPacket *) malloc(sizeof(AVPacket)); //分配一个packet
av_new_packet(packet, y_size); //分配packet的数据
while (1)
{
if (av_read_frame(pFormatCtx, packet) < 0)
{
break; //这里认为视频读取完了
}
if (packet->stream_index == videoStream) {
ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture,packet);
if (ret < 0) {
printf("decode error.\n");
return;
}
if (got_picture) {
sws_scale(img_convert_ctx,
(uint8_t const * const *) pFrame->data,
pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data,
pFrameRGB->linesize);
//把这个RGB数据 用QImage加载
QImage tmpImg((uchar *)out_buffer,pCodecCtx->width,pCodecCtx->height,QImage::Format_RGB32);
QImage image = tmpImg.copy(); //把图像复制一份 传递给界面显示
emit sig_GetOneFrame(image); //发送信号
///2017.8.11---lizhen
//提取出图像中的R数据
for(int i=0;i<pCodecCtx->width;i++)
{
for(int j=0;j<pCodecCtx->height;j++)
{
QRgb rgb=image.pixel(i,j);
int r=qRed(rgb);
image.setPixel(i,j,qRgb(r,0,0));
}
}
emit sig_GetRFrame(image);
}
}
av_free_packet(packet); //释放资源,否则内存会一直上升
///2017.8.7---lizhen
msleep(0.02); //停一停 不然放的太快了
}
av_free(out_buffer);
av_free(pFrameRGB);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
}
| 5,036 | videoplayer | cpp | zh | cpp | code | {"qsc_code_num_words": 677, "qsc_code_num_chars": 5036.0, "qsc_code_mean_word_length": 4.26587888, "qsc_code_frac_words_unique": 0.43722304, "qsc_code_frac_chars_top_2grams": 0.04155125, "qsc_code_frac_chars_top_3grams": 0.04778393, "qsc_code_frac_chars_top_4grams": 0.06024931, "qsc_code_frac_chars_dupe_5grams": 0.04155125, "qsc_code_frac_chars_dupe_6grams": 0.02770083, "qsc_code_frac_chars_dupe_7grams": 0.02770083, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03170265, "qsc_code_frac_chars_whitespace": 0.27343129, "qsc_code_size_file_byte": 5036.0, "qsc_code_num_lines": 183.0, "qsc_code_num_chars_line_max": 108.0, "qsc_code_num_chars_line_mean": 27.51912568, "qsc_code_frac_chars_alphabet": 0.75731074, "qsc_code_frac_chars_comments": 0.13919778, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.05042017, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00840336, "qsc_code_frac_chars_string_length": 0.074527, "qsc_code_frac_chars_long_word_length": 0.01868943, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.07563025, "qsc_codecpp_frac_lines_func_ratio": 0.03361345, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.13445378, "qsc_codecpp_frac_lines_print": 0.05042017} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0} |
007LiZhen/FFmpeg-QT-rtsp | README.md | # FFmpeg-QT实现摄像头rtsp实时显示
1. 程序运行平台:(1)win10 64bit (2)Qt Creator 4.3.1
2. 程序需要的库:(1)Qt 5.9.1(MSVC 2015,32bit) (2)FFmpeg 2.5.2
3. 程序流程图:
程序流程图如图1所示,图中所示的主函数部分主要完成界面的构建、播放线程的建立以及参考坐标系的建立。图1展示了整个程序的运行流程。

4. 程序界面:
程序运行界面如图2所示。

5. 主要功能:
该界面主要实现四个功能:
(1).读取摄像头视频流(rtsp),并实时显示到主界面上(注:存在0.7s左右的延时,延时测试过程如图3所示);

(2).将rtsp视频流经过FFmpeg解码后的YUV数据转化成RGB32数据,提取其中的R(红色)通道,并在界面中的小窗显示(如图2中的左上角部分);
(3).将水下机器人的横滚角反映在界面上(如图2中,中间部分的虚线“十字”为水平和竖直参考位置;实线“十字”为横滚运动后机器人相对参考位置的角度变化,图示为模拟横滚角为10度的情形)。
(4).若程序掉电,再次上电后能够自动地建立连接。
| 828 | README | md | zh | markdown | text | {"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 34.0, "qsc_doc_num_words": 265, "qsc_doc_num_chars": 828.0, "qsc_doc_num_lines": 22.0, "qsc_doc_mean_word_length": 2.39245283, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.50188679, "qsc_doc_entropy_unigram": 4.60880504, "qsc_doc_frac_words_all_caps": 0.01262626, "qsc_doc_frac_lines_dupe_lines": 0.0, "qsc_doc_frac_chars_dupe_lines": 0.0, "qsc_doc_frac_chars_top_2grams": 0.02365931, "qsc_doc_frac_chars_top_3grams": 0.07097792, "qsc_doc_frac_chars_top_4grams": 0.0851735, "qsc_doc_frac_chars_dupe_5grams": 0.18454259, "qsc_doc_frac_chars_dupe_6grams": 0.18454259, "qsc_doc_frac_chars_dupe_7grams": 0.18454259, "qsc_doc_frac_chars_dupe_8grams": 0.18454259, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 14.35185185, "qsc_doc_frac_chars_hyperlink_html_tag": 0.0, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.16062176, "qsc_doc_frac_chars_whitespace": 0.06763285, "qsc_doc_frac_chars_hex_words": 0.0} | 1 | {"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_full_bracket": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0} |
000haoji/deep-student | src-tauri/src/file_manager.rs | use std::fs;
use std::path::{Path, PathBuf};
use std::io::Write;
use tokio::fs as async_fs;
// use tokio::io::AsyncWriteExt; // Removed unused import
use base64::{Engine as _, engine::general_purpose};
use uuid::Uuid;
use crate::models::AppError;
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
type Result<T> = std::result::Result<T, AppError>;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageStatistics {
pub total_files: u64,
pub total_size_bytes: u64,
pub file_types: HashMap<String, u32>, // extension -> count
pub oldest_file: Option<u64>, // timestamp
pub newest_file: Option<u64>, // timestamp
}
pub struct FileManager {
app_data_dir: PathBuf,
images_dir: PathBuf,
}
impl FileManager {
/// 创建新的文件管理器
pub fn new(app_data_dir: PathBuf) -> Result<Self> {
let images_dir = app_data_dir.join("images");
println!("初始化文件管理器: {:?}", app_data_dir);
Ok(FileManager {
app_data_dir,
images_dir,
})
}
/// 获取数据库路径
pub fn get_database_path(&self) -> PathBuf {
self.app_data_dir.join("mistakes.db")
}
/// 保存base64编码的图片文件
pub async fn save_image_from_base64(&self, base64_data: &str, filename: &str) -> Result<String> {
println!("保存图片文件: {}", filename);
// 确保图片目录存在
async_fs::create_dir_all(&self.images_dir).await
.map_err(|e| AppError::file_system(format!("创建图片目录失败: {}", e)))?;
// 解析base64数据
let data_url_prefix = "data:image/";
let base64_start = if base64_data.starts_with(data_url_prefix) {
base64_data.find("base64,")
.ok_or_else(|| AppError::validation("无效的base64数据格式"))?
+ 7 // "base64,".len()
} else {
0
};
let base64_content = &base64_data[base64_start..];
let image_bytes = general_purpose::STANDARD
.decode(base64_content)
.map_err(|e| AppError::validation(format!("base64解码失败: {}", e)))?;
// 保存文件
let file_path = self.images_dir.join(filename);
async_fs::write(&file_path, image_bytes).await
.map_err(|e| AppError::file_system(format!("保存图片文件失败: {}", e)))?;
// 返回相对路径
Ok(format!("images/{}", filename))
}
/// 读取图片文件为base64(用于统一AI接口)
pub fn read_file_as_base64(&self, relative_path: &str) -> Result<String> {
println!("读取图片文件为base64: {}", relative_path);
let file_path = self.app_data_dir.join(relative_path);
if !file_path.exists() {
return Err(AppError::not_found(format!("图片文件不存在: {}", relative_path)));
}
let image_bytes = fs::read(&file_path)
.map_err(|e| AppError::file_system(format!("读取图片文件失败: {}", e)))?;
let base64_content = general_purpose::STANDARD.encode(&image_bytes);
Ok(base64_content)
}
/// 读取图片文件为base64(带MIME类型)
pub async fn get_image_as_base64(&self, relative_path: &str) -> Result<String> {
println!("读取图片文件: {}", relative_path);
let file_path = self.app_data_dir.join(relative_path);
if !async_fs::try_exists(&file_path).await
.map_err(|e| AppError::file_system(format!("检查文件存在性失败: {}", e)))? {
return Err(AppError::not_found(format!("图片文件不存在: {}", relative_path)));
}
let image_bytes = async_fs::read(&file_path).await
.map_err(|e| AppError::file_system(format!("读取图片文件失败: {}", e)))?;
let base64_content = general_purpose::STANDARD.encode(&image_bytes);
// 根据文件扩展名确定MIME类型
let mime_type = if relative_path.ends_with(".png") {
"image/png"
} else if relative_path.ends_with(".gif") {
"image/gif"
} else {
"image/jpeg"
};
Ok(format!("data:{};base64,{}", mime_type, base64_content))
}
/// 删除图片文件
pub async fn delete_image(&self, relative_path: &str) -> Result<()> {
println!("删除图片文件: {}", relative_path);
let file_path = self.app_data_dir.join(relative_path);
if async_fs::try_exists(&file_path).await
.map_err(|e| AppError::file_system(format!("检查文件存在性失败: {}", e)))? {
async_fs::remove_file(&file_path).await
.map_err(|e| AppError::file_system(format!("删除图片文件失败: {}", e)))?;
}
Ok(())
}
/// 删除多个图片文件
pub fn delete_images(&self, relative_paths: &[String]) -> Result<()> {
println!("删除多个图片文件: {} 个", relative_paths.len());
for path in relative_paths {
let file_path = self.app_data_dir.join(path);
if file_path.exists() {
fs::remove_file(&file_path)
.map_err(|e| AppError::file_system(format!("删除图片文件失败: {}", e)))?;
}
}
Ok(())
}
/// 清理孤立的图片文件
pub async fn cleanup_orphaned_images(&self, database: &crate::database::Database) -> Result<Vec<String>> {
println!("开始清理孤立图片文件");
if !async_fs::try_exists(&self.images_dir).await
.map_err(|e| AppError::file_system(format!("检查图片目录存在性失败: {}", e)))? {
println!("图片目录不存在,跳过清理");
return Ok(vec![]);
}
let mut cleaned_files = Vec::new();
// 1. 收集所有物理图片文件
let mut all_physical_files = std::collections::HashSet::new();
let mut entries = async_fs::read_dir(&self.images_dir).await
.map_err(|e| AppError::file_system(format!("读取图片目录失败: {}", e)))?;
while let Some(entry) = entries.next_entry().await
.map_err(|e| AppError::file_system(format!("读取目录条目失败: {}", e)))? {
let path = entry.path();
if path.is_file() {
if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
// 构建相对路径(相对于app_data_dir)
let relative_path = format!("images/{}", filename);
all_physical_files.insert(relative_path);
}
}
}
println!("发现 {} 个物理图片文件", all_physical_files.len());
// 2. 从数据库获取所有被引用的图片路径
let referenced_images = self.get_referenced_images(database)?;
println!("数据库中引用了 {} 个图片文件", referenced_images.len());
// 3. 找出孤立的图片文件
for physical_file in &all_physical_files {
if !referenced_images.contains(physical_file) {
println!("发现孤立图片文件: {}", physical_file);
// 删除孤立文件
let full_path = self.app_data_dir.join(physical_file);
match async_fs::remove_file(&full_path).await {
Ok(()) => {
cleaned_files.push(physical_file.clone());
println!("已删除孤立图片: {}", physical_file);
}
Err(e) => {
println!("删除孤立图片失败: {} - {}", physical_file, e);
}
}
}
}
// 4. 清理空的子目录
self.cleanup_empty_directories().await?;
println!("清理完成,删除了 {} 个孤立图片文件", cleaned_files.len());
Ok(cleaned_files)
}
/// 从数据库获取所有被引用的图片路径
fn get_referenced_images(&self, database: &crate::database::Database) -> Result<std::collections::HashSet<String>> {
use rusqlite::params;
let conn = database.conn().lock().map_err(|_| AppError::database("获取数据库连接失败".to_string()))?;
let mut referenced_images = std::collections::HashSet::new();
// 查询所有错题的图片路径
let mut stmt = conn.prepare("SELECT question_images, analysis_images FROM mistakes")
.map_err(|e| AppError::database(format!("准备查询语句失败: {}", e)))?;
let rows = stmt.query_map(params![], |row| {
let question_images: String = row.get(0)?;
let analysis_images: String = row.get(1)?;
Ok((question_images, analysis_images))
}).map_err(|e| AppError::database(format!("执行查询失败: {}", e)))?;
for row_result in rows {
let (question_images_json, analysis_images_json) = row_result
.map_err(|e| AppError::database(format!("读取行数据失败: {}", e)))?;
// 解析JSON数组 - 改进错误处理以防止数据丢失
match serde_json::from_str::<Vec<String>>(&question_images_json) {
Ok(question_paths) => {
for path in question_paths {
referenced_images.insert(path);
}
}
Err(e) => {
println!("警告: 解析question_images JSON失败: {} - 数据: {}", e, question_images_json);
// 不忽略错误,中止清理过程以防止数据丢失
return Err(AppError::validation(format!(
"解析错题图片路径JSON失败,中止孤立图片清理以防止数据丢失: {}", e
)));
}
}
match serde_json::from_str::<Vec<String>>(&analysis_images_json) {
Ok(analysis_paths) => {
for path in analysis_paths {
referenced_images.insert(path);
}
}
Err(e) => {
println!("警告: 解析analysis_images JSON失败: {} - 数据: {}", e, analysis_images_json);
// 不忽略错误,中止清理过程以防止数据丢失
return Err(AppError::validation(format!(
"解析分析图片路径JSON失败,中止孤立图片清理以防止数据丢失: {}", e
)));
}
}
}
Ok(referenced_images)
}
/// 清理空的子目录
async fn cleanup_empty_directories(&self) -> Result<()> {
println!("清理空目录");
let mut entries = async_fs::read_dir(&self.images_dir).await
.map_err(|e| AppError::file_system(format!("读取图片目录失败: {}", e)))?;
let mut directories_to_check = Vec::new();
while let Some(entry) = entries.next_entry().await
.map_err(|e| AppError::file_system(format!("读取目录条目失败: {}", e)))? {
let path = entry.path();
if path.is_dir() {
directories_to_check.push(path);
}
}
// 检查并删除空目录
for dir_path in directories_to_check {
match self.is_directory_empty(&dir_path).await {
Ok(true) => {
if let Err(e) = async_fs::remove_dir(&dir_path).await {
println!("删除空目录失败: {:?} - {}", dir_path, e);
} else {
println!("已删除空目录: {:?}", dir_path);
}
}
Ok(false) => {
// 目录不为空,跳过
}
Err(e) => {
println!("检查目录是否为空失败: {:?} - {}", dir_path, e);
}
}
}
Ok(())
}
/// 检查目录是否为空
async fn is_directory_empty(&self, dir_path: &Path) -> Result<bool> {
let mut entries = async_fs::read_dir(dir_path).await
.map_err(|e| AppError::file_system(format!("读取目录失败: {}", e)))?;
// 如果能读取到第一个条目,说明目录不为空
match entries.next_entry().await {
Ok(Some(_)) => Ok(false), // 有条目,不为空
Ok(None) => Ok(true), // 没有条目,为空
Err(e) => Err(AppError::file_system(format!("检查目录内容失败: {}", e)))
}
}
/// 获取图片文件统计信息
pub async fn get_image_statistics(&self) -> Result<ImageStatistics> {
let mut stats = ImageStatistics {
total_files: 0,
total_size_bytes: 0,
file_types: std::collections::HashMap::new(),
oldest_file: None,
newest_file: None,
};
if !async_fs::try_exists(&self.images_dir).await
.map_err(|e| AppError::file_system(format!("检查图片目录存在性失败: {}", e)))? {
return Ok(stats);
}
let mut entries = async_fs::read_dir(&self.images_dir).await
.map_err(|e| AppError::file_system(format!("读取图片目录失败: {}", e)))?;
while let Some(entry) = entries.next_entry().await
.map_err(|e| AppError::file_system(format!("读取目录条目失败: {}", e)))? {
let path = entry.path();
if path.is_file() {
// 获取文件元数据
let metadata = async_fs::metadata(&path).await
.map_err(|e| AppError::file_system(format!("获取文件元数据失败: {}", e)))?;
stats.total_files += 1;
stats.total_size_bytes += metadata.len();
// 统计文件类型
if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) {
*stats.file_types.entry(extension.to_lowercase()).or_insert(0) += 1;
}
// 获取修改时间
if let Ok(modified) = metadata.modified() {
let modified_timestamp = modified.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default().as_secs();
if stats.oldest_file.is_none() || modified_timestamp < stats.oldest_file.unwrap() {
stats.oldest_file = Some(modified_timestamp);
}
if stats.newest_file.is_none() || modified_timestamp > stats.newest_file.unwrap() {
stats.newest_file = Some(modified_timestamp);
}
}
}
}
Ok(stats)
}
/// 验证图片格式 (基于路径的存根)
pub fn validate_image_format_from_path_stub(&self, relative_path: &str) -> Result<bool> {
println!("验证图片格式 (存根): {}", relative_path);
// TODO: 实现基于文件路径的实际验证逻辑
Ok(true)
}
// 第一个 extract_extension_from_base64 (占位符) 已被移除,保留下面的实际实现
/// 保存图片文件(从字节数据)
pub fn save_image_from_bytes(&self, image_data: &[u8], file_extension: &str) -> Result<String> {
// 确保图片目录存在
fs::create_dir_all(&self.images_dir)
.map_err(|e| AppError::file_system(format!("创建图片目录失败: {}", e)))?;
// 生成唯一文件名
let file_id = Uuid::new_v4().to_string();
let filename = format!("{}.{}", file_id, file_extension);
let file_path = self.images_dir.join(&filename);
// 写入文件
let mut file = fs::File::create(&file_path)
.map_err(|e| AppError::file_system(format!("创建图片文件失败: {}", e)))?;
file.write_all(image_data)
.map_err(|e| AppError::file_system(format!("写入图片文件失败: {}", e)))?;
// 返回相对路径
Ok(format!("images/{}", filename))
}
/// 获取图片文件的绝对路径
pub fn get_image_absolute_path(&self, relative_path: &str) -> PathBuf {
self.app_data_dir.join(relative_path)
}
/// 检查图片文件是否存在
pub fn image_exists(&self, relative_path: &str) -> bool {
let file_path = self.app_data_dir.join(relative_path);
file_path.exists()
}
/// 获取图片文件大小
pub fn get_image_size(&self, relative_path: &str) -> Result<u64> {
let file_path = self.app_data_dir.join(relative_path);
let metadata = fs::metadata(&file_path)
.map_err(|e| AppError::file_system(format!("获取文件元数据失败: {}", e)))?;
Ok(metadata.len())
}
/// 验证图片格式 (基于Base64)
pub fn validate_image_format_from_base64(&self, base64_data: &str) -> Result<String> {
// 解析MIME类型
let mime_type = self.extract_mime_type_from_base64(base64_data)?;
// 支持的图片格式
let supported_formats = vec![
"image/jpeg", "image/jpg", "image/png", "image/gif",
"image/webp", "image/bmp", "image/tiff"
];
if !supported_formats.contains(&mime_type.as_str()) {
return Err(AppError::validation(format!(
"不支持的图片格式: {},支持的格式: {}",
mime_type,
supported_formats.join(", ")
)));
}
// 尝试解码base64以验证数据完整性
let base64_start = if base64_data.starts_with("data:") {
base64_data.find("base64,")
.ok_or_else(|| AppError::validation("无效的base64数据格式"))?
+ 7
} else {
0
};
let base64_content = &base64_data[base64_start..];
let image_bytes = general_purpose::STANDARD
.decode(base64_content)
.map_err(|e| AppError::validation(format!("base64解码失败,数据可能损坏: {}", e)))?;
// 基本的文件大小检查
if image_bytes.is_empty() {
return Err(AppError::validation("图片数据为空"));
}
if image_bytes.len() > 50 * 1024 * 1024 { // 50MB限制
return Err(AppError::validation("图片文件过大,超过50MB限制"));
}
println!("图片格式验证通过: {} ({} bytes)", mime_type, image_bytes.len());
Ok(mime_type)
}
/// 从base64数据中提取文件扩展名
pub fn extract_extension_from_base64(&self, base64_data: &str) -> Result<String> {
let mime_type = self.extract_mime_type_from_base64(base64_data)?;
let extension = match mime_type.as_str() {
"image/jpeg" | "image/jpg" => "jpg",
"image/png" => "png",
"image/gif" => "gif",
"image/webp" => "webp",
"image/bmp" => "bmp",
"image/tiff" => "tiff",
_ => return Err(AppError::validation(format!("无法确定文件扩展名,未知MIME类型: {}", mime_type)))
};
Ok(extension.to_string())
}
/// 从base64 Data URL中提取MIME类型
fn extract_mime_type_from_base64(&self, base64_data: &str) -> Result<String> {
if base64_data.starts_with("data:") {
if let Some(semicolon_pos) = base64_data.find(';') {
let mime_type = &base64_data[5..semicolon_pos]; // 跳过 "data:"
if mime_type.starts_with("image/") {
return Ok(mime_type.to_string());
}
}
return Err(AppError::validation("无效的Data URL格式"));
} else {
// 如果不是Data URL,尝试从文件头部识别
self.detect_image_type_from_content(base64_data)
}
}
/// 从文件内容检测图片类型
fn detect_image_type_from_content(&self, base64_data: &str) -> Result<String> {
let image_bytes = general_purpose::STANDARD
.decode(base64_data)
.map_err(|e| AppError::validation(format!("base64解码失败: {}", e)))?;
if image_bytes.len() < 8 {
return Err(AppError::validation("图片数据太短,无法识别格式"));
}
// 检查文件头部魔术字节
match &image_bytes[0..8] {
[0xFF, 0xD8, 0xFF, ..] => Ok("image/jpeg".to_string()),
[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] => Ok("image/png".to_string()),
[0x47, 0x49, 0x46, 0x38, 0x37, 0x61, ..] | [0x47, 0x49, 0x46, 0x38, 0x39, 0x61, ..] => Ok("image/gif".to_string()),
[0x52, 0x49, 0x46, 0x46, _, _, _, _] if &image_bytes[8..12] == b"WEBP" => Ok("image/webp".to_string()),
[0x42, 0x4D, ..] => Ok("image/bmp".to_string()),
_ => Err(AppError::validation("无法识别图片格式"))
}
}
/// 创建完整的系统备份
pub fn create_backup(&self) -> Result<PathBuf> {
let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
let backup_dir = self.app_data_dir.join("backups");
fs::create_dir_all(&backup_dir)
.map_err(|e| AppError::file_system(format!("创建备份目录失败: {}", e)))?;
let backup_file = backup_dir.join(format!("backup_{}.zip", timestamp));
println!("创建系统备份: {:?}", backup_file);
// 实现真正的备份逻辑
use std::io::Write;
let file = fs::File::create(&backup_file)
.map_err(|e| AppError::file_system(format!("创建备份文件失败: {}", e)))?;
let mut zip = zip::ZipWriter::new(file);
let options = zip::write::FileOptions::default()
.compression_method(zip::CompressionMethod::Deflated)
.unix_permissions(0o755);
// 备份数据库文件
let db_path = self.get_database_path();
if db_path.exists() {
zip.start_file("mistakes.db", options)?;
let db_content = fs::read(&db_path)
.map_err(|e| AppError::file_system(format!("读取数据库文件失败: {}", e)))?;
zip.write_all(&db_content)?;
println!("已备份数据库文件: {} bytes", db_content.len());
}
// 备份图片目录
if self.images_dir.exists() {
self.add_directory_to_zip(&mut zip, &self.images_dir, "images", options)?;
}
// 备份配置文件(如果存在)
let config_file = self.app_data_dir.join("config.json");
if config_file.exists() {
zip.start_file("config.json", options)?;
let config_content = fs::read(&config_file)
.map_err(|e| AppError::file_system(format!("读取配置文件失败: {}", e)))?;
zip.write_all(&config_content)?;
println!("已备份配置文件: {} bytes", config_content.len());
}
zip.finish().map_err(|e| AppError::file_system(format!("完成备份文件失败: {}", e)))?;
let backup_size = fs::metadata(&backup_file)
.map_err(|e| AppError::file_system(format!("获取备份文件大小失败: {}", e)))?
.len();
println!("备份创建成功: {:?} ({} bytes)", backup_file, backup_size);
Ok(backup_file)
}
/// 将目录添加到ZIP文件中
fn add_directory_to_zip<W: Write + std::io::Seek>(
&self,
zip: &mut zip::ZipWriter<W>,
dir_path: &Path,
prefix: &str,
options: zip::write::FileOptions
) -> Result<()> {
let entries = fs::read_dir(dir_path)
.map_err(|e| AppError::file_system(format!("读取目录失败: {}", e)))?;
for entry in entries {
let entry = entry.map_err(|e| AppError::file_system(format!("读取目录条目失败: {}", e)))?;
let path = entry.path();
let name = entry.file_name().to_string_lossy().to_string(); // Convert Cow<str> to String
let zip_path = format!("{}/{}", prefix, name);
if path.is_file() {
zip.start_file(&zip_path, options)?;
let content = fs::read(&path)
.map_err(|e| AppError::file_system(format!("读取文件失败: {}", e)))?;
zip.write_all(&content)?;
println!("已添加文件到备份: {} ({} bytes)", zip_path, content.len());
} else if path.is_dir() {
// 递归处理子目录
self.add_directory_to_zip(zip, &path, &zip_path, options)?;
}
}
Ok(())
}
/// 获取应用数据目录路径
pub fn get_app_data_dir(&self) -> &Path {
&self.app_data_dir
}
}
| 22,935 | file_manager | rs | en | rust | code | {"qsc_code_num_words": 2393, "qsc_code_num_chars": 22935.0, "qsc_code_mean_word_length": 4.78019223, "qsc_code_frac_words_unique": 0.16631843, "qsc_code_frac_chars_top_2grams": 0.01503628, "qsc_code_frac_chars_top_3grams": 0.02264184, "qsc_code_frac_chars_top_4grams": 0.04851823, "qsc_code_frac_chars_dupe_5grams": 0.40195821, "qsc_code_frac_chars_dupe_6grams": 0.3569368, "qsc_code_frac_chars_dupe_7grams": 0.32476615, "qsc_code_frac_chars_dupe_8grams": 0.29539295, "qsc_code_frac_chars_dupe_9grams": 0.25255704, "qsc_code_frac_chars_dupe_10grams": 0.18681703, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01595434, "qsc_code_frac_chars_whitespace": 0.32770874, "qsc_code_size_file_byte": 22935.0, "qsc_code_num_lines": 615.0, "qsc_code_num_chars_line_max": 128.0, "qsc_code_num_chars_line_mean": 37.29268293, "qsc_code_frac_chars_alphabet": 0.72592256, "qsc_code_frac_chars_comments": 0.05406584, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.20229885, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.07513252, "qsc_code_frac_chars_long_word_length": 0.0028578, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00534685, "qsc_code_frac_lines_prompt_comments": 0.00162602, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
000haoji/deep-student | src-tauri/src/llm_manager.rs | use crate::models::{ChatMessage, AppError, StandardModel1Output, StandardModel2Output, ModelAssignments, StreamChunk};
use crate::database::Database;
use crate::file_manager::FileManager;
use crate::crypto::{CryptoService, EncryptedData};
use crate::gemini_adapter;
use reqwest::{Client, ClientBuilder, header::HeaderMap};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::Arc;
use url::Url;
use serde::{Deserialize, Serialize};
use futures_util::StreamExt;
use tauri::{Window, Emitter};
use base64::{engine::general_purpose, Engine as _};
type Result<T> = std::result::Result<T, AppError>;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiConfig {
pub id: String,
pub name: String,
pub api_key: String,
pub base_url: String,
pub model: String,
pub is_multimodal: bool,
pub is_reasoning: bool,
pub enabled: bool,
#[serde(default = "default_model_adapter")]
pub model_adapter: String, // 新增:模型适配器类型
#[serde(default = "default_max_output_tokens")]
pub max_output_tokens: u32, // 新增:最大输出Token数
#[serde(default = "default_temperature")]
pub temperature: f32, // 新增:温度参数
}
// 默认值函数
fn default_model_adapter() -> String {
"general".to_string()
}
fn default_max_output_tokens() -> u32 {
8192
}
fn default_temperature() -> f32 {
0.7
}
pub struct LLMManager {
client: Client,
db: Arc<Database>,
file_manager: Arc<FileManager>,
crypto_service: CryptoService,
}
impl LLMManager {
pub fn new(db: Arc<Database>, file_manager: Arc<FileManager>) -> Self {
// 创建HTTP客户端,使用渐进式回退策略确保始终有合理的配置
let client = Self::create_http_client_with_fallback();
let app_data_dir_path = file_manager.get_app_data_dir(); // Assuming this returns &Path
let crypto_service = CryptoService::new(&app_data_dir_path.to_path_buf())
.expect("无法初始化加密服务");
Self {
client,
db,
file_manager,
crypto_service,
}
}
/// 创建HTTP客户端,使用渐进式回退策略确保始终有合理的配置
fn create_http_client_with_fallback() -> Client {
// 创建默认请求头,显式禁用压缩,防止后端收到 gzip/deflate 数据导致乱码
let mut headers = HeaderMap::new();
headers.insert("Accept-Encoding", "identity".parse().unwrap());
// 尝试1: 完整配置的客户端(推荐配置)
if let Ok(client) = ClientBuilder::new()
.timeout(std::time::Duration::from_secs(300)) // 全局超时300秒(流式请求需要更长时间)
.connect_timeout(std::time::Duration::from_secs(30)) // 连接超时30秒
.danger_accept_invalid_certs(false) // 保持SSL验证
.use_rustls_tls() // 使用rustls而不是系统TLS
.default_headers(headers.clone())
.build()
{
println!("HTTP客户端创建成功: 完整配置(超时120s,连接15s,rustls TLS)");
return client;
}
// 尝试2: 简化TLS配置的客户端
if let Ok(client) = ClientBuilder::new()
.timeout(std::time::Duration::from_secs(300))
.connect_timeout(std::time::Duration::from_secs(30))
.danger_accept_invalid_certs(false)
.default_headers(headers.clone())
.build()
{
println!("HTTP客户端创建成功: 简化TLS配置(超时120s,连接15s,系统TLS)");
return client;
}
// 尝试3: 仅超时配置的客户端
if let Ok(client) = ClientBuilder::new()
.timeout(std::time::Duration::from_secs(300))
.default_headers(headers.clone())
.build()
{
println!("HTTP客户端创建成功: 仅超时配置(超时120s)");
return client;
}
// 尝试4: 最小配置的客户端(保证基本超时)
if let Ok(client) = ClientBuilder::new()
.timeout(std::time::Duration::from_secs(180)) // 最少180秒超时
.default_headers(headers.clone())
.build()
{
println!("HTTP客户端创建成功: 最小配置(超时60s)");
return client;
}
// 最后回退: 默认客户端
println!("警告: 所有配置均失败,使用默认HTTP客户端(无超时配置)");
println!("这可能导致网络请求挂起,建议检查系统网络和TLS配置");
Client::new()
}
/// 检测Base64编码图像的真实格式
fn detect_image_format_from_base64(base64_data: &str) -> &'static str {
// 解码Base64获取前几个字节来判断格式
if let Ok(decoded) = general_purpose::STANDARD.decode(base64_data.get(..100).unwrap_or(base64_data)) {
Self::detect_image_format_from_bytes(&decoded)
} else {
"jpeg" // 默认格式
}
}
/// 根据图像字节数据检测格式
fn detect_image_format_from_bytes(image_data: &[u8]) -> &'static str {
if image_data.len() < 4 {
return "jpeg"; // 默认格式
}
// JPEG: FF D8 FF
if image_data.starts_with(&[0xFF, 0xD8, 0xFF]) {
"jpeg"
}
// PNG: 89 50 4E 47 0D 0A 1A 0A
else if image_data.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) {
"png"
}
// GIF: 47 49 46 38 (GIF8)
else if image_data.starts_with(&[0x47, 0x49, 0x46, 0x38]) {
"gif"
}
// WebP: 52 49 46 46 ... 57 45 42 50 (RIFF...WEBP)
else if image_data.len() >= 12 &&
image_data.starts_with(&[0x52, 0x49, 0x46, 0x46]) &&
&image_data[8..12] == &[0x57, 0x45, 0x42, 0x50] {
"webp"
}
// BMP: 42 4D (BM)
else if image_data.starts_with(&[0x42, 0x4D]) {
"bmp"
}
else {
"jpeg" // 默认格式
}
}
// 获取API配置(公开方法)
pub async fn get_api_configs(&self) -> Result<Vec<ApiConfig>> {
let config_str = self.db.get_setting("api_configs")
.map_err(|e| AppError::database(format!("获取API配置失败: {}", e)))?
.unwrap_or_else(|| "[]".to_string());
// 尝试反序列化为新格式
match serde_json::from_str::<Vec<ApiConfig>>(&config_str) {
Ok(mut configs) => {
// 解密API密钥
for config in &mut configs {
config.api_key = self.decrypt_api_key_if_needed(&config.api_key)?;
}
Ok(configs)
},
Err(_) => {
// 如果失败,尝试作为旧格式反序列化并迁移
println!("检测到旧版API配置格式,正在迁移...");
self.migrate_api_configs(&config_str).await
}
}
}
// 迁移旧版API配置到新格式
async fn migrate_api_configs(&self, old_config_str: &str) -> Result<Vec<ApiConfig>> {
// 尝试多种旧格式的反序列化
// 最新的旧格式(包含 is_reasoning 但没有 model_adapter)
#[derive(serde::Deserialize)]
struct OldApiConfigV2 {
id: String,
name: String,
api_key: String,
base_url: String,
model: String,
is_multimodal: bool,
is_reasoning: bool,
enabled: bool,
}
// 更旧的格式(没有 is_reasoning)
#[derive(serde::Deserialize)]
struct OldApiConfigV1 {
id: String,
name: String,
api_key: String,
base_url: String,
model: String,
is_multimodal: bool,
enabled: bool,
}
// 首先尝试解析为 V2 格式
if let Ok(old_configs) = serde_json::from_str::<Vec<OldApiConfigV2>>(old_config_str) {
let new_configs: Vec<ApiConfig> = old_configs.into_iter().map(|old| {
// 根据模型名称智能推断适配器类型
let model_adapter = if old.model.to_lowercase().contains("deepseek") &&
old.model.to_lowercase().contains("r1") {
"deepseek-r1".to_string()
} else {
"general".to_string()
};
ApiConfig {
id: old.id,
name: old.name,
api_key: old.api_key,
base_url: old.base_url,
model: old.model,
is_multimodal: old.is_multimodal,
is_reasoning: old.is_reasoning,
enabled: old.enabled,
model_adapter,
max_output_tokens: default_max_output_tokens(),
temperature: default_temperature(),
}
}).collect();
self.save_api_configurations(&new_configs).await?;
println!("API配置迁移完成(V2->V3),添加了 {} 个配置的 model_adapter 字段", new_configs.len());
return Ok(new_configs);
}
// 如果 V2 失败,尝试解析为 V1 格式
let old_configs: Vec<OldApiConfigV1> = serde_json::from_str(old_config_str)
.map_err(|e| AppError::configuration(format!("解析旧版API配置失败: {}", e)))?;
let new_configs: Vec<ApiConfig> = old_configs.into_iter().map(|old| {
// 根据模型名称智能推断适配器类型和推理能力
let (is_reasoning, model_adapter) = if old.model.to_lowercase().contains("deepseek") &&
old.model.to_lowercase().contains("r1") {
(true, "deepseek-r1".to_string())
} else if old.model.to_lowercase().contains("o1") {
(true, "general".to_string())
} else {
(false, "general".to_string())
};
ApiConfig {
id: old.id,
name: old.name,
api_key: old.api_key,
base_url: old.base_url,
model: old.model,
is_multimodal: old.is_multimodal,
is_reasoning,
enabled: old.enabled,
model_adapter,
max_output_tokens: default_max_output_tokens(),
temperature: default_temperature(),
}
}).collect();
// 保存迁移后的配置
self.save_api_configurations(&new_configs).await?;
println!("API配置迁移完成(V1->V3),添加了 {} 个配置的 is_reasoning 和 model_adapter 字段", new_configs.len());
Ok(new_configs)
}
// 获取第一模型配置
async fn get_model1_config(&self) -> Result<ApiConfig> {
let assignments = self.get_model_assignments().await?;
let model1_id = assignments.model1_config_id
.ok_or_else(|| AppError::configuration("第一模型未配置"))?;
println!("查找第一模型配置,ID: {}", model1_id);
let configs = self.get_api_configs().await?;
println!("可用的API配置数量: {}", configs.len());
for (i, config) in configs.iter().enumerate() {
println!("配置 {}: ID={}, 模型={}, 多模态={}, 启用={}",
i, config.id, config.model, config.is_multimodal, config.enabled);
}
let config = configs.into_iter()
.find(|c| c.id == model1_id && c.is_multimodal && c.enabled)
.ok_or_else(|| AppError::configuration("找不到有效的第一模型配置"))?;
println!("找到第一模型配置: 模型={}, API地址={}", config.model, config.base_url);
Ok(config)
}
// 获取第二模型配置(公开方法,供 AnalysisService 使用)
pub async fn get_model2_config(&self) -> Result<ApiConfig> {
let assignments = self.get_model_assignments().await?;
let model2_id = assignments.model2_config_id
.ok_or_else(|| AppError::configuration("第二模型未配置"))?;
let configs = self.get_api_configs().await?;
let config = configs.into_iter()
.find(|c| c.id == model2_id && c.enabled)
.ok_or_else(|| AppError::configuration("找不到有效的第二模型配置"))?;
Ok(config)
}
// 获取ANKI制卡模型配置
async fn get_anki_model_config(&self) -> Result<ApiConfig> {
let assignments = self.get_model_assignments().await?;
let anki_model_id = assignments.anki_card_model_config_id
.ok_or_else(|| AppError::configuration("ANKI制卡模型未配置"))?;
let configs = self.get_api_configs().await?;
let config = configs.into_iter()
.find(|c| c.id == anki_model_id && c.enabled)
.ok_or_else(|| AppError::configuration("找不到有效的ANKI制卡模型配置"))?;
println!("找到ANKI制卡模型配置: 模型={}, API地址={}", config.model, config.base_url);
Ok(config)
}
// 获取模型分配配置
pub async fn get_model_assignments(&self) -> Result<ModelAssignments> {
let assignments_str = self.db.get_setting("model_assignments")
.map_err(|e| AppError::database(format!("获取模型分配配置失败: {}", e)))?
.unwrap_or_else(|| r#"{"model1_config_id": null, "model2_config_id": null, "review_analysis_model_config_id": null, "anki_card_model_config_id": null}"#.to_string());
let assignments: ModelAssignments = serde_json::from_str(&assignments_str)
.map_err(|e| AppError::configuration(format!("解析模型分配配置失败: {}", e)))?;
Ok(assignments)
}
// 保存模型分配配置
pub async fn save_model_assignments(&self, assignments: &ModelAssignments) -> Result<()> {
let assignments_str = serde_json::to_string(assignments)
.map_err(|e| AppError::configuration(format!("序列化模型分配配置失败: {}", e)))?;
self.db.save_setting("model_assignments", &assignments_str)
.map_err(|e| AppError::database(format!("保存模型分配配置失败: {}", e)))?;
Ok(())
}
// 保存API配置
pub async fn save_api_configurations(&self, configs: &[ApiConfig]) -> Result<()> {
// 创建配置副本并加密API密钥
let mut encrypted_configs = configs.to_vec();
for config in &mut encrypted_configs {
config.api_key = self.encrypt_api_key(&config.api_key)?;
}
let configs_str = serde_json::to_string(&encrypted_configs)
.map_err(|e| AppError::configuration(format!("序列化API配置失败: {}", e)))?;
self.db.save_setting("api_configs", &configs_str)
.map_err(|e| AppError::database(format!("保存API配置失败: {}", e)))?;
Ok(())
}
// 加密API密钥
fn encrypt_api_key(&self, api_key: &str) -> Result<String> {
// 如果已经是加密格式,直接返回
if CryptoService::is_encrypted_format(api_key) {
return Ok(api_key.to_string());
}
let encrypted_data = self.crypto_service.encrypt_api_key(api_key)
.map_err(|e| AppError::configuration(format!("加密API密钥失败: {}", e)))?;
serde_json::to_string(&encrypted_data)
.map_err(|e| AppError::configuration(format!("序列化加密数据失败: {}", e)))
}
// 解密API密钥(如果需要)
fn decrypt_api_key_if_needed(&self, api_key: &str) -> Result<String> {
// 检查是否为加密格式
if CryptoService::is_encrypted_format(api_key) {
let encrypted_data: EncryptedData = serde_json::from_str(api_key)
.map_err(|e| AppError::configuration(format!("解析加密数据失败: {}", e)))?;
self.crypto_service.decrypt_api_key(&encrypted_data)
.map_err(|e| AppError::configuration(format!("解密API密钥失败: {}", e)))
} else {
// 明文格式,迁移到加密格式
println!("检测到明文API密钥,将在下次保存时自动加密");
Ok(api_key.to_string())
}
}
// 统一AI接口层 - 模型一(OCR + 分类)
pub async fn call_unified_model_1(
&self,
image_paths: Vec<String>,
user_question: &str,
subject: &str,
task_context: Option<&str>,
) -> Result<StandardModel1Output> {
println!("调用统一模型一接口: 图片数量={}, 科目={}", image_paths.len(), subject);
// 获取模型配置
let config = self.get_model1_config().await?;
// *** 新增的适配器路由逻辑 ***
if config.model_adapter == "google" {
// 读取图片文件并转换为Base64
let mut images_base64 = Vec::new();
for path in &image_paths {
let base64_content = self.file_manager.read_file_as_base64(path)?;
images_base64.push(base64_content);
}
// 构建包含图片的消息
let mut messages = Vec::new();
let full_prompt = if let Some(context) = task_context {
format!("科目: {}\n任务上下文: {}\n用户问题: {}\n\n请分析图片中的题目内容,提取文字内容,确定题目类型,并生成相关标签。返回JSON格式:{{\"ocr_text\": \"题目文字\", \"tags\": [\"标签1\", \"标签2\"], \"mistake_type\": \"题目类型\"}}", subject, context, user_question)
} else {
format!("科目: {}\n用户问题: {}\n\n请分析图片中的题目内容,提取文字内容,确定题目类型,并生成相关标签。返回JSON格式:{{\"ocr_text\": \"题目文字\", \"tags\": [\"标签1\", \"标签2\"], \"mistake_type\": \"题目类型\"}}", subject, user_question)
};
let mut message = ChatMessage {
role: "user".to_string(),
content: full_prompt,
timestamp: chrono::Utc::now(),
thinking_content: None,
rag_sources: None,
image_paths: None,
image_base64: Some(images_base64),
};
messages.push(message);
// 调用 Gemini 适配器(非流式)
let gemini_result = gemini_adapter::non_stream_chat(
&self.client,
&config,
&messages,
).await?;
// 解析 Gemini 响应为 StandardModel1Output 格式
let content_str = &gemini_result.assistant_message;
println!("Gemini 模型一原始响应内容: {}", content_str);
println!("Gemini 响应长度: {} 字符", content_str.len());
// 添加Gemini响应分析
if content_str.len() <= 10 {
println!("⚠️ 警告:Gemini响应内容过短,可能存在以下问题:");
println!(" 1. API 密钥配置错误");
println!(" 2. 模型配置问题");
println!(" 3. 请求内容触发了安全限制");
println!(" 4. 图片格式或内容问题");
}
let parsed_json = parse_model1_json_response(content_str)?;
return Ok(StandardModel1Output {
ocr_text: parsed_json["ocr_text"].as_str().unwrap_or("").to_string(),
tags: parsed_json["tags"].as_array()
.map(|arr| arr.iter().filter_map(|v| v.as_str().map(|s| s.to_string())).collect())
.unwrap_or_default(),
mistake_type: parsed_json["mistake_type"].as_str().unwrap_or("").to_string(),
raw_response: Some(content_str.to_string()),
});
}
// *** 适配器逻辑结束 ***
// 读取图片文件并转换为Base64
let mut images_base64 = Vec::new();
for path in &image_paths {
let base64_content = self.file_manager.read_file_as_base64(path)?;
images_base64.push(base64_content);
}
// 获取科目专用的Prompt
let subject_prompt = self.get_subject_prompt(subject, "model1");
let full_prompt = if let Some(context) = task_context {
format!("{}\n\n任务上下文: {}\n\n用户问题: {}", subject_prompt, context, user_question)
} else {
format!("{}\n\n用户问题: {}", subject_prompt, user_question)
};
// 强化的JSON指令 - 明确要求纯净JSON输出
let json_instruction = if config.model.starts_with("gpt-") {
// GPT模型支持response_format,但仍需明确指令
"你必须严格返回JSON格式的数据,不要添加任何解释、前缀、后缀或markdown标记。\n\n请分析图片中的题目内容,返回以下格式的JSON:\n{\n \"ocr_text\": \"题目的完整文字内容\",\n \"tags\": [\"相关知识点标签\"],\n \"mistake_type\": \"题目类型分类\"\n}\n\n要求:\n1. 只返回JSON数据,不要任何其他文字\n2. 字符串值必须用双引号包围\n3. 特殊字符必须正确转义"
} else {
// 其他模型需要更严格的指令
"**重要:你必须只返回纯净的JSON数据,不要添加任何解释文字、markdown标记或其他内容。**\n\n请分析图片中的题目内容,严格按照以下JSON格式返回:\n\n{\n \"ocr_text\": \"题目的完整文字内容\",\n \"tags\": [\"相关知识点标签1\", \"相关知识点标签2\"],\n \"mistake_type\": \"题目类型分类\"\n}\n\n**格式要求(必须严格遵守):**\n1. 响应必须以 { 开始,以 } 结束\n2. 不要添加 ```json 或任何markdown标记\n3. 不要添加任何解释文字或说明\n4. 字符串值必须用双引号包围\n5. 如果文字中包含引号,使用 \\\" 转义\n6. 如果文字中包含反斜杠,使用 \\\\\\ 转义\n7. 换行符使用 \\n 表示\n8. 确保JSON语法完全正确\n\n**示例输出:**\n{\"ocr_text\": \"求解方程 x² + 2x - 3 = 0\", \"tags\": [\"二次方程\", \"代数\"], \"mistake_type\": \"计算题\"}"
};
let image_context = if images_base64.len() > 1 {
format!("我将为您提供{}张图片,它们可能是同一道题目的不同部分或多道相关题目。请仔细分析所有图片内容,综合提取完整的题目信息。\n\n", images_base64.len())
} else {
"我将为您提供一张图片,请分析其中的题目内容。\n\n".to_string()
};
let mut request_content_parts = vec![
json!({
"type": "text",
"text": format!("{}{}\n\n请分析这道题目,提取文字内容,确定题目类型,并生成相关标签。\n\n{}", image_context, full_prompt, json_instruction)
})
];
// 添加图片
for image_base64 in &images_base64 {
let image_format = Self::detect_image_format_from_base64(image_base64);
println!("🖼️ 模型一检测到图像格式: {}", image_format);
request_content_parts.push(json!({
"type": "image_url",
"image_url": {
"url": format!("data:image/{};base64,{}", image_format, image_base64)
}
}));
}
let mut request_body = json!({
"model": config.model,
"messages": [
{
"role": "user",
"content": request_content_parts
}
],
"max_tokens": config.max_output_tokens,
"stream": false, // 第一模型不使用流式,因为需要结构化JSON输出
"temperature": config.temperature,
"top_p": 0.9,
"frequency_penalty": 0.0,
"presence_penalty": 0.0
});
println!("模型一使用 max_tokens: {} (模型: {})", config.max_output_tokens, config.model);
// 调试:打印请求体(不包含图片内容)
let debug_body = {
let mut debug = request_body.clone();
if let Some(messages) = debug["messages"].as_array_mut() {
for message in messages {
if let Some(content) = message["content"].as_array_mut() {
for part in content {
if part["type"] == "image_url" {
part["image_url"]["url"] = json!("data:image/*;base64,[图片数据已隐藏]");
}
}
}
}
}
debug
};
println!("📤 请求体: {}", serde_json::to_string_pretty(&debug_body).unwrap_or_default());
// 只有支持JSON模式的模型才添加response_format
// 目前已知支持的模型:gpt-3.5-turbo, gpt-4, gpt-4-turbo等
if config.model.starts_with("gpt-") {
request_body["response_format"] = json!({"type": "json_object"});
}
// 发送请求
println!("发送请求到模型一: {}/chat/completions", config.base_url);
let mut request_builder = self.client
.post(&format!("{}/chat/completions", config.base_url))
.header("Authorization", format!("Bearer {}", config.api_key))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/plain, */*")
.header("Accept-Encoding", "identity") // 禁用压缩,避免二进制响应
.header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
.header("Connection", "keep-alive")
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
if let Ok(parsed_url) = Url::parse(&config.base_url) {
if (parsed_url.scheme() == "http" || parsed_url.scheme() == "https") && parsed_url.host_str().is_some() {
let origin_val = format!("{}://{}", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
let referer_val = format!("{}://{}/", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
request_builder = request_builder
.header("Origin", origin_val)
.header("Referer", referer_val);
}
}
let response = request_builder
.json(&request_body)
.send()
.await
.map_err(|e| {
let error_msg = if e.to_string().contains("timed out") {
format!("模型一API请求超时,请检查网络连接或稍后重试: {}", e)
} else if e.to_string().contains("connect") {
format!("无法连接到模型一API服务器,请检查网络和API地址: {}", e)
} else {
format!("模型一API请求失败: {}", e)
};
AppError::network(error_msg)
})?;
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_default();
return Err(AppError::llm(format!("模型一API请求失败: {} - {}", status, error_text)));
}
// 先获取原始响应文本进行调试
let response_text = response.text().await
.map_err(|e| AppError::llm(format!("获取模型一响应文本失败: {}", e)))?;
// 打印原始响应以供调试(安全处理UTF-8)
let preview_text = if response_text.len() > 200 {
// 安全地截取前200个字节,避免UTF-8字符边界问题
let mut end = 200;
while end > 0 && !response_text.is_char_boundary(end) {
end -= 1;
}
format!("{}...", &response_text[..end])
} else {
response_text.clone()
};
// 检查是否为二进制数据
let is_binary = response_text.chars().any(|c| c.is_control() && c != '\n' && c != '\r' && c != '\t');
println!("📄 模型一原始响应文本 (前200字符): {}", preview_text);
if is_binary {
println!("⚠️ 检测到二进制响应数据,这不是有效的JSON文本");
println!("📄 响应长度: {} 字节", response_text.len());
println!("📄 响应开头字节: {:?}", response_text.as_bytes().get(..10).unwrap_or(&[]));
}
// 检查响应是否为空
if response_text.trim().is_empty() {
return Err(AppError::llm("模型一API返回空响应".to_string()));
}
// 检查是否为流式响应(SSE格式)
if response_text.contains("data: ") || response_text.starts_with("data:") {
println!("⚠️ 检测到流式响应,但期望非流式响应");
return Err(AppError::llm("API返回了流式响应,但模型一需要非流式响应。请检查API配置或切换到支持非流式的模型。".to_string()));
}
// 清理可能的额外字符(一些API可能在JSON前后添加额外内容)
let cleaned_response = response_text.trim();
let cleaned_response = if let Some(start) = cleaned_response.find('{') {
if let Some(end) = cleaned_response.rfind('}') {
&cleaned_response[start..=end]
} else {
cleaned_response
}
} else {
cleaned_response
};
// 尝试解析为JSON
let response_json: Value = serde_json::from_str(cleaned_response)
.map_err(|e| {
println!("📄 JSON解析失败的完整响应: {}", response_text);
println!("📄 清理后的响应: {}", cleaned_response);
{
// 安全地截取响应文本用于错误报告
let error_preview = if response_text.len() > 500 {
let mut end = 500;
while end > 0 && !response_text.is_char_boundary(end) {
end -= 1;
}
format!("{}...", &response_text[..end])
} else {
response_text.clone()
};
if is_binary {
AppError::llm(format!("API返回了二进制数据而非JSON文本。可能的原因:\n1. 响应被压缩(gzip/deflate)\n2. API配置错误\n3. 网络传输问题\n错误: {}", e))
} else {
AppError::llm(format!("解析模型一响应失败: {} \n原始响应: {}", e, error_preview))
}
}
})?;
let content_str = response_json["choices"][0]["message"]["content"]
.as_str()
.ok_or_else(|| AppError::llm("无法解析模型一API响应"))?;
println!("模型一原始响应内容: {}", content_str);
println!("响应长度: {} 字符", content_str.len());
// 添加响应分析
if content_str.len() <= 10 {
println!("⚠️ 警告:模型响应内容过短,可能存在以下问题:");
println!(" 1. max_tokens 设置过低(当前:{})", config.max_output_tokens);
println!(" 2. API 密钥权限不足");
println!(" 3. 模型配置错误");
println!(" 4. 请求内容触发了安全限制");
println!("完整响应JSON: {}", serde_json::to_string_pretty(&response_json).unwrap_or_default());
}
// 强化的JSON解析逻辑 - 多层次解析策略
let parsed_json = parse_model1_json_response(content_str)?;
Ok(StandardModel1Output {
ocr_text: parsed_json["ocr_text"].as_str().unwrap_or("").to_string(),
tags: parsed_json["tags"].as_array()
.map(|arr| arr.iter().filter_map(|v| v.as_str().map(|s| s.to_string())).collect())
.unwrap_or_default(),
mistake_type: parsed_json["mistake_type"].as_str().unwrap_or("").to_string(),
raw_response: Some(content_str.to_string()),
})
}
// 统一AI接口层 - 模型二(核心解析/对话)- 流式版本
pub async fn call_unified_model_2_stream(
&self,
context: &HashMap<String, Value>,
chat_history: &[ChatMessage],
subject: &str,
enable_chain_of_thought: bool,
image_paths: Option<Vec<String>>,
task_context: Option<&str>,
window: Window,
stream_event: &str,
) -> Result<StandardModel2Output> {
println!("调用统一模型二接口(流式): 科目={}, 思维链={}, 图片数量={}",
subject, enable_chain_of_thought, image_paths.as_ref().map(|p| p.len()).unwrap_or(0));
// 获取模型配置
let config = self.get_model2_config().await?;
// 处理图片(如果模型支持多模态且提供了图片)
let images_base64 = if config.is_multimodal && image_paths.is_some() {
let mut base64_images = Vec::new();
for path in image_paths.unwrap() {
let base64_content = self.file_manager.read_file_as_base64(&path)?;
base64_images.push(base64_content);
}
Some(base64_images)
} else {
None
};
let mut messages = vec![];
// 获取科目专用的Prompt
let mut subject_prompt = self.get_subject_prompt(subject, "model2");
// 添加任务上下文
if let Some(context_str) = task_context {
subject_prompt = format!("{}\n\n任务上下文: {}", subject_prompt, context_str);
}
// 构建系统消息,包含RAG增强内容
let mut system_content = format!("{}\n\n题目信息:\nOCR文本: {}\n标签: {:?}\n题目类型: {}\n用户原问题: {}",
subject_prompt,
context.get("ocr_text").and_then(|v| v.as_str()).unwrap_or(""),
context.get("tags").and_then(|v| v.as_array()).unwrap_or(&vec![]),
context.get("mistake_type").and_then(|v| v.as_str()).unwrap_or(""),
context.get("user_question").and_then(|v| v.as_str()).unwrap_or("")
);
// 如果有RAG上下文,添加到系统消息中
if let Some(rag_context) = context.get("rag_context").and_then(|v| v.as_str()) {
system_content.push_str(&format!("\n\n--- 知识库参考信息 ---\n{}", rag_context));
}
// 如果有最新用户查询(继续对话时),添加到系统消息中
if let Some(latest_query) = context.get("latest_user_query").and_then(|v| v.as_str()) {
system_content.push_str(&format!("\n\n用户最新问题: {}", latest_query));
}
// 对于推理模型,系统消息需要合并到用户消息中
if config.is_reasoning {
// 推理模型不支持系统消息,需要将系统提示合并到用户消息中
let combined_content = format!("{}\n\n请基于上述信息,提供详细的解答。", system_content);
if config.is_multimodal && images_base64.is_some() && chat_history.is_empty() {
let mut content = vec![
json!({
"type": "text",
"text": combined_content
})
];
if let Some(images) = &images_base64 {
for image_base64 in images {
let image_format = Self::detect_image_format_from_base64(image_base64);
println!("🖼️ 检测到图像格式: {}", image_format);
content.push(json!({
"type": "image_url",
"image_url": {
"url": format!("data:image/{};base64,{}", image_format, image_base64)
}
}));
}
}
messages.push(json!({
"role": "user",
"content": content
}));
} else if chat_history.is_empty() {
messages.push(json!({
"role": "user",
"content": combined_content
}));
} else {
// 如果有聊天历史,将系统提示添加到第一条用户消息前
messages.push(json!({
"role": "user",
"content": format!("{}请基于前面的信息,回答我的新问题。", system_content)
}));
}
} else {
// 非推理模型使用标准的系统消息
messages.push(json!({
"role": "system",
"content": system_content
}));
// 如果是多模态模型且提供了图片,添加图片到第一条用户消息
if config.is_multimodal && images_base64.is_some() && chat_history.is_empty() {
let mut content = vec![
json!({
"type": "text",
"text": "请基于上述信息和图片,提供详细的解答。"
})
];
if let Some(images) = &images_base64 {
for image_base64 in images {
let image_format = Self::detect_image_format_from_base64(image_base64);
println!("🖼️ 检测到图像格式: {}", image_format);
content.push(json!({
"type": "image_url",
"image_url": {
"url": format!("data:image/{};base64,{}", image_format, image_base64)
}
}));
}
}
messages.push(json!({
"role": "user",
"content": content
}));
} else if chat_history.is_empty() {
// 纯文本模型或没有提供图片
messages.push(json!({
"role": "user",
"content": "请基于上述信息,提供详细的解答。"
}));
}
}
// 添加聊天历史
for (index, msg) in chat_history.iter().enumerate() {
// 🎯 修复:如果是多模态模型且有图片,在最后一条用户消息中添加图片
if msg.role == "user" && index == chat_history.len() - 1 && config.is_multimodal && images_base64.is_some() {
let mut content = vec![
json!({
"type": "text",
"text": msg.content.clone()
})
];
if let Some(images) = &images_base64 {
for image_base64 in images {
let image_format = Self::detect_image_format_from_base64(image_base64);
println!("🖼️ 检测到图像格式: {}", image_format);
content.push(json!({
"type": "image_url",
"image_url": {
"url": format!("data:image/{};base64,{}", image_format, image_base64)
}
}));
}
}
messages.push(json!({
"role": msg.role,
"content": content
}));
} else {
messages.push(json!({
"role": msg.role,
"content": msg.content
}));
}
}
let mut request_body = json!({
"model": config.model,
"messages": messages,
"stream": true
});
// 根据模型适配器类型和是否为推理模型设置不同的参数
println!("模型适配器类型: {}, 推理模型: {}, 前端请求思维链: {}",
config.model_adapter, config.is_reasoning, enable_chain_of_thought);
let is_deepseek_model_family = config.model_adapter == "deepseek-r1" ||
config.model.to_lowercase().contains("deepseek");
if config.is_reasoning { // 目标是推理模型
match config.model_adapter.as_str() {
"deepseek-r1" => {
request_body["max_tokens"] = json!(config.max_output_tokens);
// 只有当明确是 deepseek-r1 且前端请求了思维链时,才添加 stream_options
// 或者,如果 deepseek-r1 总是需要这个选项来保证流式稳定,则无条件添加
if enable_chain_of_thought { // 或者无条件添加 if deepseek-r1 needs it
request_body["stream_options"] = json!({"include_usage": true});
println!("应用 DeepSeek-R1 特殊参数 (启用思维链): max_tokens={}, stream_options=include_usage", config.max_output_tokens);
} else {
println!("应用 DeepSeek-R1 特殊参数 (未启用思维链): max_tokens={}", config.max_output_tokens);
}
},
_ => { // 其他推理模型
request_body["max_completion_tokens"] = json!(config.max_output_tokens);
println!("应用通用推理模型参数: max_completion_tokens={}", config.max_output_tokens);
}
}
} else { // 目标是非推理模型 (例如 deepseek-v3 可能落入此分支)
if is_deepseek_model_family {
request_body["max_tokens"] = json!(config.max_output_tokens);
request_body["temperature"] = json!(config.temperature);
// 对于非推理的DeepSeek模型,如果它们不支持或不需要 stream_options,则不应添加
// 如果它们也需要 stream_options 来稳定流式输出,则可以考虑添加
// request_body["stream_options"] = json!({"include_usage": true});
println!("应用 DeepSeek 普通模型参数: max_tokens={}, temperature={}", config.max_output_tokens, config.temperature);
} else { // 其他通用非推理模型
request_body["max_tokens"] = json!(config.max_output_tokens);
request_body["temperature"] = json!(config.temperature);
println!("应用普通模型参数: max_tokens={}, temperature={}", config.max_output_tokens, config.temperature);
}
// 关键:如果模型是非推理模型,即使前端请求了思维链,
// 也不要向API发送特定于思维链的参数,除非该模型明确支持。
// 对于通用模型,通常不需要为"思维链"传递特殊参数,模型会自然地按指令回复。
// 如果 enable_chain_of_thought 对非推理模型意味着不同的处理(例如,更详细的回复),
// 这里的逻辑可能需要调整,但通常是Prompt工程的一部分,而不是API参数。
if enable_chain_of_thought {
println!("警告: 前端为非推理模型 {} 请求了思维链。通常这由Prompt控制,而非特定API参数。", config.model);
}
}
let mut request_builder = self.client
.post(&format!("{}/chat/completions", config.base_url))
.header("Authorization", format!("Bearer {}", config.api_key))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/plain, */*")
.header("Accept-Encoding", "identity") // 禁用压缩,避免二进制响应
.header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
.header("Connection", "keep-alive")
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
if let Ok(parsed_url) = Url::parse(&config.base_url) {
if (parsed_url.scheme() == "http" || parsed_url.scheme() == "https") && parsed_url.host_str().is_some() {
let origin_val = format!("{}://{}", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
let referer_val = format!("{}://{}/", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
request_builder = request_builder
.header("Origin", origin_val)
.header("Referer", referer_val);
}
}
let response = request_builder
.json(&request_body)
.send()
.await
.map_err(|e| AppError::network(format!("模型二API请求失败: {}", e)))?;
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_default();
return Err(AppError::llm(format!("模型二API请求失败: {} - {}", status, error_text)));
}
let mut stream = response.bytes_stream();
let mut full_content = String::new();
let mut reasoning_content = String::new(); // 收集思维链内容
let mut chunk_counter = 0;
let mut stream_ended = false;
// 添加调试日志输出
println!("🚀 发送给模型二的请求:");
println!("URL: {}/chat/completions", config.base_url);
println!("Model: {}", config.model);
println!("请求内容: {}", serde_json::to_string_pretty(&request_body).unwrap_or_else(|_| "序列化失败".to_string()));
println!("---请求结束---");
while let Some(chunk_result) = stream.next().await {
match chunk_result {
Ok(chunk) => {
let chunk_str = String::from_utf8_lossy(&chunk);
// 输出原始响应块(仅输出前几个块避免日志过多)
if chunk_counter < 5 || stream_ended {
println!("📥 原始响应块 #{}: {}", chunk_counter, chunk_str);
}
// 处理SSE格式的数据
for line in chunk_str.lines() {
if line.starts_with("data: ") {
let data = &line[6..]; // 移除 "data: " 前缀
if data == "[DONE]" {
// 流结束,标记但不立即发送完成信号
stream_ended = true;
println!("📍 收到流结束标记 [DONE]");
break;
}
// 特殊处理DeepSeek错误格式
if is_deepseek_model_family && (data.contains("升级") || data.contains("关闭") || data.contains("日志")) {
println!("❌ 检测到DeepSeek特定错误: {}", data);
let error_message = format!("DeepSeek API错误: {}", data);
// 发送错误事件到前端
if let Err(e) = window.emit("stream_error", &serde_json::json!({"error": error_message})) {
println!("发送DeepSeek错误事件失败: {}", e);
}
return Err(AppError::llm(error_message));
}
// 尝试解析JSON
if let Ok(json_data) = serde_json::from_str::<Value>(data) {
// 输出解析后的JSON结构(仅输出前几个)
if chunk_counter < 5 {
println!("🔍 解析后的JSON数据: {}", serde_json::to_string_pretty(&json_data).unwrap_or_else(|_| "序列化失败".to_string()));
}
if let Some(choices) = json_data["choices"].as_array() {
if let Some(choice) = choices.first() {
if let Some(delta) = choice["delta"].as_object() {
// DeepSeek-R1 推理模型的思维链内容在 reasoning_content 字段
if let Some(reasoning_content_chunk) = delta.get("reasoning_content").and_then(|v| v.as_str()) {
// 这是思维链内容
reasoning_content.push_str(reasoning_content_chunk); // 收集思维链
chunk_counter += 1;
if chunk_counter < 10 {
println!("🧠 收到思维链块: {}", reasoning_content_chunk);
}
let stream_chunk = StreamChunk {
content: reasoning_content_chunk.to_string(),
is_complete: false,
chunk_id: format!("reasoning_chunk_{}", chunk_counter),
};
// 发送思维链流事件到前端
if let Err(e) = window.emit(&format!("{}_reasoning", stream_event), &stream_chunk) {
println!("发送思维链流事件失败: {}", e);
}
}
// 普通内容仍在 content 字段
if let Some(content) = delta.get("content").and_then(|v| v.as_str()) {
full_content.push_str(content);
chunk_counter += 1;
if chunk_counter < 10 {
println!("💬 收到主内容块: {}", content);
}
let stream_chunk = StreamChunk {
content: content.to_string(),
is_complete: false,
chunk_id: format!("chunk_{}", chunk_counter),
};
// 发送流事件到前端
if let Err(e) = window.emit(stream_event, &stream_chunk) {
println!("发送流事件失败: {}", e);
}
}
}
}
}
} else {
// JSON解析失败,输出原始数据以便调试
if chunk_counter < 10 {
println!("⚠️ JSON解析失败,原始数据: {}", data);
}
// 检查是否是错误信息
if data.contains("error") || data.contains("Error") || data.contains("升级") {
println!("❌ 检测到流式请求错误: {}", data);
// 尝试解析错误信息
let error_message = if let Ok(error_json) = serde_json::from_str::<serde_json::Value>(data) {
if let Some(error_msg) = error_json.get("error").and_then(|e| e.as_str()) {
error_msg.to_string()
} else if let Some(message) = error_json.get("message").and_then(|m| m.as_str()) {
message.to_string()
} else {
format!("流式请求错误: {}", data)
}
} else {
format!("流式请求解析错误: {}", data)
};
// 发送错误事件到前端
if let Err(e) = window.emit("stream_error", &serde_json::json!({"error": error_message})) {
println!("发送错误事件失败: {}", e);
}
return Err(AppError::llm(error_message));
}
}
}
}
}
Err(e) => {
println!("❌ 流读取错误: {}", e);
println!("已处理块数: {}, 主内容长度: {}, 思维链长度: {}",
chunk_counter, full_content.len(), reasoning_content.len());
// 如果已经有内容,不把这当作完全失败
if !full_content.is_empty() || !reasoning_content.is_empty() {
println!("⚠️ 部分内容已接收,标记为部分成功");
break;
} else {
println!("💥 没有接收到任何内容,这是完全失败");
return Err(AppError::network(format!("流式请求失败: {}", e)));
}
}
}
// 如果流已结束,退出循环
if stream_ended {
break;
}
}
// 输出最终收集的内容长度
println!("📊 流式响应完成统计:");
println!(" - 主内容总长度: {} 字符", full_content.len());
println!(" - 思维链总长度: {} 字符", reasoning_content.len());
println!(" - 主内容预览:");
if full_content.chars().count() > 50 {
let preview: String = full_content.chars().take(50).collect();
println!("{}...", preview);
} else {
println!("{}", full_content);
}
println!(" - 思维链预览:");
if reasoning_content.chars().count() > 50 {
let preview: String = reasoning_content.chars().take(50).collect();
println!("{}...", preview);
} else {
println!("{}", reasoning_content);
}
// 发送最终完成信号到主内容流
let final_chunk = StreamChunk {
content: full_content.clone(), // 发送完整内容而不是空字符串
is_complete: true,
chunk_id: format!("final_chunk_{}", chunk_counter + 1),
};
if let Err(e) = window.emit(stream_event, &final_chunk) {
println!("发送最终主内容完成信号失败: {}", e);
} else {
println!("✅ 发送主内容完成信号成功,内容长度: {}", full_content.len());
}
// 如果有思维链内容,也发送思维链完成信号
if enable_chain_of_thought && !reasoning_content.is_empty() {
let reasoning_final_chunk = StreamChunk {
content: reasoning_content.clone(), // 也发送完整的思维链内容
is_complete: true,
chunk_id: format!("reasoning_final_chunk_{}", chunk_counter + 1),
};
if let Err(e) = window.emit(&format!("{}_reasoning", stream_event), &reasoning_final_chunk) {
println!("发送思维链完成信号失败: {}", e);
} else {
println!("✅ 发送思维链完成信号成功,内容长度: {}", reasoning_content.len());
}
}
// 如果启用了思维链,尝试提取思维链详情
let is_deepseek_r1 = config.model_adapter == "deepseek-r1";
let chain_of_thought_details = if enable_chain_of_thought || is_deepseek_r1 {
if config.is_reasoning || is_deepseek_r1 {
// 推理模型自动包含思维链
let details = if is_deepseek_r1 && !reasoning_content.is_empty() {
// DeepSeek-R1 的思维链在 reasoning_content 中
json!({
"full_response": full_content,
"reasoning_content": reasoning_content,
"enabled": true,
"is_reasoning_model": true,
"model_type": "deepseek-r1",
"model_adapter": config.model_adapter,
"parsed_sections": extract_reasoning_sections(&reasoning_content)
})
} else {
// 其他推理模型的思维链在主内容中
json!({
"full_response": full_content,
"enabled": true,
"is_reasoning_model": true,
"model_adapter": config.model_adapter,
"parsed_sections": extract_reasoning_sections(&full_content)
})
};
Some(details)
} else {
// 普通模型的思维链处理
Some(json!({
"full_response": full_content,
"enabled": true,
"is_reasoning_model": false,
"model_adapter": config.model_adapter
}))
}
} else {
None
};
Ok(StandardModel2Output {
assistant_message: full_content,
raw_response: Some("stream_response".to_string()),
chain_of_thought_details,
})
}
// 🎯 新增:通用流式接口,支持自定义模型配置(用于总结请求等特殊场景)
pub async fn call_unified_model_stream_with_config(
&self,
config: &ApiConfig,
context: &HashMap<String, Value>,
chat_history: &[ChatMessage],
subject: &str,
enable_chain_of_thought: bool,
image_paths: Option<Vec<String>>,
task_context: Option<&str>,
window: Window,
stream_event: &str,
) -> Result<StandardModel2Output> {
println!("调用通用流式接口: 模型={}, 科目={}, 思维链={}, 图片数量={}",
config.model, subject, enable_chain_of_thought, image_paths.as_ref().map(|p| p.len()).unwrap_or(0));
// *** 新增的适配器路由逻辑 ***
if config.model_adapter == "google" {
// 处理图片(如果模型支持多模态且提供了图片)
let images_base64 = if config.is_multimodal && image_paths.is_some() {
let mut base64_images = Vec::new();
for path in image_paths.as_ref().unwrap() {
let base64_content = self.file_manager.read_file_as_base64(path)?;
base64_images.push(base64_content);
}
Some(base64_images)
} else {
None
};
// 构建 ChatMessage 格式的消息历史
let mut messages_with_images = chat_history.to_vec();
// 如果有图片且是多模态模型,将图片添加到最后一条用户消息
if let Some(images) = images_base64 {
if let Some(last_msg) = messages_with_images.last_mut() {
if last_msg.role == "user" {
last_msg.image_base64 = Some(images);
}
} else {
// 如果没有聊天历史,创建一个包含图片的用户消息
let mut system_content = String::new();
// 构建系统提示词
if !context.is_empty() {
for (key, value) in context {
match key.as_str() {
"ocr_text" => system_content.push_str(&format!("题目内容: {}\n", value.as_str().unwrap_or(""))),
"user_question" => system_content.push_str(&format!("学生问题: {}\n", value.as_str().unwrap_or(""))),
"tags" => {
if let Some(tags_array) = value.as_array() {
let tags: Vec<String> = tags_array.iter()
.filter_map(|v| v.as_str())
.map(|s| s.to_string())
.collect();
if !tags.is_empty() {
system_content.push_str(&format!("相关标签: {}\n", tags.join(", ")));
}
}
},
"mistake_type" => system_content.push_str(&format!("题目类型: {}\n", value.as_str().unwrap_or(""))),
_ => {}
}
}
}
system_content.push_str("请基于上述信息和图片,提供详细的解答。");
let message = ChatMessage {
role: "user".to_string(),
content: system_content,
timestamp: chrono::Utc::now(),
thinking_content: None,
rag_sources: None,
image_paths: None,
image_base64: Some(images),
};
messages_with_images.push(message);
}
}
// 调用 Gemini 适配器(流式)
return gemini_adapter::stream_chat(
&self.client,
config,
&messages_with_images,
window,
stream_event,
).await;
}
// *** 适配器逻辑结束 ***
// 处理图片(如果模型支持多模态且提供了图片)
let images_base64 = if config.is_multimodal && image_paths.is_some() {
let mut base64_images = Vec::new();
for path in image_paths.unwrap() {
let base64_content = self.file_manager.read_file_as_base64(&path)?;
base64_images.push(base64_content);
}
Some(base64_images)
} else {
None
};
let mut messages = vec![];
// 获取科目专用的Prompt
let subject_prompt = self.db.get_subject_config_by_name(subject)
.unwrap_or(None)
.map(|config| {
match task_context {
Some(task) if task.contains("总结") || task.contains("summary") => {
format!("【科目专用指导 - {}】\n{}\n\n", subject, config.prompts.analysis_prompt)
},
_ => {
format!("【科目专用指导 - {}】\n{}\n\n", subject, config.prompts.chat_prompt)
}
}
})
.unwrap_or_else(|| format!("请基于{}科目的特点进行分析。\n\n", subject));
// 构建系统提示词(使用与call_unified_model_2_stream相同的逻辑)
if !context.is_empty() {
let mut system_content = subject_prompt;
if let Some(task_ctx) = task_context {
system_content.push_str(&format!("【任务背景】\n{}\n\n", task_ctx));
}
for (key, value) in context {
match key.as_str() {
"ocr_text" => system_content.push_str(&format!("【题目内容】\n{}\n\n", value.as_str().unwrap_or(""))),
"user_question" => system_content.push_str(&format!("【学生问题】\n{}\n\n", value.as_str().unwrap_or(""))),
"tags" => {
if let Some(tags_array) = value.as_array() {
let tags: Vec<String> = tags_array.iter()
.filter_map(|v| v.as_str())
.map(|s| s.to_string())
.collect();
if !tags.is_empty() {
system_content.push_str(&format!("【相关标签】\n{}\n\n", tags.join(", ")));
}
}
},
"mistake_type" => system_content.push_str(&format!("【题目类型】\n{}\n\n", value.as_str().unwrap_or(""))),
_ => {}
}
}
messages.push(json!({
"role": "system",
"content": system_content
}));
// 如果是多模态模型且提供了图片,添加图片到第一条用户消息
if config.is_multimodal && images_base64.is_some() && chat_history.is_empty() {
let mut content = vec![
json!({
"type": "text",
"text": "请基于上述信息和图片,提供详细的解答。"
})
];
if let Some(images) = &images_base64 {
for image_base64 in images {
let image_format = Self::detect_image_format_from_base64(image_base64);
println!("🖼️ 检测到图像格式: {}", image_format);
content.push(json!({
"type": "image_url",
"image_url": {
"url": format!("data:image/{};base64,{}", image_format, image_base64)
}
}));
}
}
messages.push(json!({
"role": "user",
"content": content
}));
} else if chat_history.is_empty() {
// 纯文本模型或没有提供图片
messages.push(json!({
"role": "user",
"content": "请基于上述信息,提供详细的解答。"
}));
}
}
// 添加聊天历史
for (index, msg) in chat_history.iter().enumerate() {
// 🎯 修复:如果是多模态模型且有图片,在最后一条用户消息中添加图片
if msg.role == "user" && index == chat_history.len() - 1 && config.is_multimodal && images_base64.is_some() {
let mut content = vec![
json!({
"type": "text",
"text": msg.content.clone()
})
];
if let Some(images) = &images_base64 {
for image_base64 in images {
let image_format = Self::detect_image_format_from_base64(image_base64);
println!("🖼️ 检测到图像格式: {}", image_format);
content.push(json!({
"type": "image_url",
"image_url": {
"url": format!("data:image/{};base64,{}", image_format, image_base64)
}
}));
}
}
messages.push(json!({
"role": msg.role,
"content": content
}));
} else {
messages.push(json!({
"role": msg.role,
"content": msg.content
}));
}
}
let mut request_body = json!({
"model": config.model,
"messages": messages,
"stream": true
});
// 根据模型适配器添加特定参数
match config.model_adapter.as_str() {
"deepseek-r1" => {
request_body["max_reasoning_tokens"] = json!(config.max_output_tokens);
request_body["max_completion_tokens"] = json!(4096);
request_body["temperature"] = json!(config.temperature);
},
_ => {
request_body["max_tokens"] = json!(config.max_output_tokens);
request_body["temperature"] = json!(config.temperature);
}
}
println!("发送请求到: {}", config.base_url);
let mut request_builder = self.client
.post(&format!("{}/chat/completions", config.base_url))
.header("Authorization", format!("Bearer {}", config.api_key))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/plain, */*")
.header("Accept-Encoding", "identity") // 禁用压缩,避免二进制响应
.header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
.header("Connection", "keep-alive")
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
if let Ok(parsed_url) = Url::parse(&config.base_url) { // config is a parameter here
if (parsed_url.scheme() == "http" || parsed_url.scheme() == "https") && parsed_url.host_str().is_some() {
let origin_val = format!("{}://{}", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
let referer_val = format!("{}://{}/", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
request_builder = request_builder
.header("Origin", origin_val)
.header("Referer", referer_val);
}
}
let response = request_builder
.json(&request_body)
.send()
.await
.map_err(|e| AppError::network(format!("请求失败: {}", e)))?;
// 流式处理响应(使用与call_unified_model_2_stream相同的逻辑)
let mut stream = response.bytes_stream();
let mut full_content = String::new();
let mut reasoning_content = String::new();
let mut chunk_counter = 0;
while let Some(chunk_result) = stream.next().await {
match chunk_result {
Ok(chunk) => {
let chunk_str = String::from_utf8_lossy(&chunk);
for line in chunk_str.lines() {
if line.starts_with("data: ") {
let data = &line[6..];
if data == "[DONE]" {
break;
}
if let Ok(json_data) = serde_json::from_str::<Value>(data) {
if let Some(choices) = json_data["choices"].as_array() {
if let Some(choice) = choices.first() {
// 处理主内容
if let Some(delta) = choice["delta"].as_object() {
if let Some(content) = delta.get("content").and_then(|v| v.as_str()) {
full_content.push_str(content);
let chunk = StreamChunk {
content: content.to_string(),
is_complete: false,
chunk_id: format!("chunk_{}", chunk_counter),
};
if let Err(e) = window.emit(stream_event, &chunk) {
println!("发送流式数据失败: {}", e);
}
chunk_counter += 1;
}
}
// 处理思维链内容(DeepSeek-R1)
if config.model_adapter == "deepseek-r1" {
if let Some(delta) = choice["delta"].as_object() {
if let Some(reasoning) = delta.get("reasoning_content").and_then(|v| v.as_str()) {
reasoning_content.push_str(reasoning);
let reasoning_chunk = StreamChunk {
content: reasoning.to_string(),
is_complete: false,
chunk_id: format!("reasoning_chunk_{}", chunk_counter),
};
if let Err(e) = window.emit(&format!("{}_reasoning", stream_event), &reasoning_chunk) {
println!("发送思维链流式数据失败: {}", e);
}
}
}
}
}
}
}
}
}
}
Err(e) => {
println!("流式响应错误: {}", e);
break;
}
}
}
// 发送完成信号
let final_chunk = StreamChunk {
content: full_content.clone(),
is_complete: true,
chunk_id: format!("final_chunk_{}", chunk_counter),
};
if let Err(e) = window.emit(stream_event, &final_chunk) {
println!("发送最终完成信号失败: {}", e);
}
// 如果有思维链内容,也发送思维链完成信号
if enable_chain_of_thought && !reasoning_content.is_empty() {
let reasoning_final_chunk = StreamChunk {
content: reasoning_content.clone(),
is_complete: true,
chunk_id: format!("reasoning_final_chunk_{}", chunk_counter + 1),
};
if let Err(e) = window.emit(&format!("{}_reasoning", stream_event), &reasoning_final_chunk) {
println!("发送思维链完成信号失败: {}", e);
}
}
// 构建思维链详情
let is_deepseek_r1 = config.model_adapter == "deepseek-r1";
let chain_of_thought_details = if enable_chain_of_thought || is_deepseek_r1 {
if config.is_reasoning || is_deepseek_r1 {
let details = if is_deepseek_r1 && !reasoning_content.is_empty() {
json!({
"full_response": full_content,
"reasoning_content": reasoning_content,
"enabled": true,
"is_reasoning_model": true,
"model_type": "deepseek-r1",
"model_adapter": config.model_adapter
})
} else {
json!({
"full_response": full_content,
"enabled": true,
"is_reasoning_model": true,
"model_adapter": config.model_adapter
})
};
Some(details)
} else {
None
}
} else {
None
};
Ok(StandardModel2Output {
assistant_message: full_content,
raw_response: Some("stream_response".to_string()),
chain_of_thought_details,
})
}
// 统一AI接口层 - 模型二(核心解析/对话)- 非流式版本(保持向后兼容)
pub async fn call_unified_model_2(
&self,
context: &HashMap<String, Value>,
chat_history: &[ChatMessage],
subject: &str,
enable_chain_of_thought: bool,
image_paths: Option<Vec<String>>,
task_context: Option<&str>,
) -> Result<StandardModel2Output> {
println!("调用统一模型二接口: 科目={}, 思维链={}, 图片数量={}",
subject, enable_chain_of_thought, image_paths.as_ref().map(|p| p.len()).unwrap_or(0));
// 获取模型配置
let config = self.get_model2_config().await?;
// 处理图片(如果模型支持多模态且提供了图片)
let images_base64 = if config.is_multimodal && image_paths.is_some() {
let mut base64_images = Vec::new();
for path in image_paths.unwrap() {
let base64_content = self.file_manager.read_file_as_base64(&path)?;
base64_images.push(base64_content);
}
Some(base64_images)
} else {
None
};
let mut messages = vec![];
// 获取科目专用的Prompt
let mut subject_prompt = self.get_subject_prompt(subject, "model2");
// 添加任务上下文
if let Some(context_str) = task_context {
subject_prompt = format!("{}\n\n任务上下文: {}", subject_prompt, context_str);
}
// 构建系统消息,包含RAG增强内容
let mut system_content = format!("{}\n\n题目信息:\nOCR文本: {}\n标签: {:?}\n题目类型: {}\n用户原问题: {}",
subject_prompt,
context.get("ocr_text").and_then(|v| v.as_str()).unwrap_or(""),
context.get("tags").and_then(|v| v.as_array()).unwrap_or(&vec![]),
context.get("mistake_type").and_then(|v| v.as_str()).unwrap_or(""),
context.get("user_question").and_then(|v| v.as_str()).unwrap_or("")
);
// 如果有RAG上下文,添加到系统消息中
if let Some(rag_context) = context.get("rag_context").and_then(|v| v.as_str()) {
system_content.push_str(&format!("\n\n--- 知识库参考信息 ---\n{}", rag_context));
}
// 如果有最新用户查询(继续对话时),添加到系统消息中
if let Some(latest_query) = context.get("latest_user_query").and_then(|v| v.as_str()) {
system_content.push_str(&format!("\n\n用户最新问题: {}", latest_query));
}
// 对于推理模型,系统消息需要合并到用户消息中
if config.is_reasoning {
// 推理模型不支持系统消息,需要将系统提示合并到用户消息中
let combined_content = format!("{}\n\n请基于上述信息,提供详细的解答。", system_content);
if config.is_multimodal && images_base64.is_some() && chat_history.is_empty() {
let mut content = vec![
json!({
"type": "text",
"text": combined_content
})
];
if let Some(images) = &images_base64 {
for image_base64 in images {
let image_format = Self::detect_image_format_from_base64(image_base64);
println!("🖼️ 检测到图像格式: {}", image_format);
content.push(json!({
"type": "image_url",
"image_url": {
"url": format!("data:image/{};base64,{}", image_format, image_base64)
}
}));
}
}
messages.push(json!({
"role": "user",
"content": content
}));
} else if chat_history.is_empty() {
messages.push(json!({
"role": "user",
"content": combined_content
}));
} else {
// 如果有聊天历史,将系统提示添加到第一条用户消息前
messages.push(json!({
"role": "user",
"content": format!("{}请基于前面的信息,回答我的新问题。", system_content)
}));
}
} else {
// 非推理模型使用标准的系统消息
messages.push(json!({
"role": "system",
"content": system_content
}));
// 如果是多模态模型且提供了图片,添加图片到第一条用户消息
if config.is_multimodal && images_base64.is_some() && chat_history.is_empty() {
let mut content = vec![
json!({
"type": "text",
"text": "请基于上述信息和图片,提供详细的解答。"
})
];
if let Some(images) = &images_base64 {
for image_base64 in images {
let image_format = Self::detect_image_format_from_base64(image_base64);
println!("🖼️ 检测到图像格式: {}", image_format);
content.push(json!({
"type": "image_url",
"image_url": {
"url": format!("data:image/{};base64,{}", image_format, image_base64)
}
}));
}
}
messages.push(json!({
"role": "user",
"content": content
}));
} else if chat_history.is_empty() {
// 纯文本模型或没有提供图片
messages.push(json!({
"role": "user",
"content": "请基于上述信息,提供详细的解答。"
}));
}
}
// 添加聊天历史
for msg in chat_history {
messages.push(json!({
"role": msg.role,
"content": msg.content
}));
}
let mut request_body = json!({
"model": config.model,
"messages": messages,
"stream": false // 非流式版本
});
// 根据模型适配器类型设置不同的参数
println!("模型适配器类型: {}, 推理模型: {}", config.model_adapter, config.is_reasoning);
if config.is_reasoning {
// 推理模型的特殊参数
match config.model_adapter.as_str() {
"deepseek-r1" => {
request_body["max_tokens"] = json!(config.max_output_tokens);
println!("应用 DeepSeek-R1 特殊参数: max_tokens={}", config.max_output_tokens);
},
_ => {
// 其他推理模型(如o1系列)
request_body["max_completion_tokens"] = json!(config.max_output_tokens);
println!("应用通用推理模型参数: max_completion_tokens={}", config.max_output_tokens);
}
}
} else {
// 普通模型的标准参数
request_body["max_tokens"] = json!(config.max_output_tokens);
request_body["temperature"] = json!(config.temperature);
println!("应用普通模型参数: max_tokens={}, temperature={}", config.max_output_tokens, config.temperature);
}
let mut request_builder = self.client
.post(&format!("{}/chat/completions", config.base_url))
.header("Authorization", format!("Bearer {}", config.api_key))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/plain, */*")
.header("Accept-Encoding", "identity") // 禁用压缩,避免二进制响应
.header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
.header("Connection", "keep-alive")
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
if let Ok(parsed_url) = Url::parse(&config.base_url) {
if (parsed_url.scheme() == "http" || parsed_url.scheme() == "https") && parsed_url.host_str().is_some() {
let origin_val = format!("{}://{}", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
let referer_val = format!("{}://{}/", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
request_builder = request_builder
.header("Origin", origin_val)
.header("Referer", referer_val);
}
}
let response = request_builder
.json(&request_body)
.send()
.await
.map_err(|e| AppError::network(format!("模型二API请求失败: {}", e)))?;
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_default();
return Err(AppError::llm(format!("模型二API请求失败: {} - {}", status, error_text)));
}
let response_json: Value = response.json().await
.map_err(|e| AppError::llm(format!("解析模型二响应失败: {}", e)))?;
let content = response_json["choices"][0]["message"]["content"]
.as_str()
.ok_or_else(|| AppError::llm("无法解析模型二API响应"))?;
// 如果启用了思维链,尝试提取思维链详情
let is_deepseek_r1 = config.model_adapter == "deepseek-r1";
let chain_of_thought_details = if enable_chain_of_thought || is_deepseek_r1 {
// 这里可以根据响应内容解析思维链步骤
// 暂时将完整响应作为思维链详情
Some(json!({
"full_response": content,
"enabled": true,
"is_reasoning_model": config.is_reasoning,
"model_adapter": config.model_adapter
}))
} else {
None
};
Ok(StandardModel2Output {
assistant_message: content.to_string(),
raw_response: Some(response_json.to_string()),
chain_of_thought_details,
})
}
// 测试API连接 - 支持指定模型名称
pub async fn test_connection(&self, api_key: &str, base_url: &str) -> Result<bool> {
self.test_connection_with_model(api_key, base_url, None).await
}
// 测试API连接 - 可以指定具体模型
pub async fn test_connection_with_model(&self, api_key: &str, base_url: &str, model_name: Option<&str>) -> Result<bool> {
println!("测试API连接: {} (密钥长度: {})", base_url, api_key.len());
// 确保base_url格式正确
let normalized_url = if base_url.ends_with('/') {
base_url.trim_end_matches('/').to_string()
} else {
base_url.to_string()
};
// 如果指定了模型名称,优先使用指定的模型
let test_models = if let Some(specified_model) = model_name {
vec![specified_model.to_string()]
} else {
// 使用通用的测试模型名称,不同API提供商可能支持不同的模型
vec![
"gpt-3.5-turbo".to_string(), // OpenAI
"deepseek-chat".to_string(), // DeepSeek
"Qwen/Qwen2-7B-Instruct".to_string(), // SiliconFlow
"meta-llama/Llama-2-7b-chat-hf".to_string(), // 其他
]
};
// 尝试不同的模型进行测试
for model in test_models {
let request_body = json!({
"model": model,
"messages": [
{
"role": "user",
"content": "Hi"
}
],
"max_tokens": 5,
"temperature": 0.1
});
println!("尝试模型: {}", model);
// 使用tokio的timeout包装整个请求
let timeout_duration = std::time::Duration::from_secs(15);
let mut request_builder = self.client
.post(&format!("{}/chat/completions", normalized_url))
.header("Authorization", format!("Bearer {}", api_key))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/plain, */*")
.header("Accept-Encoding", "identity") // 禁用压缩,避免二进制响应
.header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
.header("Connection", "keep-alive")
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
if let Ok(parsed_url) = Url::parse(&normalized_url) { // Use normalized_url here
if (parsed_url.scheme() == "http" || parsed_url.scheme() == "https") && parsed_url.host_str().is_some() {
let origin_val = format!("{}://{}", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
let referer_val = format!("{}://{}/", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
request_builder = request_builder
.header("Origin", origin_val)
.header("Referer", referer_val);
}
}
let request_future = request_builder
.json(&request_body)
.send();
// 使用tokio::time::timeout
match tokio::time::timeout(timeout_duration, request_future).await {
Ok(Ok(response)) => {
let status = response.status();
println!("API连接测试响应状态: {} (模型: {})", status, model);
if status.is_success() {
println!("API连接测试成功!使用模型: {}", model);
return Ok(true);
} else if status == 400 {
// 400错误可能是模型不支持,尝试下一个
let error_text = response.text().await.unwrap_or_default();
println!("模型 {} 不支持,错误: {}", model, error_text);
// 如果是用户指定的模型,直接返回失败
if model_name.is_some() {
return Ok(false);
}
continue;
} else if status == 401 {
// 401是认证错误,不需要尝试其他模型
println!("API密钥认证失败: {}", status);
return Ok(false);
} else {
// 其他错误
let error_text = response.text().await.unwrap_or_default();
println!("API请求失败: {} - {}", status, error_text);
// 如果是用户指定的模型,直接返回失败
if model_name.is_some() {
return Ok(false);
}
continue;
}
},
Ok(Err(e)) => {
println!("API连接测试请求错误 (模型: {}): {}", model, e);
// 如果是连接错误,不需要尝试其他模型
if e.to_string().contains("handshake") || e.to_string().contains("connect") {
return Err(AppError::network(format!("连接失败: {}", e)));
}
// 如果是用户指定的模型,直接返回失败
if model_name.is_some() {
return Err(AppError::network(format!("请求失败: {}", e)));
}
continue;
},
Err(_) => {
println!("API连接测试超时 (模型: {})", model);
// 如果是用户指定的模型,直接返回失败
if model_name.is_some() {
return Err(AppError::network("请求超时"));
}
continue;
}
}
}
println!("所有测试模型都失败了");
Ok(false)
}
}
// 获取科目配置的Prompt模板(从数据库读取)
impl LLMManager {
pub fn get_subject_prompt(&self, subject: &str, task_type: &str) -> String {
// 尝试从数据库获取科目配置
match self.db.get_subject_config_by_name(subject) {
Ok(Some(config)) => {
let base_prompt = match task_type {
"model1" | "ocr" | "classification" => {
// OCR和分类任务使用OCR提示词+分类提示词
let mut prompt = config.prompts.ocr_prompt.clone();
if !config.prompts.classification_prompt.is_empty() {
prompt.push_str("\n\n");
prompt.push_str(&config.prompts.classification_prompt);
}
// 添加JSON格式要求
prompt.push_str("\n\n请以JSON格式返回结果:{\"ocr_text\": \"题目文字\", \"tags\": [\"标签1\", \"标签2\"], \"mistake_type\": \"题目类型\"}");
prompt
},
"model2" | "analysis" => {
config.prompts.analysis_prompt.clone()
},
"review" => {
config.prompts.review_prompt.clone()
},
"chat" => {
config.prompts.chat_prompt.clone()
},
"consolidated_review" | "consolidated_review_chat" => {
config.prompts.consolidated_review_prompt.clone()
},
"anki_generation" => {
config.prompts.anki_generation_prompt.clone()
},
_ => {
config.prompts.analysis_prompt.clone() // 默认为分析
}
};
// 替换占位符
base_prompt.replace("{subject}", subject)
},
_ => {
// 如果无法从数据库获取配置,使用默认提示词
self.get_fallback_prompt(subject, task_type)
}
}
}
// 备用提示词(当数据库配置不可用时使用)
fn get_fallback_prompt(&self, subject: &str, task_type: &str) -> String {
match task_type {
"model1" | "ocr" | "classification" => {
format!("你是一个{}题目分析专家。请识别图片中的{}题目文字内容,并分析题目类型和相关知识点标签。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,不要使用LaTeX格式\n2. 数学公式用普通文字描述\n3. 保持文本简洁易读\n4. 避免使用特殊LaTeX命令\n\n请以JSON格式返回结果:{{\"ocr_text\": \"题目文字\", \"tags\": [\"标签1\", \"标签2\"], \"mistake_type\": \"题目类型\"}}", subject, subject)
},
"model2" | "analysis" => {
if subject == "数学" || subject == "物理" || subject == "化学" || subject == "生物" {
format!("你是一个{}教学专家。请仔细分析这道{}错题,提供详细的解题思路和知识点讲解。\n\n【重要】公式格式要求:\n1. 行内公式请使用 $\\text{{公式}}$ 格式\n2. 独立公式请使用 $$\\text{{公式}}$$ 格式\n3. 分数请使用 \\frac{{分子}}{{分母}} 格式\n4. 积分请使用 \\int 格式\n5. 求和请使用 \\sum 格式\n6. 根号请使用 \\sqrt{{}} 格式\n7. 幂次请使用 ^ 符号,如 x^2\n8. 下标请使用 _ 符号,如 x_1\n9. 希腊字母请使用对应的LaTeX命令,如 \\alpha, \\beta\n10. 请确保所有数学表达式都严格按照LaTeX格式书写,避免使用纯文本表示数学公式", subject, subject)
} else {
format!("你是一个{}教学专家。请仔细分析这道{}错题,提供详细的解题思路和知识点讲解。", subject, subject)
}
},
"review" => {
format!("你是一个{}学习分析专家。请分析这些{}错题的共同问题和改进建议。", subject, subject)
},
"consolidated_review" => {
format!("你是一个{}学习分析专家。请对提供的{}错题进行综合复习分析,包括知识点总结、常见错误模式识别和学习建议。", subject, subject)
},
"chat" => {
if subject == "数学" || subject == "物理" || subject == "化学" || subject == "生物" {
format!("基于这道{}题目,请回答学生的问题。\n\n【重要】公式格式要求:\n1. 行内公式请使用 $公式$ 格式\n2. 独立公式请使用 $$公式$$ 格式\n3. 分数请使用 \\frac{{分子}}{{分母}} 格式\n4. 积分请使用 \\int 格式\n5. 求和请使用 \\sum 格式\n6. 根号请使用 \\sqrt{{}} 格式\n7. 请确保所有数学表达式都严格按照LaTeX格式书写", subject)
} else {
format!("基于这道{}题目,请回答学生的问题。", subject)
}
},
"anki_generation" => {
format!("请根据以下{}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的概念。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。", subject)
},
_ => {
format!("请根据提供的{}题目信息,详细解答问题。", subject)
}
}
}
/// 生成ANKI卡片 - 核心功能
pub async fn generate_anki_cards_from_document(
&self,
document_content: &str,
subject_name: &str,
options: Option<&crate::models::AnkiGenerationOptions>,
) -> Result<Vec<crate::models::AnkiCard>> {
println!("开始生成ANKI卡片: 科目={}, 文档长度={}", subject_name, document_content.len());
// 1. 获取ANKI制卡模型配置
let config = self.get_anki_model_config().await?;
// 2. 获取科目特定的ANKI制卡Prompt
let subject_prompt = self.get_subject_prompt(subject_name, "anki_generation");
// 3. 构建最终的AI指令
let final_prompt = format!("{}\n\n文档内容:\n{}", subject_prompt, document_content);
// 4. 准备AI模型请求
let max_tokens = options.as_ref()
.and_then(|opt| opt.max_tokens)
.unwrap_or(config.max_output_tokens); // 使用配置中的max_output_tokens
let temperature = options.as_ref()
.and_then(|opt| opt.temperature)
.unwrap_or(0.3);
let mut request_body = json!({
"model": config.model,
"messages": [
{
"role": "user",
"content": final_prompt
}
],
"max_tokens": max_tokens,
"temperature": temperature
});
// 如果支持JSON模式,添加response_format
if config.model.starts_with("gpt-") {
request_body["response_format"] = json!({"type": "json_object"});
}
println!("发送ANKI制卡请求到: {}/chat/completions", config.base_url);
// 5. 发送HTTP请求至AI模型
let mut request_builder = self.client
.post(&format!("{}/chat/completions", config.base_url))
.header("Authorization", format!("Bearer {}", config.api_key))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/plain, */*")
.header("Accept-Encoding", "identity") // 禁用压缩,避免二进制响应
.header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
.header("Connection", "keep-alive")
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
if let Ok(parsed_url) = Url::parse(&config.base_url) {
if (parsed_url.scheme() == "http" || parsed_url.scheme() == "https") && parsed_url.host_str().is_some() {
let origin_val = format!("{}://{}", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
let referer_val = format!("{}://{}/", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
request_builder = request_builder
.header("Origin", origin_val)
.header("Referer", referer_val);
}
}
let response = request_builder
.json(&request_body)
.send()
.await
.map_err(|e| {
let error_msg = if e.to_string().contains("timed out") {
format!("ANKI制卡API请求超时: {}", e)
} else if e.to_string().contains("connect") {
format!("无法连接到ANKI制卡API服务器: {}", e)
} else {
format!("ANKI制卡API请求失败: {}", e)
};
AppError::network(error_msg)
})?;
// 6. 处理HTTP响应
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_default();
return Err(AppError::llm(format!("ANKI制卡API请求失败: {} - {}", status, error_text)));
}
let response_json: Value = response.json().await
.map_err(|e| AppError::llm(format!("解析ANKI制卡响应失败: {}", e)))?;
// 7. 提取AI生成的内容
let content_str = response_json["choices"][0]["message"]["content"]
.as_str()
.ok_or_else(|| AppError::llm("无法解析ANKI制卡API响应"))?;
println!("ANKI制卡原始响应: {}", content_str);
// 8. 清理和解析AI返回的JSON数据
let cleaned_content = self.clean_anki_json_response(content_str)?;
println!("清理后的JSON: {}", cleaned_content);
// 9. 反序列化为AnkiCard向量(带容错处理)
let cards: Vec<crate::models::AnkiCard> = self.parse_anki_cards_with_fallback(&cleaned_content, content_str)?;
println!("成功生成 {} 张ANKI卡片", cards.len());
Ok(cards)
}
/// 清理AI返回的ANKI卡片JSON响应
fn clean_anki_json_response(&self, content: &str) -> Result<String> {
let mut cleaned = content.trim().to_string();
// 移除markdown代码块
cleaned = regex::Regex::new(r"```(?:json)?\s*")
.unwrap()
.replace_all(&cleaned, "")
.to_string();
cleaned = regex::Regex::new(r"```\s*$")
.unwrap()
.replace_all(&cleaned, "")
.to_string();
// 移除常见前缀
let prefixes = [
"以下是生成的Anki卡片:", "Anki卡片:", "JSON结果:", "卡片数据:",
"Here are the Anki cards:", "Cards:", "JSON:", "Result:",
];
for prefix in &prefixes {
if cleaned.starts_with(prefix) {
cleaned = cleaned.strip_prefix(prefix).unwrap_or(&cleaned).trim().to_string();
break;
}
}
// 确保是有效的JSON数组格式
if !cleaned.starts_with('[') {
// 尝试找到第一个'['
if let Some(start) = cleaned.find('[') {
cleaned = cleaned[start..].to_string();
} else {
return Err(AppError::llm("无法找到JSON数组开始标记"));
}
}
if !cleaned.ends_with(']') {
// 尝试找到最后一个']'
if let Some(end) = cleaned.rfind(']') {
cleaned = cleaned[..=end].to_string();
} else {
return Err(AppError::llm("无法找到JSON数组结束标记"));
}
}
Ok(cleaned)
}
/// 解析ANKI卡片JSON,带容错处理(自动补充缺失的images字段和兼容question字段)
fn parse_anki_cards_with_fallback(&self, json_str: &str, original_content: &str) -> Result<Vec<crate::models::AnkiCard>> {
// 尝试将JSON字符串解析为通用的Value数组
let mut card_values: Vec<Value> = match serde_json::from_str(json_str) {
Ok(v) => v,
Err(e) => {
// 如果连基本JSON都解析不了,直接返回错误
return Err(AppError::llm(format!("解析ANKI卡片JSON失败: {} - 原始内容: {}", e, original_content)));
}
};
// 遍历每个卡片对象,进行字段兼容性处理
for card_value in &mut card_values {
if let Some(obj) = card_value.as_object_mut() {
// 兼容 "question" 字段 -> "front"
if obj.contains_key("question") && !obj.contains_key("front") {
if let Some(question_val) = obj.remove("question") {
obj.insert("front".to_string(), question_val);
}
}
// 自动补充缺失的 "images" 字段
if !obj.contains_key("images") {
obj.insert("images".to_string(), json!([]));
}
}
}
// 将处理过的Value转换回JSON字符串
let processed_json_str = match serde_json::to_string(&card_values) {
Ok(s) => s,
Err(e) => return Err(AppError::llm(format!("重新序列化卡片数据失败: {}", e))),
};
// 使用处理过的JSON字符串进行最终的反序列化
match serde_json::from_str::<Vec<crate::models::AnkiCard>>(&processed_json_str) {
Ok(cards) => Ok(cards),
Err(e) => {
// 如果仍然失败,说明有其他结构问题
Err(AppError::llm(format!("最终解析ANKI卡片失败: {} - 处理后JSON: {}", e, processed_json_str)))
}
}
}
}
// 提取推理模型的思维链段落
/// 改进的思维链内容提取方法,提供多种策略以提高可靠性
fn extract_reasoning_sections(content: &str) -> Vec<serde_json::Value> {
// 策略1: 尝试标准化的思维链格式提取
if let Some(sections) = extract_standard_cot_format(content) {
return sections;
}
// 策略2: 尝试数字列表格式提取
if let Some(sections) = extract_numbered_list_format(content) {
return sections;
}
// 策略3: 尝试关键词段落格式提取
if let Some(sections) = extract_keyword_sections(content) {
return sections;
}
// 策略4: 尝试markdown格式提取
if let Some(sections) = extract_markdown_sections(content) {
return sections;
}
// 策略5: 回退到语义分割
extract_semantic_sections(content)
}
/// 策略1: 提取标准化的思维链格式(如 "## 步骤1:", "### 分析:", 等)
fn extract_standard_cot_format(content: &str) -> Option<Vec<serde_json::Value>> {
use regex::Regex;
// 匹配标准思维链格式的标题
let cot_patterns = [
r"(?i)^#{1,4}\s*(步骤\s*\d+|问题理解|知识点分析|解题思路|具体步骤|结论总结)[::]?\s*(.*)$",
r"(?i)^(\d+\.\s*(?:问题理解|知识点分析|解题思路|具体步骤|结论总结))[::]?\s*(.*)$",
r"(?i)^(思考过程\s*\d*|分析\s*\d*|推理\s*\d*)[::]\s*(.*)$"
];
for pattern in &cot_patterns {
if let Ok(re) = Regex::new(pattern) {
if re.is_match(content) {
return Some(extract_sections_by_regex(content, &re));
}
}
}
None
}
/// 策略2: 提取数字列表格式(如 "1. 分析", "2. 推理")
fn extract_numbered_list_format(content: &str) -> Option<Vec<serde_json::Value>> {
use regex::Regex;
if let Ok(re) = Regex::new(r"(?m)^(\d+\.\s+.+?)(?=^\d+\.\s|\z)") {
let sections: Vec<_> = re.captures_iter(content)
.enumerate()
.map(|(i, cap)| {
let full_match = cap.get(0).unwrap().as_str();
let lines: Vec<&str> = full_match.lines().collect();
let title = lines.first().unwrap_or(&"").trim();
let content_lines = &lines[1..];
json!({
"title": title,
"content": content_lines.join("\n").trim(),
"section_index": i,
"extraction_method": "numbered_list"
})
})
.collect();
if !sections.is_empty() {
return Some(sections);
}
}
None
}
/// 策略3: 提取关键词段落格式
fn extract_keyword_sections(content: &str) -> Option<Vec<serde_json::Value>> {
let mut sections = Vec::new();
let lines: Vec<&str> = content.lines().collect();
let mut current_section: Option<(String, Vec<String>)> = None;
// 增强的关键词列表
let section_keywords = [
"思考过程", "分析过程", "推理过程", "解题思路", "问题理解",
"知识点分析", "具体步骤", "结论总结", "答案推导", "计算过程",
"观察", "假设", "验证", "解法", "方法", "策略", "思维链",
"第一步", "第二步", "第三步", "最后", "因此", "所以", "综上"
];
for line in lines {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
// 检查是否是段落标题 - 更严格的匹配
let is_section_title = section_keywords.iter().any(|&keyword| {
trimmed.starts_with(keyword) ||
(trimmed.contains(keyword) && (trimmed.ends_with(":") || trimmed.ends_with(":"))) ||
(trimmed.len() < 50 && trimmed.contains(keyword) &&
(trimmed.contains("分析") || trimmed.contains("思考") || trimmed.contains("步骤")))
});
if is_section_title {
// 保存上一个段落
if let Some((title, content_lines)) = current_section.take() {
if !content_lines.is_empty() {
sections.push(json!({
"title": title,
"content": content_lines.join("\n"),
"extraction_method": "keyword_sections"
}));
}
}
// 开始新段落
let title = trimmed.trim_end_matches([':', ':']).to_string();
current_section = Some((title, Vec::new()));
} else if let Some((_, ref mut content_lines)) = current_section {
// 添加到当前段落内容
content_lines.push(trimmed.to_string());
}
}
// 保存最后一个段落
if let Some((title, content_lines)) = current_section {
if !content_lines.is_empty() {
sections.push(json!({
"title": title,
"content": content_lines.join("\n"),
"extraction_method": "keyword_sections"
}));
}
}
if !sections.is_empty() {
Some(sections)
} else {
None
}
}
/// 策略4: 提取markdown格式
fn extract_markdown_sections(content: &str) -> Option<Vec<serde_json::Value>> {
use regex::Regex;
if let Ok(re) = Regex::new(r"(?m)^(#{1,6}\s+.+?)$((?:(?!^#{1,6}\s).)*?)") {
let sections: Vec<_> = re.captures_iter(content)
.enumerate()
.map(|(i, cap)| {
let title = cap.get(1).unwrap().as_str().trim();
let section_content = cap.get(2).unwrap().as_str().trim();
json!({
"title": title.trim_start_matches('#').trim(),
"content": section_content,
"section_index": i,
"extraction_method": "markdown"
})
})
.collect();
if !sections.is_empty() {
return Some(sections);
}
}
None
}
/// 策略5: 语义分割回退方案
fn extract_semantic_sections(content: &str) -> Vec<serde_json::Value> {
let trimmed_content = content.trim();
if trimmed_content.is_empty() {
return vec![];
}
// 尝试按句号或换行符分割
let sentences: Vec<&str> = trimmed_content
.split(|c| c == '。' || c == '.' || c == '\n')
.map(|s| s.trim())
.filter(|s| !s.is_empty() && s.len() > 10) // 过滤太短的内容
.collect();
if sentences.len() > 1 {
// 如果能分割出多个句子,按句子分组
let sections: Vec<_> = sentences
.chunks(2) // 每两个句子一组
.enumerate()
.map(|(i, chunk)| {
json!({
"title": format!("思维片段 {}", i + 1),
"content": chunk.join("。"),
"section_index": i,
"extraction_method": "semantic_fallback"
})
})
.collect();
sections
} else {
// 无法分割,返回整个内容
vec![json!({
"title": "完整推理内容",
"content": trimmed_content,
"section_index": 0,
"extraction_method": "full_content_fallback"
})]
}
}
/// 通用的正则表达式段落提取器
fn extract_sections_by_regex(content: &str, re: ®ex::Regex) -> Vec<serde_json::Value> {
let sections: Vec<_> = re.captures_iter(content)
.enumerate()
.map(|(i, cap)| {
let title = cap.get(1).map(|m| m.as_str()).unwrap_or("未知段落");
let section_content = cap.get(2).map(|m| m.as_str()).unwrap_or("");
json!({
"title": title.trim(),
"content": section_content.trim(),
"section_index": i,
"extraction_method": "regex"
})
})
.collect();
sections
}
// 清理JSON响应内容
fn clean_json_response(content: &str) -> String {
// 移除常见的包装文本
let mut cleaned = content.trim();
// 移除markdown代码块标记
if cleaned.starts_with("```json") {
cleaned = cleaned.strip_prefix("```json").unwrap_or(cleaned).trim();
}
if cleaned.starts_with("```") {
cleaned = cleaned.strip_prefix("```").unwrap_or(cleaned).trim();
}
if cleaned.ends_with("```") {
cleaned = cleaned.strip_suffix("```").unwrap_or(cleaned).trim();
}
// 移除常见的前缀文本
let prefixes_to_remove = [
"以下是JSON格式的结果:",
"JSON结果:",
"结果:",
"答案:",
"这是分析结果:",
];
for prefix in &prefixes_to_remove {
if cleaned.starts_with(prefix) {
cleaned = cleaned.strip_prefix(prefix).unwrap_or(cleaned).trim();
break;
}
}
cleaned.to_string()
}
// 从文本中提取JSON
fn extract_json_from_text(text: &str) -> Option<String> {
// 方法1:查找第一个{到最后一个}
if let Some(start) = text.find('{') {
if let Some(end) = text.rfind('}') {
if end > start {
let json_candidate = &text[start..=end];
// 验证这是一个合理的JSON结构
if json_candidate.contains("ocr_text") || json_candidate.contains("tags") || json_candidate.contains("mistake_type") {
return Some(json_candidate.to_string());
}
}
}
}
// 方法2:查找包含所需字段的JSON对象
let lines: Vec<&str> = text.lines().collect();
for (i, line) in lines.iter().enumerate() {
if line.trim().starts_with('{') {
// 从这一行开始,找到匹配的}
let mut brace_count = 0;
let mut json_lines = Vec::new();
for j in i..lines.len() {
let current_line = lines[j];
json_lines.push(current_line);
for ch in current_line.chars() {
match ch {
'{' => brace_count += 1,
'}' => brace_count -= 1,
_ => {}
}
}
if brace_count == 0 {
let json_candidate = json_lines.join("\n");
if json_candidate.contains("ocr_text") || json_candidate.contains("tags") || json_candidate.contains("mistake_type") {
return Some(json_candidate);
}
break;
}
}
}
}
None
}
// 修复常见的JSON错误
fn fix_common_json_errors(json_str: &str) -> String {
let mut fixed = json_str.to_string();
// 修复常见的转义问题
// 1. 修复单引号为双引号(但要小心不要破坏字符串内容)
// 这个比较复杂,暂时跳过
// 2. 修复未转义的引号
// 在字符串值中查找未转义的引号并转义它们
// 这需要更复杂的解析,暂时使用简单的替换
// 3. 修复尾随逗号
fixed = fixed.replace(",}", "}");
fixed = fixed.replace(",]", "]");
// 4. 修复多余的空白字符
fixed = fixed.replace("\n", " ");
fixed = fixed.replace("\r", " ");
// 5. 修复常见的字段名问题
fixed = fixed.replace("'ocr_text'", "\"ocr_text\"");
fixed = fixed.replace("'tags'", "\"tags\"");
fixed = fixed.replace("'mistake_type'", "\"mistake_type\"");
// 6. 确保字符串值被正确引用
// 这需要更复杂的逻辑,暂时跳过
fixed
}
/// 强化的模型一JSON响应解析函数
/// 使用多层次解析策略,提高稳定性和成功率
fn parse_model1_json_response(content: &str) -> Result<Value> {
println!("开始强化JSON解析,内容长度: {} 字符", content.len());
// 第一层:直接解析(针对格式良好的响应)
if let Ok(json_value) = serde_json::from_str::<Value>(content.trim()) {
if validate_model1_json(&json_value) {
println!("✅ 第一层解析成功:直接解析");
return Ok(json_value);
} else {
println!("⚠️ 第一层解析成功但数据验证失败");
}
}
// 第二层:预处理后解析(清理常见包装和格式问题)
let cleaned_content = enhanced_clean_json_response(content);
println!("第二层:清理后内容: {}", cleaned_content);
if let Ok(json_value) = serde_json::from_str::<Value>(&cleaned_content) {
if validate_model1_json(&json_value) {
println!("✅ 第二层解析成功:预处理后解析");
return Ok(json_value);
}
}
// 第三层:智能提取(从文本中提取JSON结构)
if let Some(extracted_json) = smart_extract_json_from_text(content) {
println!("第三层:提取的JSON: {}", extracted_json);
if let Ok(json_value) = serde_json::from_str::<Value>(&extracted_json) {
if validate_model1_json(&json_value) {
println!("✅ 第三层解析成功:智能提取");
return Ok(json_value);
}
}
}
// 第四层:模式匹配重构(从非结构化内容中重构JSON)
if let Some(reconstructed_json) = reconstruct_json_from_content(content) {
println!("第四层:重构的JSON: {}", reconstructed_json);
if let Ok(json_value) = serde_json::from_str::<Value>(&reconstructed_json) {
if validate_model1_json(&json_value) {
println!("✅ 第四层解析成功:模式匹配重构");
return Ok(json_value);
}
}
}
// 第五层:降级处理(创建带默认值的最小可用JSON)
let fallback_json = create_fallback_json(content);
println!("第五层:降级处理JSON: {}", fallback_json);
if let Ok(json_value) = serde_json::from_str::<Value>(&fallback_json) {
println!("⚠️ 使用降级处理结果");
return Ok(json_value);
}
// 所有解析策略都失败
Err(AppError::llm(format!(
"所有JSON解析策略都失败。原始内容: {}",
content
)))
}
/// 验证模型一JSON响应的数据结构
fn validate_model1_json(json: &Value) -> bool {
// 检查必需字段存在且类型正确
let has_ocr_text = json.get("ocr_text").and_then(|v| v.as_str()).is_some();
let has_tags = json.get("tags").and_then(|v| v.as_array()).is_some();
let has_mistake_type = json.get("mistake_type").and_then(|v| v.as_str()).is_some();
let is_valid = has_ocr_text && has_tags && has_mistake_type;
if !is_valid {
println!("JSON验证失败: ocr_text={}, tags={}, mistake_type={}",
has_ocr_text, has_tags, has_mistake_type);
}
is_valid
}
/// 增强的JSON清理函数
fn enhanced_clean_json_response(content: &str) -> String {
let mut cleaned = content.trim().to_string();
// 移除markdown代码块
cleaned = regex::Regex::new(r"```(?:json)?\s*").unwrap().replace_all(&cleaned, "").to_string();
cleaned = regex::Regex::new(r"```\s*$").unwrap().replace_all(&cleaned, "").to_string();
// 移除常见前缀和后缀
let prefixes = [
"以下是JSON格式的结果:", "JSON结果:", "结果:", "答案:", "分析结果:",
"Here is the JSON:", "JSON:", "Result:", "Output:", "Analysis:",
"根据分析,JSON格式结果如下:", "JSON格式输出:",
];
for prefix in &prefixes {
if cleaned.starts_with(prefix) {
cleaned = cleaned.strip_prefix(prefix).unwrap_or(&cleaned).trim().to_string();
}
}
// 移除常见后缀
let suffixes = [
"以上就是分析结果。", "分析完成。", "希望对您有帮助。",
"That's the analysis.", "Analysis complete.",
];
for suffix in &suffixes {
if cleaned.ends_with(suffix) {
cleaned = cleaned.strip_suffix(suffix).unwrap_or(&cleaned).trim().to_string();
}
}
cleaned
}
/// 智能JSON提取函数
fn smart_extract_json_from_text(text: &str) -> Option<String> {
// 使用正则表达式查找JSON对象
let json_pattern = regex::Regex::new(r#"\{[^{}]*"ocr_text"[^{}]*"tags"[^{}]*"mistake_type"[^{}]*\}"#).unwrap();
if let Some(captures) = json_pattern.find(text) {
return Some(captures.as_str().to_string());
}
// 备用方法:查找花括号包围的内容
let mut brace_depth = 0;
let mut start_pos = None;
let mut end_pos = None;
for (i, ch) in text.char_indices() {
match ch {
'{' => {
if brace_depth == 0 {
start_pos = Some(i);
}
brace_depth += 1;
}
'}' => {
brace_depth -= 1;
if brace_depth == 0 && start_pos.is_some() {
end_pos = Some(i + 1);
break;
}
}
_ => {}
}
}
if let (Some(start), Some(end)) = (start_pos, end_pos) {
let json_candidate = &text[start..end];
// 验证是否包含必需字段
if json_candidate.contains("ocr_text") &&
json_candidate.contains("tags") &&
json_candidate.contains("mistake_type") {
return Some(json_candidate.to_string());
}
}
None
}
/// 从内容中重构JSON(当结构化JSON无法提取时)
fn reconstruct_json_from_content(content: &str) -> Option<String> {
// 使用正则表达式提取各个字段的值
let ocr_pattern = regex::Regex::new(r#"(?i)(?:ocr_text|题目内容|文字内容|题目文字)[":\s]*["']?([^"'\n\r}]+)["']?"#).unwrap();
let tags_pattern = regex::Regex::new(r#"(?i)(?:tags|标签|知识点)[":\s]*\[([^\]]+)\]"#).unwrap();
let type_pattern = regex::Regex::new(r#"(?i)(?:mistake_type|题目类型|类型)[":\s]*["']?([^"'\n\r}]+)["']?"#).unwrap();
let mut ocr_text = "";
let mut tags_text = "";
let mut mistake_type = "";
// 提取OCR文本
if let Some(captures) = ocr_pattern.captures(content) {
ocr_text = captures.get(1).map(|m| m.as_str().trim()).unwrap_or("");
}
// 提取标签
if let Some(captures) = tags_pattern.captures(content) {
tags_text = captures.get(1).map(|m| m.as_str().trim()).unwrap_or("");
}
// 提取错误类型
if let Some(captures) = type_pattern.captures(content) {
mistake_type = captures.get(1).map(|m| m.as_str().trim()).unwrap_or("");
}
// 如果至少提取到一些内容,构建JSON
if !ocr_text.is_empty() || !tags_text.is_empty() || !mistake_type.is_empty() {
// 处理标签字符串
let tags_array = if tags_text.is_empty() {
"[]".to_string()
} else {
let tags: Vec<String> = tags_text
.split(',')
.map(|tag| format!("\"{}\"", tag.trim().trim_matches('"').trim_matches('\'')))
.collect();
format!("[{}]", tags.join(", "))
};
let json = format!(
r#"{{"ocr_text": "{}", "tags": {}, "mistake_type": "{}"}}"#,
ocr_text.replace('"', "\\\""),
tags_array,
mistake_type.replace('"', "\\\"")
);
return Some(json);
}
None
}
/// 创建降级JSON(最后的兜底方案)
fn create_fallback_json(content: &str) -> String {
println!("📋 创建降级JSON,原始内容: '{}'", content);
// 特殊处理空响应或只有符号的响应
if content.trim().is_empty() || content.trim() == "{}" || content.trim() == "[]" {
println!("⚠️ 检测到空响应,生成默认内容");
return format!(
r#"{{"ocr_text": "模型响应为空,无法识别题目内容", "tags": ["API响应异常", "需要人工处理"], "mistake_type": "系统错误"}}"#
);
}
// 尝试从内容中提取一些有用信息作为OCR文本
let mut ocr_content = content
.lines()
.filter(|line| !line.trim().is_empty())
.filter(|line| !line.contains("JSON") && !line.contains("格式"))
.take(3)
.collect::<Vec<_>>()
.join(" ");
// 清理内容
ocr_content = ocr_content.replace('"', "\\\"");
if ocr_content.chars().count() > 200 {
ocr_content = format!("{}...", ocr_content.chars().take(200).collect::<String>());
}
if ocr_content.is_empty() || ocr_content == "{}" {
ocr_content = "无法识别题目内容,模型响应异常".to_string();
}
format!(
r#"{{"ocr_text": "{}", "tags": ["需要人工标注"], "mistake_type": "未分类"}}"#,
ocr_content
)
}
// ==================== RAG相关扩展方法 ====================
impl LLMManager {
/// 获取嵌入模型配置
pub async fn get_embedding_model_config(&self) -> Result<ApiConfig> {
let assignments = self.get_model_assignments().await?;
let embedding_model_id = assignments.embedding_model_config_id
.ok_or_else(|| AppError::configuration("未配置嵌入模型"))?;
let configs = self.get_api_configs().await?;
configs.into_iter()
.find(|config| config.id == embedding_model_id)
.ok_or_else(|| AppError::configuration("找不到嵌入模型配置"))
}
/// 获取重排序模型配置
pub async fn get_reranker_model_config(&self) -> Result<ApiConfig> {
let assignments = self.get_model_assignments().await?;
let reranker_model_id = assignments.reranker_model_config_id
.ok_or_else(|| AppError::configuration("未配置重排序模型"))?;
let configs = self.get_api_configs().await?;
configs.into_iter()
.find(|config| config.id == reranker_model_id)
.ok_or_else(|| AppError::configuration("找不到重排序模型配置"))
}
/// 调用嵌入API生成向量
pub async fn call_embedding_api(&self, texts: Vec<String>, model_config_id: &str) -> Result<Vec<Vec<f32>>> {
println!("🧠 调用嵌入API,文本数量: {}", texts.len());
// 获取API配置
let configs = self.get_api_configs().await?;
let config = configs.iter()
.find(|c| c.id == model_config_id)
.ok_or_else(|| AppError::configuration("找不到嵌入模型配置"))?;
// 解密API密钥
let api_key = self.decrypt_api_key_if_needed(&config.api_key)?;
// 构造请求
let request_body = match config.model_adapter.as_str() {
"openai" | "general" => {
json!({
"model": config.model,
"input": texts,
"encoding_format": "float"
})
}
"claude" => {
// Claude目前不直接支持嵌入,这里返回错误
return Err(AppError::configuration("Claude模型不支持嵌入API"));
}
"deepseek" => {
json!({
"model": config.model,
"input": texts,
"encoding_format": "float"
})
}
_ => {
// 默认使用OpenAI格式
json!({
"model": config.model,
"input": texts,
"encoding_format": "float"
})
}
};
// 发送请求
let url = format!("{}/embeddings", config.base_url.trim_end_matches('/'));
let mut request_builder = self.client
.post(&url)
.header("Authorization", format!("Bearer {}", api_key))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/plain, */*")
.header("Accept-Encoding", "identity") // 禁用压缩,避免二进制响应
.header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
.header("Connection", "keep-alive")
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
if let Ok(parsed_url) = Url::parse(&config.base_url) { // config is the specific model config here
if (parsed_url.scheme() == "http" || parsed_url.scheme() == "https") && parsed_url.host_str().is_some() {
let origin_val = format!("{}://{}", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
let referer_val = format!("{}://{}/", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
request_builder = request_builder
.header("Origin", origin_val)
.header("Referer", referer_val);
}
}
let response = request_builder
.json(&request_body)
.send()
.await
.map_err(|e| AppError::network(format!("嵌入API请求失败: {}", e)))?;
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_default();
return Err(AppError::llm(format!("嵌入API返回错误 {}: {}", status, error_text)));
}
let response_json: Value = response.json().await
.map_err(|e| AppError::llm(format!("解析嵌入API响应失败: {}", e)))?;
// 解析嵌入向量
let data = response_json["data"].as_array()
.ok_or_else(|| AppError::llm("嵌入API响应格式无效:缺少data字段"))?;
let mut embeddings = Vec::new();
for item in data {
let embedding = item["embedding"].as_array()
.ok_or_else(|| AppError::llm("嵌入API响应格式无效:缺少embedding字段"))?;
let vector: Result<Vec<f32>> = embedding.iter()
.map(|v| v.as_f64()
.map(|f| f as f32)
.ok_or_else(|| AppError::llm("嵌入向量包含无效数值")))
.collect();
embeddings.push(vector?);
}
if embeddings.len() != texts.len() {
return Err(AppError::llm("嵌入向量数量与输入文本数量不匹配"));
}
println!("✅ 嵌入API调用成功,返回 {} 个向量", embeddings.len());
Ok(embeddings)
}
/// 调用重排序API
pub async fn call_reranker_api(
&self,
query: String,
chunks: Vec<crate::models::RetrievedChunk>,
model_config_id: &str
) -> Result<Vec<crate::models::RetrievedChunk>> {
println!("🔄 调用重排序API,候选文档数量: {}", chunks.len());
// 获取API配置
let configs = self.get_api_configs().await?;
let config = configs.iter()
.find(|c| c.id == model_config_id)
.ok_or_else(|| AppError::configuration("找不到重排序模型配置"))?;
// 解密API密钥
let api_key = self.decrypt_api_key_if_needed(&config.api_key)?;
// 构造重排序请求
let documents: Vec<String> = chunks.iter()
.map(|chunk| chunk.chunk.text.clone())
.collect();
let request_body = json!({
"model": config.model,
"query": query,
"documents": documents,
"top_k": chunks.len(),
"return_documents": true
});
// 发送请求
let url = format!("{}/rerank", config.base_url.trim_end_matches('/'));
let mut request_builder = self.client
.post(&url)
.header("Authorization", format!("Bearer {}", api_key))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/plain, */*")
.header("Accept-Encoding", "identity") // 禁用压缩,避免二进制响应
.header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
.header("Connection", "keep-alive")
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
if let Ok(parsed_url) = Url::parse(&config.base_url) { // config is the specific model config here
if (parsed_url.scheme() == "http" || parsed_url.scheme() == "https") && parsed_url.host_str().is_some() {
let origin_val = format!("{}://{}", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
let referer_val = format!("{}://{}/", parsed_url.scheme(), parsed_url.host_str().unwrap_or_default());
request_builder = request_builder
.header("Origin", origin_val)
.header("Referer", referer_val);
}
}
let response = request_builder
.json(&request_body)
.send()
.await
.map_err(|e| AppError::network(format!("重排序API请求失败: {}", e)))?;
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_default();
return Err(AppError::llm(format!("重排序API返回错误 {}: {}", status, error_text)));
}
let response_json: Value = response.json().await
.map_err(|e| AppError::llm(format!("解析重排序API响应失败: {}", e)))?;
// 解析重排序结果
let results = response_json["results"].as_array()
.ok_or_else(|| AppError::llm("重排序API响应格式无效:缺少results字段"))?;
let mut reranked_chunks = Vec::new();
for result in results {
let index = result["index"].as_u64()
.ok_or_else(|| AppError::llm("重排序结果缺少index字段"))? as usize;
let relevance_score = result["relevance_score"].as_f64()
.ok_or_else(|| AppError::llm("重排序结果缺少relevance_score字段"))? as f32;
if index < chunks.len() {
let mut reranked_chunk = chunks[index].clone();
reranked_chunk.score = relevance_score;
reranked_chunks.push(reranked_chunk);
}
}
println!("✅ 重排序API调用成功,返回 {} 个重排序结果", reranked_chunks.len());
Ok(reranked_chunks)
}
/// RAG增强的流式模型调用
pub async fn call_rag_enhanced_model_stream(
&self,
analysis_context: &std::collections::HashMap<String, serde_json::Value>,
retrieved_context: Vec<crate::models::RetrievedChunk>,
chat_history: &[ChatMessage],
subject: &str,
enable_chain_of_thought: bool,
image_paths: Option<Vec<String>>, // 🎯 修复:添加图片路径参数
window: Window,
stream_event: &str,
) -> Result<StandardModel2Output> {
println!("🚀 开始RAG增强的流式模型调用");
// 构建增强的上下文
let mut enhanced_context = analysis_context.clone();
// 添加检索到的上下文
if !retrieved_context.is_empty() {
let context_text = retrieved_context.iter()
.enumerate()
.map(|(i, chunk)| {
format!(
"--- 参考信息{} (来源: {}) ---\n{}",
i + 1,
chunk.chunk.metadata.get("file_name").unwrap_or(&"unknown".to_string()),
chunk.chunk.text
)
})
.collect::<Vec<_>>()
.join("\n\n");
enhanced_context.insert("rag_context".to_string(), serde_json::Value::String(context_text));
}
enhanced_context.insert("has_rag_context".to_string(), serde_json::Value::Bool(!retrieved_context.is_empty()));
// 发送RAG来源信息事件到前端
if !retrieved_context.is_empty() {
let rag_sources: Vec<serde_json::Value> = retrieved_context.iter().map(|chunk| {
serde_json::json!({
"document_id": chunk.chunk.document_id,
"file_name": chunk.chunk.metadata.get("file_name").unwrap_or(&"unknown".to_string()),
"chunk_text": chunk.chunk.text,
"score": chunk.score,
"chunk_index": chunk.chunk.chunk_index
})
}).collect();
let rag_sources_event = format!("{}_rag_sources", stream_event);
let rag_payload = serde_json::json!({
"sources": rag_sources
});
// 发送RAG来源信息事件
if let Err(e) = window.emit(&rag_sources_event, &rag_payload) {
println!("⚠️ 发送RAG来源信息事件失败: {}", e);
} else {
println!("✅ RAG来源信息事件已发送: {} 个来源", rag_sources.len());
}
}
// 调用原有的流式模型方法,传入增强的上下文
self.call_unified_model_2_stream(
&enhanced_context,
chat_history,
subject,
enable_chain_of_thought,
image_paths, // 🎯 修复:传递图片路径参数
Some("rag_enhanced_analysis"), // 任务类型标识
window,
stream_event,
).await
}
}
| 128,636 | llm_manager | rs | en | rust | code | {"qsc_code_num_words": 11803, "qsc_code_num_chars": 128636.0, "qsc_code_mean_word_length": 4.97839532, "qsc_code_frac_words_unique": 0.12445988, "qsc_code_frac_chars_top_2grams": 0.00799864, "qsc_code_frac_chars_top_3grams": 0.00888359, "qsc_code_frac_chars_top_4grams": 0.00653506, "qsc_code_frac_chars_dupe_5grams": 0.60901974, "qsc_code_frac_chars_dupe_6grams": 0.55330157, "qsc_code_frac_chars_dupe_7grams": 0.52047311, "qsc_code_frac_chars_dupe_8grams": 0.49395848, "qsc_code_frac_chars_dupe_9grams": 0.46523145, "qsc_code_frac_chars_dupe_10grams": 0.44928523, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01224459, "qsc_code_frac_chars_whitespace": 0.38479897, "qsc_code_size_file_byte": 128636.0, "qsc_code_num_lines": 3210.0, "qsc_code_num_chars_line_max": 519.0, "qsc_code_num_chars_line_mean": 40.07352025, "qsc_code_frac_chars_alphabet": 0.72936806, "qsc_code_frac_chars_comments": 0.05814857, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.47251846, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00861362, "qsc_code_frac_chars_string_length": 0.11924296, "qsc_code_frac_chars_long_word_length": 0.02071709, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00082538, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
000haoji/deep-student | src-tauri/src/commands.rs | use crate::models::{
AnalysisRequest, AnalysisResponse, ContinueChatRequest, ContinueChatResponse,
InitialAnalysisData, SaveMistakeRequest, SaveMistakeResponse,
MistakeItem, ChatMessage, ModelAssignments, AppError, ReviewAnalysisItem,
ReviewSessionResponse, ReviewSession, ReviewChatMessage, StartStreamingAnswerRequest,
SubjectConfig, CreateSubjectConfigRequest, UpdateSubjectConfigRequest,
StartConsolidatedReviewAnalysisRequest, StartConsolidatedReviewAnalysisResponse,
TriggerConsolidatedReviewStreamRequest, ContinueConsolidatedReviewStreamRequest,
ConsolidatedReviewSession, AnkiDocumentGenerationRequest, AnkiDocumentGenerationResponse,
AnkiGenerationOptions, SubLibrary, CreateSubLibraryRequest, UpdateSubLibraryRequest,
RagAddDocumentsRequest, RagAddDocumentsFromContentRequest, GetDocumentsRequest,
RagQueryOptionsWithLibraries, RagQueryOptions, RagQueryResponse,
GenerateMistakeSummaryRequest, GenerateMistakeSummaryResponse,
CustomAnkiTemplate, CreateTemplateRequest, UpdateTemplateRequest, TemplateImportRequest, TemplateExportResponse,
ImageOcrRequest, ImageOcrResponse, CreateImageOcclusionRequest, ImageOcclusionResponse, ImageOcclusionCard,
};
use crate::llm_manager::ApiConfig;
use crate::analysis_service::AnalysisService;
use crate::database::Database;
use crate::file_manager::FileManager;
use std::sync::Arc;
use tauri::{State, Window};
use std::collections::HashMap;
use uuid::Uuid;
type Result<T> = std::result::Result<T, AppError>;
use chrono::Utc;
use serde_json;
// 应用状态
pub struct AppState {
pub analysis_service: Arc<AnalysisService>,
pub database: Arc<Database>,
pub file_manager: Arc<FileManager>,
pub temp_sessions: Arc<tokio::sync::Mutex<HashMap<String, TempSession>>>,
pub llm_manager: Arc<crate::llm_manager::LLMManager>,
pub review_sessions: Arc<tokio::sync::Mutex<HashMap<String, ConsolidatedReviewSession>>>,
pub rag_manager: Arc<crate::rag_manager::RagManager>,
pub image_occlusion_service: Arc<crate::image_occlusion_service::ImageOcclusionService>,
}
#[derive(Debug, Clone)]
pub struct TempSession {
pub temp_id: String,
pub subject: String,
pub question_images: Vec<String>,
pub analysis_images: Vec<String>,
pub user_question: String,
pub ocr_text: String,
pub tags: Vec<String>,
pub mistake_type: String,
pub chat_history: Vec<ChatMessage>,
pub created_at: chrono::DateTime<Utc>,
}
/// 获取模板配置
fn get_template_config(template_id: &str) -> std::result::Result<(String, Vec<String>, String, String, String), String> {
// 内置模板配置(对应前端ankiTemplates.ts)
match template_id {
"minimal-card" => Ok((
"极简卡片".to_string(),
vec!["Front".to_string(), "Back".to_string(), "Notes".to_string()],
r#"<div class="card minimal-card">
<div class="question">{{Front}}</div>
<div class="hint">点击显示答案</div>
</div>"#.to_string(),
r#"<div class="card minimal-card">
<div class="question">{{Front}}</div>
<div class="hint">点击显示答案</div>
<div class="answer">{{Back}}</div>
{{#Notes}}
<div class="notes">
<div class="notes-label">注释:</div>
<div>{{Notes}}</div>
</div>
{{/Notes}}
</div>"#.to_string(),
r#".minimal-card {
font-family: 'Segoe UI', system-ui, sans-serif;
width: 100%;
max-width: 100%;
margin: 0;
padding: 20px;
border-radius: 16px;
background: white;
box-shadow: 0 5px 25px rgba(0,0,0,0.08);
text-align: center;
box-sizing: border-box;
overflow: hidden;
}
.question {
font-size: 20px;
font-weight: 600;
color: #2c3e50;
line-height: 1.4;
margin-bottom: 15px;
word-wrap: break-word;
}
.answer {
font-size: 16px;
color: #27ae60;
padding: 15px;
background: #f9fbfa;
border-radius: 12px;
margin: 20px 0;
border-left: 4px solid #2ecc71;
display: block;
word-wrap: break-word;
}
.hint {
font-size: 12px;
color: #95a5a6;
font-style: italic;
margin-bottom: 10px;
}
.notes {
text-align: left;
margin-top: 15px;
padding: 12px;
background: #f8f9fa;
border-radius: 10px;
font-size: 14px;
color: #7f8c8d;
word-wrap: break-word;
}
.notes-label {
font-weight: 600;
color: #3498db;
margin-bottom: 5px;
}
.card:hover {
box-shadow: 0 8px 30px rgba(0,0,0,0.12);
}"#.to_string(),
)),
"academic-card" => Ok((
"学术卡片".to_string(),
vec!["Front".to_string(), "Back".to_string(), "Example".to_string(), "Source".to_string(), "Tags".to_string()],
r#"<div class="card academic-card">
<div class="header">
<div class="deck-name">{{Deck}}</div>
<div class="card-type">知识卡片</div>
</div>
<div class="question">{{Front}}</div>
</div>"#.to_string(),
r#"<div class="card academic-card">
<div class="header">
<div class="deck-name">{{Deck}}</div>
<div class="card-type">知识卡片</div>
</div>
<div class="question">{{Front}}</div>
<div class="divider"></div>
<div class="answer">
<div class="definition">{{Back}}</div>
{{#Example}}
<div class="example">
<div class="example-label">示例:</div>
<div>{{Example}}</div>
</div>
{{/Example}}
</div>
<div class="footer">
<div class="source">{{Source}}</div>
<div class="tags">{{#Tags}}<span class="tag">{{.}}</span>{{/Tags}}</div>
</div>
</div>"#.to_string(),
r#".academic-card {
font-family: 'Georgia', serif;
width: 100%;
max-width: 100%;
margin: 0;
padding: 20px;
background: #fcfaf7;
border: 1px solid #e6e2dd;
box-shadow: 0 3px 10px rgba(0,0,0,0.05);
box-sizing: border-box;
overflow: hidden;
}
.header {
display: flex;
justify-content: space-between;
margin-bottom: 15px;
font-size: 12px;
color: #95a5a6;
}
.question {
font-size: 20px;
font-weight: bold;
color: #2c3e50;
text-align: center;
margin: 15px 0 20px;
word-wrap: break-word;
}
.divider {
height: 1px;
background: linear-gradient(90deg, transparent, #bdc3c7, transparent);
margin: 10px 0 15px;
}
.definition {
font-size: 16px;
line-height: 1.6;
color: #34495e;
text-align: justify;
word-wrap: break-word;
}
.example {
margin-top: 15px;
padding: 12px;
background: #f8f9fa;
border-left: 3px solid #3498db;
word-wrap: break-word;
}
.example-label {
font-weight: bold;
color: #2980b9;
margin-bottom: 5px;
}
.footer {
display: flex;
justify-content: space-between;
margin-top: 20px;
font-size: 11px;
color: #7f8c8d;
flex-wrap: wrap;
}
.tag {
display: inline-block;
background: #ecf0f1;
padding: 2px 8px;
border-radius: 12px;
margin-left: 3px;
margin-bottom: 2px;
font-size: 10px;
}"#.to_string(),
)),
"code-card" => Ok((
"编程卡片".to_string(),
vec!["Front".to_string(), "Back".to_string(), "Code".to_string()],
r#"<div class="card code-card">
<div class="question">{{Front}}</div>
<div class="hint">// 点击查看解决方案</div>
</div>"#.to_string(),
r#"<div class="card code-card">
<div class="question">{{Front}}</div>
<div class="hint">// 点击查看解决方案</div>
<div class="answer">
{{#Code}}
<pre><code>{{Code}}</code></pre>
{{/Code}}
<div class="explanation">{{Back}}</div>
</div>
</div>"#.to_string(),
r#".code-card {
font-family: 'Fira Code', 'Consolas', monospace;
width: 100%;
max-width: 100%;
margin: 0;
padding: 20px;
background: #2d3748;
color: #cbd5e0;
border-radius: 8px;
box-shadow: 0 10px 25px rgba(0,0,0,0.3);
box-sizing: border-box;
overflow: hidden;
}
.question {
font-size: 16px;
line-height: 1.5;
color: #81e6d9;
margin-bottom: 15px;
word-wrap: break-word;
}
.hint {
text-align: center;
color: #718096;
font-style: italic;
margin-bottom: 15px;
font-size: 12px;
}
pre {
background: #1a202c;
padding: 15px;
border-radius: 6px;
overflow-x: auto;
border-left: 3px solid #63b3ed;
font-size: 12px;
line-height: 1.4;
word-wrap: break-word;
white-space: pre-wrap;
}
code {
color: #feb2b2;
word-wrap: break-word;
}
.explanation {
margin-top: 15px;
padding: 12px;
background: #4a5568;
border-radius: 6px;
font-size: 14px;
line-height: 1.6;
word-wrap: break-word;
}"#.to_string(),
)),
"cloze-card" => Ok((
"填空题卡片".to_string(),
vec!["Text".to_string(), "Hint".to_string(), "Source".to_string()],
r#"<div class="card cloze-card">
<div class="cloze-text">{{cloze:Text}}</div>
{{#Hint}}
<div class="hint-section">
<div class="hint-label">💡 提示:</div>
<div class="hint-content">{{Hint}}</div>
</div>
{{/Hint}}
</div>"#.to_string(),
r#"<div class="card cloze-card">
<div class="cloze-text">{{cloze:Text}}</div>
{{#Hint}}
<div class="hint-section">
<div class="hint-label">💡 提示:</div>
<div class="hint-content">{{Hint}}</div>
</div>
{{/Hint}}
<div class="complete-text">
<div class="complete-label">完整内容:</div>
<div class="complete-content">{{Text}}</div>
</div>
{{#Source}}
<div class="source-section">
<span class="source-label">📚 来源:</span>
<span class="source-content">{{Source}}</span>
</div>
{{/Source}}
</div>"#.to_string(),
r#".cloze-card {
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
width: 100%;
max-width: 100%;
margin: 0;
padding: 24px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 12px;
box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
box-sizing: border-box;
overflow: hidden;
position: relative;
}
.cloze-card::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 12px;
z-index: -1;
}
.cloze-text {
font-size: 18px;
line-height: 1.6;
margin-bottom: 20px;
text-align: justify;
word-wrap: break-word;
}
.cloze {
background: #FFD700;
color: #2c3e50;
padding: 2px 8px;
border-radius: 6px;
font-weight: 600;
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
.hint-section {
background: rgba(255, 255, 255, 0.2);
padding: 12px;
border-radius: 8px;
margin: 15px 0;
border-left: 4px solid #FFD700;
}
.hint-label {
font-weight: 600;
font-size: 14px;
margin-bottom: 5px;
color: #FFD700;
}
.hint-content {
font-size: 14px;
line-height: 1.4;
opacity: 0.9;
}
.complete-text {
background: rgba(255, 255, 255, 0.15);
padding: 15px;
border-radius: 8px;
margin-top: 20px;
border: 1px solid rgba(255, 255, 255, 0.3);
}
.complete-label {
font-weight: 600;
font-size: 14px;
margin-bottom: 8px;
color: #E8F4FD;
}
.complete-content {
font-size: 16px;
line-height: 1.5;
color: #F8F9FA;
}
.source-section {
margin-top: 15px;
padding-top: 10px;
border-top: 1px solid rgba(255, 255, 255, 0.3);
font-size: 12px;
opacity: 0.8;
}
.source-label {
font-weight: 600;
}"#.to_string(),
)),
"choice-card" => Ok((
"选择题卡片".to_string(),
vec!["Front".to_string(), "optiona".to_string(), "optionb".to_string(), "optionc".to_string(), "optiond".to_string(), "correct".to_string(), "explanation".to_string()],
r#"<div class="card choice-card">
<div class="question-section">
<div class="question-label">📝 题目</div>
<div class="question-text">{{Front}}</div>
</div>
<div class="options-section">
<div class="option clickable" onclick="selectOption('A', '{{correct}}')">
<span class="option-label">A</span>
<span class="option-text">{{optiona}}</span>
<span class="feedback" style="display: none;"></span>
</div>
<div class="option clickable" onclick="selectOption('B', '{{correct}}')">
<span class="option-label">B</span>
<span class="option-text">{{optionb}}</span>
<span class="feedback" style="display: none;"></span>
</div>
<div class="option clickable" onclick="selectOption('C', '{{correct}}')">
<span class="option-label">C</span>
<span class="option-text">{{optionc}}</span>
<span class="feedback" style="display: none;"></span>
</div>
<div class="option clickable" onclick="selectOption('D', '{{correct}}')">
<span class="option-label">D</span>
<span class="option-text">{{optiond}}</span>
<span class="feedback" style="display: none;"></span>
</div>
</div>
<div class="instruction">点击选项查看结果</div>
{{#explanation}}
<div class="explanation-section" style="display: none;">
<div class="explanation-label">💡 解析</div>
<div class="explanation-text">{{explanation}}</div>
</div>
{{/explanation}}
<script>
function selectOption(selected, correct) {
const options = document.querySelectorAll('.choice-card .option');
const explanationSection = document.querySelector('.choice-card .explanation-section');
options.forEach(option => {
option.classList.remove('clickable');
option.onclick = null;
const label = option.querySelector('.option-label').textContent;
const feedback = option.querySelector('.feedback');
if (label === selected) {
if (selected === correct) {
option.classList.add('correct-selected');
feedback.innerHTML = '✓ 正确';
feedback.style.color = '#22c55e';
} else {
option.classList.add('wrong-selected');
feedback.innerHTML = '✗ 错误';
feedback.style.color = '#ef4444';
}
feedback.style.display = 'inline';
} else if (label === correct) {
option.classList.add('correct-answer');
const correctFeedback = option.querySelector('.feedback');
correctFeedback.innerHTML = '✓ 正确答案';
correctFeedback.style.color = '#22c55e';
correctFeedback.style.display = 'inline';
}
});
if (explanationSection) {
explanationSection.style.display = 'block';
}
document.querySelector('.choice-card .instruction').textContent =
selected === correct ? '答对了!' : '答错了,正确答案是 ' + correct;
}
</script>
</div>"#.to_string(),
r#"<div class="card choice-card">
<div class="question-section">
<div class="question-label">📝 题目</div>
<div class="question-text">{{Front}}</div>
</div>
<div class="options-section answered">
<div class="option">
<span class="option-label">A</span>
<span class="option-text">{{optiona}}</span>
</div>
<div class="option">
<span class="option-label">B</span>
<span class="option-text">{{optionb}}</span>
</div>
<div class="option">
<span class="option-label">C</span>
<span class="option-text">{{optionc}}</span>
</div>
<div class="option">
<span class="option-label">D</span>
<span class="option-text">{{optiond}}</span>
</div>
</div>
<div class="answer-section">
<div class="answer-label">✅ 正确答案:{{correct}}</div>
</div>
{{#explanation}}
<div class="explanation-section">
<div class="explanation-label">💡 解析</div>
<div class="explanation-text">{{explanation}}</div>
</div>
{{/explanation}}
</div>"#.to_string(),
r#".choice-card {
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
width: 100%;
max-width: 100%;
margin: 0;
padding: 20px;
background: #f8fafc;
border: 2px solid #e2e8f0;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0,0,0,0.08);
box-sizing: border-box;
overflow: hidden;
}
.question-section {
margin-bottom: 20px;
}
.question-label {
font-size: 14px;
font-weight: 600;
color: #3b82f6;
margin-bottom: 8px;
}
.question-text {
font-size: 18px;
font-weight: 500;
color: #1e293b;
line-height: 1.6;
word-wrap: break-word;
}
.options-section {
margin-bottom: 20px;
}
.option {
display: flex;
align-items: center;
padding: 12px;
margin: 8px 0;
background: white;
border: 1px solid #e2e8f0;
border-radius: 8px;
transition: all 0.2s ease;
position: relative;
}
.option.clickable {
cursor: pointer;
}
.option.clickable:hover {
border-color: #3b82f6;
box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
transform: translateY(-1px);
}
.option.correct-selected {
background: #dcfce7;
border-color: #22c55e;
box-shadow: 0 2px 8px rgba(34, 197, 94, 0.2);
}
.option.wrong-selected {
background: #fee2e2;
border-color: #ef4444;
box-shadow: 0 2px 8px rgba(239, 68, 68, 0.2);
}
.option.correct-answer {
background: #f0f9ff;
border-color: #22c55e;
box-shadow: 0 2px 8px rgba(34, 197, 94, 0.15);
}
.feedback {
font-weight: 600;
font-size: 14px;
margin-left: auto;
}
.option-label {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
background: #f1f5f9;
color: #475569;
border-radius: 50%;
font-weight: 600;
font-size: 14px;
margin-right: 12px;
flex-shrink: 0;
}
.option-text {
flex: 1;
font-size: 16px;
color: #334155;
line-height: 1.5;
word-wrap: break-word;
}
.answer-section {
background: #dcfce7;
border: 1px solid #22c55e;
border-radius: 8px;
padding: 12px;
margin: 15px 0;
}
.answer-label {
font-weight: 600;
color: #15803d;
font-size: 16px;
}
.explanation-section {
background: #fffbeb;
border: 1px solid #f59e0b;
border-radius: 8px;
padding: 15px;
margin-top: 15px;
}
.explanation-label {
font-weight: 600;
color: #d97706;
margin-bottom: 8px;
font-size: 14px;
}
.explanation-text {
color: #92400e;
line-height: 1.6;
font-size: 14px;
word-wrap: break-word;
}
.instruction {
text-align: center;
color: #64748b;
font-style: italic;
font-size: 14px;
padding: 10px;
background: #f1f5f9;
border-radius: 6px;
}"#.to_string(),
)),
_ => Err(format!("未知的模板ID: {}", template_id))
}
}
// 分析新错题 - 流式版本
#[tauri::command]
pub async fn analyze_new_mistake_stream(
request: AnalysisRequest,
window: Window,
state: State<'_, AppState>,
) -> Result<AnalysisResponse> {
// 生成临时ID
let temp_id = Uuid::new_v4().to_string();
println!("🚀 启动流式AI解答: {}, 思维链: {}", temp_id, true);
// 安全地截取用户问题,使用字符边界而非字节边界
let question_preview = if request.user_question.chars().count() > 50 {
request.user_question.chars().take(50).collect::<String>() + "..."
} else {
request.user_question.clone()
};
println!("📝 请求信息: 科目={}, 题目图片={}, 解析图片={}, 用户问题={}",
request.subject,
request.question_image_files.len(),
request.analysis_image_files.len(),
question_preview
);
// 保存图片到本地
let mut question_image_paths = Vec::new();
for (index, base64_data) in request.question_image_files.iter().enumerate() {
let file_name = format!("question_{}_{}.jpg", temp_id, index);
let path = state.file_manager.save_image_from_base64(base64_data, &file_name)
.await?;
question_image_paths.push(path);
}
let mut analysis_image_paths = Vec::new();
for (index, base64_data) in request.analysis_image_files.iter().enumerate() {
let file_name = format!("analysis_{}_{}.jpg", temp_id, index);
let path = state.file_manager.save_image_from_base64(base64_data, &file_name)
.await?;
analysis_image_paths.push(path);
}
// 调用分析服务(流式)
let stream_event = format!("analysis_stream_{}", temp_id);
let analysis_result = state.analysis_service.analyze_mistake_stream(
&question_image_paths,
&request.user_question,
&request.subject,
window,
&stream_event,
).await?;
// 创建临时会话
let temp_session = TempSession {
temp_id: temp_id.clone(),
subject: request.subject,
question_images: question_image_paths,
analysis_images: analysis_image_paths,
user_question: request.user_question,
ocr_text: analysis_result.ocr_text.clone(),
tags: analysis_result.tags.clone(),
mistake_type: analysis_result.mistake_type.clone(),
chat_history: vec![ChatMessage {
role: "assistant".to_string(),
content: analysis_result.first_answer.clone(),
timestamp: Utc::now(),
thinking_content: None, // 思维链内容由流式事件处理
rag_sources: None,
image_paths: None,
image_base64: None,
}],
created_at: Utc::now(),
};
// 保存临时会话
{
let mut sessions = state.temp_sessions.lock().await;
sessions.insert(temp_id.clone(), temp_session);
}
Ok(AnalysisResponse {
temp_id,
initial_data: InitialAnalysisData {
ocr_text: analysis_result.ocr_text,
tags: analysis_result.tags,
mistake_type: analysis_result.mistake_type,
first_answer: analysis_result.first_answer,
},
})
}
// 分析新错题 - 非流式版本(已废弃,为了兼容性保留)
#[tauri::command]
pub async fn analyze_new_mistake(
_request: AnalysisRequest,
_state: State<'_, AppState>,
) -> Result<AnalysisResponse> {
println!("警告: analyze_new_mistake 非流式版本已废弃");
Err(AppError::validation("非流式版本已废弃,请使用 analyze_new_mistake_stream"))
}
// 继续对话 - 流式版本
#[tauri::command]
pub async fn continue_chat_stream(
request: ContinueChatRequest,
window: Window,
state: State<'_, AppState>,
) -> Result<ContinueChatResponse> {
println!("继续对话(流式): {}", request.temp_id);
// 获取临时会话
let temp_session = {
let sessions = state.temp_sessions.lock().await;
sessions.get(&request.temp_id).cloned()
};
let mut session = temp_session.ok_or("临时会话不存在")?;
// 构建上下文
let mut context = std::collections::HashMap::new();
context.insert("ocr_text".to_string(), serde_json::json!(session.ocr_text));
context.insert("tags".to_string(), serde_json::json!(session.tags));
context.insert("mistake_type".to_string(), serde_json::json!(session.mistake_type));
context.insert("user_question".to_string(), serde_json::json!(session.user_question));
// 启动流式对话
let stream_event = format!("continue_chat_stream_{}", request.temp_id);
// 获取模型配置以判断是否是推理模型
let model_config = state.llm_manager.get_model2_config().await
.map_err(|e| format!("获取模型配置失败: {}", e))?;
// 使用前端传入的思维链设置,如果没有则根据模型类型自动决定
let enable_chain_of_thought = request.enable_chain_of_thought.unwrap_or(model_config.is_reasoning);
let model2_result = state.llm_manager.call_unified_model_2_stream(
&context,
&request.chat_history,
&session.subject,
enable_chain_of_thought,
Some(session.question_images.clone()), // 🎯 修复:传入图片路径给第二模型
Some("基于题目信息继续对话解答用户问题"),
window,
&stream_event,
).await.map_err(|e| format!("流式对话失败: {}", e))?;
// 更新会话的聊天记录
session.chat_history = request.chat_history;
session.chat_history.push(ChatMessage {
role: "assistant".to_string(),
content: model2_result.assistant_message.clone(),
timestamp: Utc::now(),
thinking_content: model2_result.chain_of_thought_details.map(|details| details.to_string()),
rag_sources: None,
image_paths: None,
image_base64: None,
});
// 保存更新后的会话
{
let mut sessions = state.temp_sessions.lock().await;
sessions.insert(request.temp_id, session);
}
Ok(ContinueChatResponse {
new_assistant_message: model2_result.assistant_message,
})
}
// 继续对话 - 非流式版本(已废弃,为了兼容性保留)
#[tauri::command]
pub async fn continue_chat(
_request: ContinueChatRequest,
_state: State<'_, AppState>,
) -> Result<ContinueChatResponse> {
println!("警告: continue_chat 非流式版本已废弃");
Err(AppError::validation("非流式版本已废弃,请使用 continue_chat_stream"))
}
#[tauri::command]
pub async fn save_mistake_from_analysis(
request: SaveMistakeRequest,
state: State<'_, AppState>,
) -> Result<SaveMistakeResponse> {
println!("保存错题分析结果: {}", request.temp_id);
// 获取临时会话
let temp_session = {
let sessions = state.temp_sessions.lock().await;
sessions.get(&request.temp_id).cloned()
};
let session = temp_session.ok_or("临时会话不存在")?;
// 创建错题项
let mistake_item = MistakeItem {
id: Uuid::new_v4().to_string(),
subject: session.subject,
created_at: session.created_at,
question_images: session.question_images,
analysis_images: session.analysis_images,
user_question: session.user_question,
ocr_text: session.ocr_text,
tags: session.tags,
mistake_type: session.mistake_type,
status: "summary_required".to_string(), // 需要生成总结才能完成
updated_at: Utc::now(),
chat_history: request.final_chat_history,
mistake_summary: None, // 新增字段:需要后续生成
user_error_analysis: None, // 新增字段:需要后续生成
};
// 保存到数据库
match state.database.save_mistake(&mistake_item) {
Ok(_) => {
// 清理临时会话
{
let mut sessions = state.temp_sessions.lock().await;
sessions.remove(&request.temp_id);
}
Ok(SaveMistakeResponse {
success: true,
final_mistake_item: Some(mistake_item),
})
}
Err(e) => Err(AppError::database(format!("保存错题失败: {}", e))),
}
}
// 错题库管理命令
#[tauri::command]
pub async fn get_mistakes(
subject: Option<String>,
mistake_type: Option<String>,
tags: Option<Vec<String>>,
state: State<'_, AppState>,
) -> Result<Vec<MistakeItem>> {
println!("获取错题列表");
let subject_filter = subject.as_deref();
let type_filter = mistake_type.as_deref();
let tags_filter = tags.as_ref().map(|v| v.as_slice());
match state.database.get_mistakes(subject_filter, type_filter, tags_filter) {
Ok(mistakes) => Ok(mistakes),
Err(e) => Err(AppError::database(format!("获取错题列表失败: {}", e))),
}
}
#[tauri::command]
pub async fn get_review_analyses(
subject: Option<String>,
status: Option<String>,
state: State<'_, AppState>,
) -> Result<Vec<ReviewAnalysisItem>> {
println!("获取回顾分析列表");
let subject_filter = subject.as_deref();
let status_filter = status.as_deref();
match state.database.get_review_analyses(subject_filter, status_filter) {
Ok(analyses) => Ok(analyses),
Err(e) => Err(AppError::database(format!("获取回顾分析列表失败: {}", e))),
}
}
#[tauri::command]
pub async fn delete_review_analysis(
id: String,
state: State<'_, AppState>,
) -> Result<bool> {
println!("删除回顾分析: {}", id);
match state.database.delete_review_analysis(&id) {
Ok(deleted) => {
if deleted {
println!("✅ 回顾分析删除成功: {}", id);
} else {
println!("⚠️ 回顾分析不存在: {}", id);
}
Ok(deleted)
},
Err(e) => {
println!("❌ 删除回顾分析失败: {}", e);
Err(AppError::database(format!("删除回顾分析失败: {}", e)))
},
}
}
#[tauri::command]
pub async fn get_mistake_details(
id: String,
state: State<'_, AppState>,
) -> Result<Option<MistakeItem>> {
println!("获取错题详情: {}", id);
match state.database.get_mistake_by_id(&id) {
Ok(mistake) => Ok(mistake),
Err(e) => Err(AppError::database(format!("获取错题详情失败: {}", e))),
}
}
#[tauri::command]
pub async fn update_mistake(
mistake: MistakeItem,
state: State<'_, AppState>,
) -> Result<MistakeItem> {
println!("更新错题: {}", mistake.id);
match state.database.save_mistake(&mistake) {
Ok(_) => Ok(mistake),
Err(e) => Err(AppError::database(format!("更新错题失败: {}", e))),
}
}
#[tauri::command]
pub async fn delete_mistake(
id: String,
state: State<'_, AppState>,
) -> Result<bool> {
println!("删除错题: {}", id);
// 首先获取错题信息以获取图片路径
if let Ok(Some(mistake)) = state.database.get_mistake_by_id(&id) {
// 删除关联的图片文件
for image_path in mistake.question_images.iter().chain(mistake.analysis_images.iter()) {
if let Err(e) = state.file_manager.delete_image(image_path).await {
println!("删除图片文件失败: {}, 错误: {}", image_path, e);
}
}
}
// 删除数据库记录
match state.database.delete_mistake(&id) {
Ok(deleted) => Ok(deleted),
Err(e) => Err(AppError::database(format!("删除错题失败: {}", e))),
}
}
// 🎯 修复BUG-03:新的错题对话接口,支持显式总结请求参数
#[tauri::command]
pub async fn continue_mistake_chat_stream_v2(
mistakeId: String,
chatHistory: Vec<ChatMessage>,
userMessage: String,
isSummaryRequest: Option<bool>,
enableChainOfThought: Option<bool>,
window: Window,
state: State<'_, AppState>,
) -> Result<ContinueChatResponse> {
println!("在错题详情页继续对话(流式v2): {}, 总结请求: {:?}", mistakeId, isSummaryRequest);
// 获取错题详情
let mistake = state.database.get_mistake_by_id(&mistakeId)
.map_err(|e| AppError::database(format!("获取错题失败: {}", e)))?
.ok_or_else(|| AppError::not_found("错题不存在"))?;
// 构建上下文
let mut context = std::collections::HashMap::new();
context.insert("ocr_text".to_string(), serde_json::json!(mistake.ocr_text));
context.insert("tags".to_string(), serde_json::json!(mistake.tags));
context.insert("user_question".to_string(), serde_json::json!(mistake.user_question));
context.insert("mistake_type".to_string(), serde_json::json!(mistake.mistake_type));
let is_summary_request = isSummaryRequest.unwrap_or(false);
// 根据是否为总结请求选择合适的模型配置
let model_config = if is_summary_request {
println!("🔍 显式总结请求,尝试使用总结模型");
// 获取模型分配配置
let model_assignments = state.llm_manager.get_model_assignments().await
.map_err(|e| format!("获取模型分配失败: {}", e))?;
// 优先使用总结模型,如果未配置则回退到第二模型
let target_model_id = model_assignments.summary_model_config_id
.or(model_assignments.model2_config_id)
.ok_or_else(|| "没有配置可用的总结模型或第二模型".to_string())?;
// 获取目标模型配置
let api_configs = state.llm_manager.get_api_configs().await
.map_err(|e| format!("获取API配置失败: {}", e))?;
let target_config = api_configs.iter()
.find(|config| config.id == target_model_id && config.enabled)
.ok_or_else(|| format!("找不到可用的目标模型配置: {}", target_model_id))?;
println!("📋 总结请求使用模型: {} ({})", target_config.name, target_config.model);
target_config.clone()
} else {
// 常规对话使用第二模型
state.llm_manager.get_model2_config().await
.map_err(|e| format!("获取模型配置失败: {}", e))?
};
// 决定是否启用思维链
let enable_cot = if is_summary_request {
enableChainOfThought.unwrap_or(false)
} else {
enableChainOfThought.unwrap_or(model_config.is_reasoning)
};
// 为多模态模型传递图片信息
let image_paths = if model_config.is_multimodal && !mistake.question_images.is_empty() {
Some(mistake.question_images.clone())
} else {
None
};
// 构建完整的聊天历史(包含新的用户消息)
let mut full_chat_history = chatHistory;
if !userMessage.trim().is_empty() {
full_chat_history.push(ChatMessage {
role: "user".to_string(),
content: userMessage,
timestamp: Utc::now(),
thinking_content: None,
rag_sources: None,
image_paths: None,
image_base64: None,
});
}
// 调用统一AI接口获取回复(流式)
let stream_event = format!("mistake_chat_stream_{}", mistakeId);
let model2_result = if is_summary_request {
// 总结请求使用动态选择的模型配置
state.llm_manager.call_unified_model_stream_with_config(
&model_config,
&context,
&full_chat_history,
&mistake.subject,
enable_cot,
image_paths.clone(),
Some("基于题目信息和聊天记录生成学习总结"),
window,
&stream_event,
).await.map_err(|e| format!("获取AI回复失败: {}", e))?
} else {
// 常规对话使用第二模型
state.llm_manager.call_unified_model_2_stream(
&context,
&full_chat_history,
&mistake.subject,
enable_cot,
image_paths,
Some("基于题目信息和聊天记录进行深入追问解答"),
window,
&stream_event,
).await.map_err(|e| format!("获取AI回复失败: {}", e))?
};
let response = model2_result.assistant_message.clone();
// 🎯 修复总结BUG:过滤掉魔法字符串,避免污染数据库
let filtered_chat_history: Vec<ChatMessage> = full_chat_history.into_iter()
.filter(|msg| !msg.content.contains("[SUMMARY_REQUEST]"))
.collect();
// 更新错题的聊天记录
let mut updated_mistake = mistake;
updated_mistake.chat_history = filtered_chat_history;
// 🎯 关键修复:只有非总结请求才将AI响应添加到聊天记录
if !is_summary_request {
updated_mistake.chat_history.push(ChatMessage {
role: "assistant".to_string(),
content: response.clone(),
timestamp: Utc::now(),
thinking_content: extract_thinking_content_from_model_output(&model2_result),
rag_sources: None,
image_paths: None,
image_base64: None,
});
println!("✅ [聊天记录v2] 普通对话响应已添加到聊天记录");
} else {
println!("🚫 [总结请求v2] 总结响应不添加到聊天记录,避免显示为第二个AI回复");
}
updated_mistake.updated_at = Utc::now();
// 保存更新后的错题
if let Err(e) = state.database.save_mistake(&updated_mistake) {
println!("保存聊天记录失败: {}", e);
}
Ok(ContinueChatResponse {
new_assistant_message: response,
})
}
// 在错题详情页继续对话 - 流式版本(保持向后兼容)
#[tauri::command]
pub async fn continue_mistake_chat_stream(
mistakeId: String,
chatHistory: Vec<ChatMessage>,
enableChainOfThought: Option<bool>,
window: Window,
state: State<'_, AppState>,
) -> Result<ContinueChatResponse> {
println!("在错题详情页继续对话(流式): {}", mistakeId);
// 获取错题详情
let mistake = state.database.get_mistake_by_id(&mistakeId)
.map_err(|e| AppError::database(format!("获取错题失败: {}", e)))?
.ok_or_else(|| AppError::not_found("错题不存在"))?;
// 构建上下文
let mut context = std::collections::HashMap::new();
context.insert("ocr_text".to_string(), serde_json::json!(mistake.ocr_text));
context.insert("tags".to_string(), serde_json::json!(mistake.tags));
context.insert("user_question".to_string(), serde_json::json!(mistake.user_question));
context.insert("mistake_type".to_string(), serde_json::json!(mistake.mistake_type));
// 🎯 新增:检测是否为总结请求
let is_summary_request = chatHistory.last()
.map(|msg| msg.content.contains("[SUMMARY_REQUEST]"))
.unwrap_or(false);
// 🎯 新增:根据是否为总结请求选择合适的模型配置
let model_config = if is_summary_request {
println!("🔍 检测到总结请求,尝试使用总结模型");
// 获取模型分配配置
let model_assignments = state.llm_manager.get_model_assignments().await
.map_err(|e| format!("获取模型分配失败: {}", e))?;
// 优先使用总结模型,如果未配置则回退到第二模型
let target_model_id = model_assignments.summary_model_config_id
.or(model_assignments.model2_config_id)
.ok_or_else(|| "没有配置可用的总结模型或第二模型".to_string())?;
// 获取目标模型配置
let api_configs = state.llm_manager.get_api_configs().await
.map_err(|e| format!("获取API配置失败: {}", e))?;
let target_config = api_configs.iter()
.find(|config| config.id == target_model_id && config.enabled)
.ok_or_else(|| format!("找不到可用的目标模型配置: {}", target_model_id))?;
println!("📋 总结请求使用模型: {} ({})", target_config.name, target_config.model);
target_config.clone()
} else {
// 常规对话使用第二模型
state.llm_manager.get_model2_config().await
.map_err(|e| format!("获取模型配置失败: {}", e))?
};
// 决定是否启用思维链:用户设置优先,否则根据模型类型自动决定
// 总结请求默认不启用思维链(除非用户明确要求)
let enable_cot = if is_summary_request {
enableChainOfThought.unwrap_or(false)
} else {
enableChainOfThought.unwrap_or(model_config.is_reasoning)
};
// 调用统一AI接口获取回复(流式)
let stream_event = format!("mistake_chat_stream_{}", mistakeId);
// 🎯 修复BUG-01:为多模态模型传递图片信息
let image_paths = if model_config.is_multimodal && !mistake.question_images.is_empty() {
Some(mistake.question_images.clone())
} else {
None
};
// 🎯 新增:根据模型配置调用相应的AI接口
let model2_result = if is_summary_request {
// 总结请求使用动态选择的模型配置
state.llm_manager.call_unified_model_stream_with_config(
&model_config,
&context,
&chatHistory,
&mistake.subject,
enable_cot,
image_paths.clone(), // 🎯 修复:传递图片信息
Some("基于题目信息和聊天记录生成学习总结"),
window,
&stream_event,
).await.map_err(|e| format!("获取AI回复失败: {}", e))?
} else {
// 常规对话使用第二模型
state.llm_manager.call_unified_model_2_stream(
&context,
&chatHistory,
&mistake.subject,
enable_cot,
image_paths, // 🎯 修复:传递图片信息
Some("基于题目信息和聊天记录进行深入追问解答"),
window,
&stream_event,
).await.map_err(|e| format!("获取AI回复失败: {}", e))?
};
let response = model2_result.assistant_message.clone(); // Clone to avoid partial move
// 🎯 修复总结BUG:检测是否为总结请求,如果是则不将响应添加到聊天记录
let is_summary_request = chatHistory.last()
.map(|msg| msg.content.contains("[SUMMARY_REQUEST]"))
.unwrap_or(false);
// 🎯 修复BUG-03:过滤掉魔法字符串,避免污染数据库
let filtered_chat_history: Vec<ChatMessage> = chatHistory.into_iter()
.filter(|msg| !msg.content.contains("[SUMMARY_REQUEST]"))
.collect();
// 更新错题的聊天记录
let mut updated_mistake = mistake;
updated_mistake.chat_history = filtered_chat_history;
// 🎯 关键修复:只有非总结请求才将AI响应添加到聊天记录
if !is_summary_request {
updated_mistake.chat_history.push(ChatMessage {
role: "assistant".to_string(),
content: response.clone(),
timestamp: Utc::now(),
thinking_content: extract_thinking_content_from_model_output(&model2_result),
rag_sources: None,
image_paths: None,
image_base64: None,
});
println!("✅ [聊天记录] 普通对话响应已添加到聊天记录");
} else {
println!("🚫 [总结请求] 总结响应不添加到聊天记录,避免显示为第二个AI回复");
}
updated_mistake.updated_at = Utc::now();
// 保存更新后的错题
if let Err(e) = state.database.save_mistake(&updated_mistake) {
println!("保存聊天记录失败: {}", e);
}
Ok(ContinueChatResponse {
new_assistant_message: response,
})
}
// 在错题详情页继续对话 - 非流式版本(已废弃,为了兼容性保留)
#[tauri::command]
pub async fn continue_mistake_chat(
_mistake_id: String,
_chat_history: Vec<ChatMessage>,
_state: State<'_, AppState>,
) -> Result<ContinueChatResponse> {
println!("警告: continue_mistake_chat 非流式版本已废弃");
Err(AppError::validation("非流式版本已废弃,请使用 continue_mistake_chat_stream"))
}
// 回顾分析命令 - 流式版本
#[tauri::command]
pub async fn analyze_review_session_stream(
subject: String,
mistake_ids: Vec<String>,
window: Window,
state: State<'_, AppState>,
) -> Result<ReviewSessionResponse> {
println!("回顾分析(流式): {} 个错题", mistake_ids.len());
// 获取所有选中的错题
let mut mistakes = Vec::new();
for id in &mistake_ids {
match state.database.get_mistake_by_id(id) {
Ok(Some(mistake)) => mistakes.push(mistake),
Ok(None) => return Err(AppError::not_found(format!("错题不存在: {}", id))),
Err(e) => return Err(AppError::database(format!("获取错题失败: {}", e))),
}
}
// 调用分析服务进行回顾分析(流式)
let stream_event = "review_analysis_stream";
let analysis_result = state.analysis_service.analyze_review_session_stream(
&mistakes,
&subject,
window,
stream_event,
).await.map_err(|e| format!("回顾分析失败: {}", e))?;
let review_id = Uuid::new_v4().to_string();
let now = Utc::now();
// 创建回顾分析会话
let review_session = ReviewSession {
id: review_id.clone(),
subject: subject.clone(),
mistake_ids: mistake_ids.clone(),
analysis_summary: analysis_result.clone(),
created_at: now,
updated_at: now,
chat_history: vec![ReviewChatMessage {
id: Uuid::new_v4().to_string(),
session_id: review_id.clone(),
role: "assistant".to_string(),
content: analysis_result.clone(),
timestamp: now,
}],
};
// 保存回顾分析会话到数据库
match state.database.save_review_session(&review_session) {
Ok(_) => {
println!("回顾分析会话已保存: {}", review_id);
},
Err(e) => {
println!("保存回顾分析会话失败: {}", e);
return Err(AppError::database(format!("保存回顾分析会话失败: {}", e)));
}
}
Ok(ReviewSessionResponse {
review_id,
analysis_summary: analysis_result.clone(),
chat_history: Some(vec![ChatMessage {
role: "assistant".to_string(),
content: analysis_result,
timestamp: now,
thinking_content: None,
rag_sources: None,
image_paths: None,
image_base64: None,
}]),
})
}
// 统计和设置命令
#[tauri::command]
pub async fn get_statistics(
state: State<'_, AppState>,
) -> Result<serde_json::Value> {
println!("获取统计信息");
match state.database.get_statistics() {
Ok(stats) => {
let stats_json = serde_json::to_value(stats)
.map_err(|e| format!("序列化统计数据失败: {}", e))?;
Ok(stats_json)
}
Err(e) => Err(AppError::database(format!("获取统计信息失败: {}", e))),
}
}
#[tauri::command]
pub async fn save_setting(
key: String,
value: String,
state: State<'_, AppState>,
) -> Result<()> {
println!("保存设置: {} = {}", key, value);
match state.database.save_setting(&key, &value) {
Ok(_) => Ok(()),
Err(e) => Err(AppError::database(format!("保存设置失败: {}", e))),
}
}
#[tauri::command]
pub async fn get_setting(
key: String,
state: State<'_, AppState>,
) -> Result<Option<String>> {
println!("获取设置: {}", key);
match state.database.get_setting(&key) {
Ok(value) => Ok(value),
Err(e) => Err(AppError::database(format!("获取设置失败: {}", e))),
}
}
#[tauri::command]
pub async fn test_api_connection(
api_key: String,
api_base: String,
model: Option<String>,
state: State<'_, AppState>,
) -> Result<bool> {
println!("测试API连接: {} (模型: {:?})", api_base, model);
// 创建临时的LLM管理器进行测试
let temp_llm = crate::llm_manager::LLMManager::new(state.database.clone(), state.file_manager.clone());
let result = if let Some(model_name) = model.as_deref() {
temp_llm.test_connection_with_model(&api_key, &api_base, Some(model_name)).await
} else {
temp_llm.test_connection(&api_key, &api_base).await
};
match result {
Ok(success) => {
println!("API连接测试结果: {}", success);
if !success {
println!("API连接测试失败:虽然没有异常,但测试返回了false");
}
Ok(success)
},
Err(e) => {
println!("API连接测试错误: {}", e);
// 为了获得更详细的错误信息,我们返回错误而不是false
Err(AppError::validation(format!("API连接测试失败: {}", e)))
}
}
}
#[tauri::command]
pub async fn get_supported_subjects(
state: State<'_, AppState>,
) -> Result<Vec<String>> {
println!("获取支持的科目(从数据库动态获取)");
// 从数据库获取所有已启用的科目配置
match state.database.get_all_subject_configs(true) {
Ok(configs) => {
let subjects: Vec<String> = configs
.into_iter()
.map(|config| config.subject_name)
.collect();
println!("从数据库获取到 {} 个启用的科目: {:?}", subjects.len(), subjects);
// 如果数据库中没有科目配置,返回默认科目列表并记录警告
if subjects.is_empty() {
println!("⚠️ 数据库中没有启用的科目配置,返回默认科目列表");
Ok(vec![
"数学".to_string(),
"物理".to_string(),
"化学".to_string(),
"英语".to_string(),
"语文".to_string(),
"生物".to_string(),
"历史".to_string(),
"地理".to_string(),
"政治".to_string(),
])
} else {
Ok(subjects)
}
}
Err(e) => {
println!("⚠️ 从数据库获取科目配置失败: {},返回默认科目列表", e);
// 数据库查询失败时返回默认科目列表,确保应用可用性
Ok(vec![
"数学".to_string(),
"物理".to_string(),
"化学".to_string(),
"英语".to_string(),
"语文".to_string(),
"生物".to_string(),
"历史".to_string(),
"地理".to_string(),
"政治".to_string(),
])
}
}
}
// 文件管理命令
#[tauri::command]
pub async fn get_image_as_base64(
relative_path: String,
state: State<'_, AppState>,
) -> Result<String> {
println!("获取图片base64: {}", relative_path);
match state.file_manager.get_image_as_base64(&relative_path).await {
Ok(base64_data) => Ok(base64_data),
Err(e) => Err(AppError::database(format!("获取图片失败: {}", e))),
}
}
#[tauri::command]
pub async fn save_image_from_base64_path(
base64_data: String,
file_name: String,
state: State<'_, AppState>,
) -> Result<String> {
println!("从Base64保存图片: {}", file_name);
match state.file_manager.save_image_from_base64(&base64_data, &file_name).await {
Ok(saved_path) => Ok(saved_path),
Err(e) => Err(AppError::database(format!("保存图片失败: {}", e))),
}
}
#[tauri::command]
pub async fn cleanup_orphaned_images(
state: State<'_, AppState>,
) -> Result<Vec<String>> {
println!("清理孤立图片");
match state.file_manager.cleanup_orphaned_images(&state.database).await {
Ok(cleaned_files) => Ok(cleaned_files),
Err(e) => Err(AppError::database(format!("清理孤立图片失败: {}", e))),
}
}
/// 获取图片统计信息
#[tauri::command]
pub async fn get_image_statistics(
state: State<'_, AppState>,
) -> Result<crate::file_manager::ImageStatistics> {
println!("获取图片统计信息");
state.file_manager.get_image_statistics().await
.map_err(|e| AppError::database(format!("获取图片统计失败: {}", e)))
}
// 专用配置管理命令
#[tauri::command]
pub async fn get_api_configurations(
state: State<'_, AppState>,
) -> Result<Vec<ApiConfig>> {
println!("获取API配置列表");
state.llm_manager.get_api_configs().await
}
#[tauri::command]
pub async fn save_api_configurations(
configs: Vec<ApiConfig>,
state: State<'_, AppState>,
) -> Result<()> {
println!("保存API配置列表: {} 个配置", configs.len());
state.llm_manager.save_api_configurations(&configs).await
}
#[tauri::command]
pub async fn get_model_assignments(
state: State<'_, AppState>,
) -> Result<ModelAssignments> {
println!("获取模型分配配置");
state.llm_manager.get_model_assignments().await
}
#[tauri::command]
pub async fn save_model_assignments(
assignments: ModelAssignments,
state: State<'_, AppState>,
) -> Result<()> {
println!("保存模型分配配置");
state.llm_manager.save_model_assignments(&assignments).await
}
// 回顾分析追问 - 流式版本
#[tauri::command]
pub async fn continue_review_chat_stream(
review_id: String,
chat_history: Vec<ChatMessage>,
window: Window,
state: State<'_, AppState>,
) -> Result<ContinueChatResponse> {
println!("回顾分析追问(流式): {}", review_id);
// 获取回顾分析会话
let review_session = state.database.get_review_session_by_id(&review_id)
.map_err(|e| format!("获取回顾分析会话失败: {}", e))?
.ok_or("回顾分析会话不存在")?;
// 构建上下文信息
let mut context = std::collections::HashMap::new();
context.insert("review_type".to_string(), serde_json::json!("回顾分析"));
context.insert("subject".to_string(), serde_json::json!(review_session.subject));
context.insert("mistake_count".to_string(), serde_json::json!(review_session.mistake_ids.len()));
context.insert("analysis_summary".to_string(), serde_json::json!(review_session.analysis_summary));
// 获取模型配置以判断是否是推理模型
let model_config = state.llm_manager.get_model2_config().await
.map_err(|e| format!("获取模型配置失败: {}", e))?;
// 推理模型自动启用思维链,回顾分析追问也需要深度思考
let enable_chain_of_thought = model_config.is_reasoning || true; // 回顾分析追问总是启用思维链
// 🎯 修复:获取相关错题的图片信息
let mut all_image_paths = Vec::new();
for mistake_id in &review_session.mistake_ids {
if let Ok(Some(mistake)) = state.database.get_mistake_by_id(mistake_id) {
all_image_paths.extend(mistake.question_images);
}
}
// 🎯 修复:为多模态模型传递图片信息
let image_paths = if model_config.is_multimodal && !all_image_paths.is_empty() {
Some(all_image_paths)
} else {
None
};
// 调用统一AI接口获取回复(流式)
let stream_event = format!("review_chat_stream_{}", review_id);
let response = state.llm_manager.call_unified_model_2_stream(
&context,
&chat_history,
&review_session.subject,
enable_chain_of_thought,
image_paths, // 🎯 修复:传递相关错题的图片信息
Some("基于回顾分析结果和相关题目图片进行追问解答"),
window,
&stream_event,
).await.map_err(|e| format!("获取AI回复失败: {}", e))?;
// 创建新的聊天消息
let new_message = ReviewChatMessage {
id: Uuid::new_v4().to_string(),
session_id: review_id.clone(),
role: "assistant".to_string(),
content: response.assistant_message.clone(),
timestamp: Utc::now(),
};
// 保存聊天消息到数据库
if let Err(e) = state.database.add_review_chat_message(&new_message) {
println!("保存回顾分析聊天记录失败: {}", e);
}
Ok(ContinueChatResponse {
new_assistant_message: response.assistant_message,
})
}
// 回顾分析追问 - 非流式版本(已废弃,为了兼容性保留)
#[tauri::command]
pub async fn continue_review_chat(
_review_id: String,
_chat_history: Vec<ChatMessage>,
_state: State<'_, AppState>,
) -> Result<ContinueChatResponse> {
println!("警告: continue_review_chat 非流式版本已废弃");
Err(AppError::validation("非流式版本已废弃,请使用 continue_review_chat_stream"))
}
// 分步骤分析:先OCR,再流式AI解答
#[tauri::command]
pub async fn analyze_step_by_step(
request: AnalysisRequest,
state: State<'_, AppState>,
) -> Result<serde_json::Value> {
println!("🚀 开始分步骤分析: 科目={}, 问题图片={}, 解析图片={}, 用户问题长度={}",
request.subject,
request.question_image_files.len(),
request.analysis_image_files.len(),
request.user_question.len()
);
let temp_id = Uuid::new_v4().to_string();
println!("🆔 生成临时ID: {}", temp_id);
// 保存上传的图片文件
let mut question_image_paths = Vec::new();
let mut analysis_image_paths = Vec::new();
// 处理问题图片
println!("📁 开始保存问题图片,共{}张", request.question_image_files.len());
for (index, base64_data) in request.question_image_files.iter().enumerate() {
let filename = format!("question_{}_{}.jpg", temp_id, index);
println!("💾 保存问题图片 {}: {}", index + 1, filename);
match state.file_manager.save_image_from_base64(base64_data, &filename).await {
Ok(path) => {
println!("✅ 问题图片保存成功: {}", path);
question_image_paths.push(path);
},
Err(e) => {
let error_msg = format!("保存问题图片失败: {}", e);
println!("❌ {}", error_msg);
return Err(AppError::database(error_msg));
}
}
}
// 处理解析图片
for (index, base64_data) in request.analysis_image_files.iter().enumerate() {
let filename = format!("analysis_{}_{}.jpg", temp_id, index);
match state.file_manager.save_image_from_base64(base64_data, &filename).await {
Ok(path) => analysis_image_paths.push(path),
Err(e) => return Err(AppError::database(format!("保存解析图片失败: {}", e))),
}
}
// 第一步:只进行OCR和分类分析
println!("🔍 开始调用模型一进行OCR分析,图片数量: {}", question_image_paths.len());
let model1_result = state.llm_manager.call_unified_model_1(
question_image_paths.clone(),
&request.user_question,
&request.subject,
None,
).await.map_err(|e| {
let error_msg = format!("OCR分析失败: {}", e);
println!("❌ {}", error_msg);
AppError::llm(error_msg)
})?;
println!("✅ OCR分析完成");
// 创建临时会话(暂时不包含AI解答)
let temp_session = TempSession {
temp_id: temp_id.clone(),
subject: request.subject.clone(),
question_images: question_image_paths,
analysis_images: analysis_image_paths,
user_question: request.user_question.clone(),
ocr_text: model1_result.ocr_text.clone(),
tags: model1_result.tags.clone(),
mistake_type: model1_result.mistake_type.clone(),
chat_history: vec![], // 暂时为空,等待流式填充
created_at: Utc::now(),
};
// 保存临时会话
{
let mut sessions = state.temp_sessions.lock().await;
sessions.insert(temp_id.clone(), temp_session);
}
// 返回OCR结果
let response = serde_json::json!({
"temp_id": temp_id,
"ocr_result": {
"ocr_text": model1_result.ocr_text,
"tags": model1_result.tags,
"mistake_type": model1_result.mistake_type
}
});
Ok(response)
}
// 启动流式AI解答
#[tauri::command]
pub async fn start_streaming_answer(
request: StartStreamingAnswerRequest,
window: Window,
state: State<'_, AppState>,
) -> Result<()> {
println!("启动流式AI解答: {}, 思维链: {}", request.temp_id, request.enable_chain_of_thought);
// 获取临时会话
let temp_session = {
let sessions = state.temp_sessions.lock().await;
sessions.get(&request.temp_id).cloned()
};
let session = temp_session.ok_or("临时会话不存在")?;
// 构建上下文
let mut context = std::collections::HashMap::new();
context.insert("ocr_text".to_string(), serde_json::json!(session.ocr_text));
context.insert("tags".to_string(), serde_json::json!(session.tags));
context.insert("mistake_type".to_string(), serde_json::json!(session.mistake_type));
context.insert("user_question".to_string(), serde_json::json!(session.user_question));
// 启动流式AI解答
let stream_event = format!("analysis_stream_{}", request.temp_id);
let model2_result = state.llm_manager.call_unified_model_2_stream(
&context,
&[], // 空的聊天历史
&session.subject,
request.enable_chain_of_thought, // 使用传入的思维链参数
Some(session.question_images.clone()), // 🎯 修复:传入图片路径给第二模型
None, // 暂时不使用任务上下文
window,
&stream_event,
).await.map_err(|e| format!("流式AI解答失败: {}", e))?;
// 更新临时会话的聊天历史
{
let mut sessions = state.temp_sessions.lock().await;
if let Some(session) = sessions.get_mut(&request.temp_id) {
session.chat_history.push(ChatMessage {
role: "assistant".to_string(),
content: model2_result.assistant_message,
timestamp: Utc::now(),
thinking_content: None,
rag_sources: None,
image_paths: None,
image_base64: None,
});
}
}
Ok(())
}
// 获取支持的模型适配器选项
#[tauri::command]
pub async fn get_model_adapter_options(
state: State<'_, AppState>,
) -> Result<Vec<serde_json::Value>> {
println!("获取模型适配器选项");
// 尝试从数据库加载自定义适配器选项
match state.database.get_setting("model_adapter_options") {
Ok(Some(options_json)) => {
// 尝试解析自定义配置
match serde_json::from_str::<Vec<serde_json::Value>>(&options_json) {
Ok(mut custom_options) => {
// 如果列表中缺少 Google(Gemini) 选项,则自动补充
let has_google = custom_options.iter().any(|item| {
item.get("value").and_then(|v| v.as_str()) == Some("google")
});
if !has_google {
if let Some(google_item) = get_default_model_adapter_options()
.into_iter()
.find(|item| item.get("value").and_then(|v| v.as_str()) == Some("google"))
{
println!("🚀 未检测到 Google (Gemini) 适配器,已自动添加。");
custom_options.push(google_item);
// 将更新后的列表写回数据库
if let Err(e) = state.database.save_setting(
"model_adapter_options",
&serde_json::to_string(&custom_options).unwrap_or_default(),
) {
println!("⚠️ 写回模型适配器选项失败: {}", e);
}
}
}
if !custom_options.is_empty() {
println!("使用自定义模型适配器选项: {} 个", custom_options.len());
return Ok(custom_options);
}
}
Err(e) => {
println!("解析自定义模型适配器选项失败: {}, 使用默认配置", e);
}
}
}
Ok(None) => {
// 没有自定义配置,使用默认配置
println!("没有找到自定义模型适配器选项,使用默认配置");
}
Err(e) => {
println!("获取模型适配器选项配置失败: {}, 使用默认配置", e);
}
}
// 返回默认的模型适配器选项
let default_options = get_default_model_adapter_options();
// 如果数据库中没有配置,保存默认配置供将来使用
if let Err(e) = state.database.save_setting("model_adapter_options", &serde_json::to_string(&default_options).unwrap_or_default()) {
println!("保存默认模型适配器选项失败: {}", e);
}
Ok(default_options)
}
/// 保存自定义模型适配器选项
#[tauri::command]
pub async fn save_model_adapter_options(
state: State<'_, AppState>,
options: Vec<serde_json::Value>,
) -> Result<()> {
println!("保存自定义模型适配器选项: {} 个", options.len());
// 验证选项格式
for (i, option) in options.iter().enumerate() {
if !option.is_object() ||
option.get("value").is_none() ||
option.get("label").is_none() {
return Err(AppError::validation(format!(
"模型适配器选项 {} 格式无效,必须包含 'value' 和 'label' 字段", i
)));
}
}
let options_json = serde_json::to_string(&options)
.map_err(|e| AppError::validation(format!("序列化模型适配器选项失败: {}", e)))?;
state.database.save_setting("model_adapter_options", &options_json)
.map_err(|e| AppError::database(format!("保存模型适配器选项失败: {}", e)))?;
println!("模型适配器选项保存成功");
Ok(())
}
/// 重置模型适配器选项为默认值
#[tauri::command]
pub async fn reset_model_adapter_options(
state: State<'_, AppState>,
) -> Result<Vec<serde_json::Value>> {
println!("重置模型适配器选项为默认值");
let default_options = get_default_model_adapter_options();
let options_json = serde_json::to_string(&default_options)
.map_err(|e| AppError::validation(format!("序列化默认模型适配器选项失败: {}", e)))?;
state.database.save_setting("model_adapter_options", &options_json)
.map_err(|e| AppError::database(format!("重置模型适配器选项失败: {}", e)))?;
println!("模型适配器选项重置成功");
Ok(default_options)
}
// 科目配置管理命令
#[tauri::command]
pub async fn get_all_subject_configs(
enabled_only: Option<bool>,
state: State<'_, AppState>,
) -> Result<Vec<SubjectConfig>> {
println!("获取科目配置列表: enabled_only={:?}", enabled_only);
state.database.get_all_subject_configs(enabled_only.unwrap_or(false))
.map_err(|e| AppError::database(format!("获取科目配置失败: {}", e)))
}
#[tauri::command]
pub async fn get_subject_config_by_id(
id: String,
state: State<'_, AppState>,
) -> Result<Option<SubjectConfig>> {
println!("获取科目配置详情: {}", id);
state.database.get_subject_config_by_id(&id)
.map_err(|e| AppError::database(format!("获取科目配置失败: {}", e)))
}
#[tauri::command]
pub async fn get_subject_config_by_name(
subject_name: String,
state: State<'_, AppState>,
) -> Result<Option<SubjectConfig>> {
println!("根据科目名称获取配置: {}", subject_name);
state.database.get_subject_config_by_name(&subject_name)
.map_err(|e| AppError::database(format!("获取科目配置失败: {}", e)))
}
#[tauri::command]
pub async fn create_subject_config(
request: CreateSubjectConfigRequest,
state: State<'_, AppState>,
) -> Result<SubjectConfig> {
println!("创建科目配置: {}", request.subject_name);
// 检查科目名称是否已存在
if let Ok(Some(_)) = state.database.get_subject_config_by_name(&request.subject_name) {
return Err(AppError::validation(format!("科目 '{}' 已存在", request.subject_name)));
}
let now = Utc::now();
let config = SubjectConfig {
id: Uuid::new_v4().to_string(),
subject_name: request.subject_name,
display_name: request.display_name,
description: request.description.unwrap_or_default(),
is_enabled: true,
prompts: request.prompts.unwrap_or_default(),
mistake_types: request.mistake_types.unwrap_or_else(|| vec![
"计算错误".to_string(),
"概念理解".to_string(),
"方法应用".to_string(),
"知识遗忘".to_string(),
"审题不清".to_string(),
]),
default_tags: request.default_tags.unwrap_or_else(|| vec![
"基础知识".to_string(),
"重点难点".to_string(),
"易错点".to_string(),
]),
created_at: now,
updated_at: now,
};
state.database.save_subject_config(&config)
.map_err(|e| AppError::database(format!("保存科目配置失败: {}", e)))?;
Ok(config)
}
#[tauri::command]
pub async fn update_subject_config(
request: UpdateSubjectConfigRequest,
state: State<'_, AppState>,
) -> Result<SubjectConfig> {
println!("更新科目配置: {}", request.id);
// 获取现有配置
let mut config = state.database.get_subject_config_by_id(&request.id)
.map_err(|e| AppError::database(format!("获取科目配置失败: {}", e)))?
.ok_or_else(|| AppError::not_found("科目配置不存在"))?;
// 更新字段
if let Some(display_name) = request.display_name {
config.display_name = display_name;
}
if let Some(description) = request.description {
config.description = description;
}
if let Some(is_enabled) = request.is_enabled {
config.is_enabled = is_enabled;
}
if let Some(prompts) = request.prompts {
config.prompts = prompts;
}
if let Some(mistake_types) = request.mistake_types {
config.mistake_types = mistake_types;
}
if let Some(default_tags) = request.default_tags {
config.default_tags = default_tags;
}
config.updated_at = Utc::now();
state.database.save_subject_config(&config)
.map_err(|e| AppError::database(format!("更新科目配置失败: {}", e)))?;
Ok(config)
}
#[tauri::command]
pub async fn delete_subject_config(
id: String,
state: State<'_, AppState>,
) -> Result<bool> {
println!("删除科目配置: {}", id);
state.database.delete_subject_config(&id)
.map_err(|e| AppError::database(format!("删除科目配置失败: {}", e)))
}
#[tauri::command]
pub async fn initialize_default_subject_configs(
state: State<'_, AppState>,
) -> Result<()> {
println!("初始化默认科目配置");
state.database.initialize_default_subject_configs()
.map_err(|e| AppError::database(format!("初始化默认科目配置失败: {}", e)))
}
// ============================================================================
// Batch Operations Commands
// ============================================================================
use crate::batch_operations::{BatchOperationExt, batch_utils};
use serde::{Serialize, Deserialize};
#[derive(Debug, Deserialize)]
pub struct BatchDeleteRequest {
pub mistake_ids: Vec<String>,
}
#[derive(Debug, Serialize)]
pub struct BatchOperationResult {
pub success: bool,
pub processed_count: usize,
pub message: String,
}
#[derive(Debug, Deserialize)]
pub struct BatchUpdateStatusRequest {
pub updates: std::collections::HashMap<String, String>, // mistake_id -> new_status
}
#[derive(Debug, Deserialize)]
pub struct BatchUpdateTagsRequest {
pub updates: std::collections::HashMap<String, Vec<String>>, // mistake_id -> new_tags
}
#[derive(Debug, Deserialize)]
pub struct BatchCleanupRequest {
pub archive_days: Option<i64>, // If provided, archive mistakes older than this many days
}
#[derive(Debug, Serialize)]
pub struct BatchCleanupResult {
pub orphaned_messages_cleaned: usize,
pub mistakes_archived: usize,
pub message: String,
}
#[derive(Debug, Deserialize)]
pub struct BatchExportRequest {
pub mistake_ids: Vec<String>,
}
/// Batch delete multiple mistakes
#[tauri::command]
pub async fn batch_delete_mistakes(
request: BatchDeleteRequest,
state: State<'_, AppState>,
) -> Result<BatchOperationResult> {
println!("批量删除错题: {} 个", request.mistake_ids.len());
if request.mistake_ids.is_empty() {
return Ok(BatchOperationResult {
success: true,
processed_count: 0,
message: "没有需要删除的错题".to_string(),
});
}
let deleted_count = state.database.with_batch_operations(|batch_ops| {
batch_ops.batch_delete_mistakes(&request.mistake_ids)
}).map_err(|e| AppError::database(format!("批量删除错题失败: {}", e)))?;
Ok(BatchOperationResult {
success: true,
processed_count: deleted_count,
message: format!("成功删除 {} 个错题", deleted_count),
})
}
/// Batch update mistake statuses
#[tauri::command]
pub async fn batch_update_mistake_statuses(
request: BatchUpdateStatusRequest,
state: State<'_, AppState>,
) -> Result<BatchOperationResult> {
println!("批量更新错题状态: {} 个", request.updates.len());
if request.updates.is_empty() {
return Ok(BatchOperationResult {
success: true,
processed_count: 0,
message: "没有需要更新的错题状态".to_string(),
});
}
let updated_count = state.database.with_batch_operations(|batch_ops| {
batch_ops.batch_update_mistake_statuses(&request.updates)
}).map_err(|e| AppError::database(format!("批量更新错题状态失败: {}", e)))?;
Ok(BatchOperationResult {
success: true,
processed_count: updated_count,
message: format!("成功更新 {} 个错题的状态", updated_count),
})
}
/// Batch update mistake tags
#[tauri::command]
pub async fn batch_update_mistake_tags(
request: BatchUpdateTagsRequest,
state: State<'_, AppState>,
) -> Result<BatchOperationResult> {
println!("批量更新错题标签: {} 个", request.updates.len());
if request.updates.is_empty() {
return Ok(BatchOperationResult {
success: true,
processed_count: 0,
message: "没有需要更新的错题标签".to_string(),
});
}
let updated_count = state.database.with_batch_operations(|batch_ops| {
batch_ops.batch_update_mistake_tags(&request.updates)
}).map_err(|e| AppError::database(format!("批量更新错题标签失败: {}", e)))?;
Ok(BatchOperationResult {
success: true,
processed_count: updated_count,
message: format!("成功更新 {} 个错题的标签", updated_count),
})
}
/// Batch cleanup operations (orphaned messages, old mistakes)
#[tauri::command]
pub async fn batch_cleanup_database(
request: BatchCleanupRequest,
state: State<'_, AppState>,
) -> Result<BatchCleanupResult> {
println!("批量清理数据库");
let (orphaned_count, archived_count) = batch_utils::bulk_cleanup(
&state.database,
request.archive_days
).map_err(|e| AppError::database(format!("数据库清理失败: {}", e)))?;
let message = if archived_count > 0 {
format!(
"清理完成:删除 {} 条孤立消息,归档 {} 个旧错题",
orphaned_count, archived_count
)
} else {
format!("清理完成:删除 {} 条孤立消息", orphaned_count)
};
Ok(BatchCleanupResult {
orphaned_messages_cleaned: orphaned_count,
mistakes_archived: archived_count,
message,
})
}
/// Batch export mistakes with full data
#[tauri::command]
pub async fn batch_export_mistakes(
request: BatchExportRequest,
state: State<'_, AppState>,
) -> Result<Vec<MistakeItem>> {
println!("批量导出错题: {} 个", request.mistake_ids.len());
if request.mistake_ids.is_empty() {
return Ok(Vec::new());
}
let mistakes = batch_utils::bulk_export_mistakes(
&state.database,
&request.mistake_ids
).map_err(|e| AppError::database(format!("批量导出错题失败: {}", e)))?;
println!("批量导出完成: {} 个错题", mistakes.len());
Ok(mistakes)
}
/// Batch save mistakes (useful for import operations)
#[tauri::command]
pub async fn batch_save_mistakes(
mistakes: Vec<MistakeItem>,
state: State<'_, AppState>,
) -> Result<BatchOperationResult> {
println!("批量保存错题: {} 个", mistakes.len());
if mistakes.is_empty() {
return Ok(BatchOperationResult {
success: true,
processed_count: 0,
message: "没有需要保存的错题".to_string(),
});
}
let saved_count = batch_utils::bulk_import_mistakes(
&state.database,
&mistakes
).map_err(|e| AppError::database(format!("批量保存错题失败: {}", e)))?;
Ok(BatchOperationResult {
success: true,
processed_count: saved_count,
message: format!("成功保存 {} 个错题", saved_count),
})
}
// ============================================================================
// Database Optimization Commands
// ============================================================================
use crate::database_optimizations::DatabaseOptimizationExt;
#[derive(Debug, Deserialize)]
pub struct OptimizedGetMistakesRequest {
pub subject_filter: Option<String>,
pub type_filter: Option<String>,
pub tags_filter: Option<Vec<String>>,
pub limit: Option<u32>,
pub offset: Option<u32>,
}
#[derive(Debug, Deserialize)]
pub struct FullTextSearchRequest {
pub search_term: String,
pub subject_filter: Option<String>,
pub limit: Option<u32>,
}
#[derive(Debug, Deserialize)]
pub struct DateRangeRequest {
pub start_date: String, // RFC3339 format
pub end_date: String, // RFC3339 format
pub subject_filter: Option<String>,
}
/// Get mistakes using optimized queries with tag filtering
#[tauri::command]
pub async fn get_mistakes_optimized(
request: OptimizedGetMistakesRequest,
state: State<'_, AppState>,
) -> Result<Vec<MistakeItem>> {
println!(
"获取错题(优化版): subject={:?}, type={:?}, tags={:?}, limit={:?}, offset={:?}",
request.subject_filter, request.type_filter, request.tags_filter, request.limit, request.offset
);
let mistakes = state.database.get_mistakes_optimized(
request.subject_filter.as_deref(),
request.type_filter.as_deref(),
request.tags_filter.as_deref().map(|v| v.as_ref()),
request.limit,
request.offset,
).map_err(|e| AppError::database(format!("获取错题失败: {}", e)))?;
println!("获取错题(优化版)完成: {} 个", mistakes.len());
Ok(mistakes)
}
/// Get tag statistics using optimized JSON queries
#[tauri::command]
pub async fn get_tag_statistics_optimized(
state: State<'_, AppState>,
) -> Result<std::collections::HashMap<String, i32>> {
println!("获取标签统计(优化版)");
let stats = state.database.get_tag_statistics_optimized()
.map_err(|e| AppError::database(format!("获取标签统计失败: {}", e)))?;
println!("获取标签统计(优化版)完成: {} 个标签", stats.len());
Ok(stats)
}
/// Full-text search across mistake content
#[tauri::command]
pub async fn search_mistakes_fulltext(
request: FullTextSearchRequest,
state: State<'_, AppState>,
) -> Result<Vec<MistakeItem>> {
println!("全文搜索错题: '{}'", request.search_term);
if request.search_term.trim().is_empty() {
return Ok(Vec::new());
}
let mistakes = state.database.search_mistakes_fulltext(
&request.search_term,
request.subject_filter.as_deref(),
request.limit,
).map_err(|e| AppError::database(format!("全文搜索失败: {}", e)))?;
println!("全文搜索完成: {} 个结果", mistakes.len());
Ok(mistakes)
}
/// Get mistakes by date range
#[tauri::command]
pub async fn get_mistakes_by_date_range(
request: DateRangeRequest,
state: State<'_, AppState>,
) -> Result<Vec<MistakeItem>> {
println!("按日期范围获取错题: {} 到 {}", request.start_date, request.end_date);
let mistakes = state.database.get_mistakes_by_date_range(
&request.start_date,
&request.end_date,
request.subject_filter.as_deref(),
).map_err(|e| AppError::database(format!("按日期范围获取错题失败: {}", e)))?;
println!("按日期范围获取错题完成: {} 个", mistakes.len());
Ok(mistakes)
}
/// Create performance indexes for better query speed
#[tauri::command]
pub async fn create_performance_indexes(
state: State<'_, AppState>,
) -> Result<String> {
println!("创建性能索引");
state.database.create_performance_indexes()
.map_err(|e| AppError::database(format!("创建性能索引失败: {}", e)))?;
Ok("性能索引创建成功".to_string())
}
/// Analyze query performance
#[tauri::command]
pub async fn analyze_query_performance(
query: String,
state: State<'_, AppState>,
) -> Result<String> {
println!("分析查询性能: {}", query);
let analysis = state.database.analyze_query_performance(&query)
.map_err(|e| AppError::database(format!("查询性能分析失败: {}", e)))?;
Ok(analysis)
}
/// 从模型输出中提取思维链内容
fn extract_thinking_content_from_model_output(model_output: &crate::models::StandardModel2Output) -> Option<String> {
match &model_output.chain_of_thought_details {
Some(cot_details) => {
// 尝试提取结构化的思维链内容
if let Some(reasoning_content) = cot_details.get("reasoning_content") {
if let Some(reasoning_str) = reasoning_content.as_str() {
if !reasoning_str.trim().is_empty() {
return Some(reasoning_str.to_string());
}
}
}
// 如果有解析的段落,格式化为可读内容
if let Some(parsed_sections) = cot_details.get("parsed_sections") {
if let Some(sections_array) = parsed_sections.as_array() {
if !sections_array.is_empty() {
let formatted_sections = sections_array
.iter()
.filter_map(|section| {
let title = section.get("title")?.as_str()?;
let content = section.get("content")?.as_str()?;
if !content.trim().is_empty() {
Some(format!("## {}\n{}", title, content))
} else {
None
}
})
.collect::<Vec<_>>()
.join("\n\n");
if !formatted_sections.trim().is_empty() {
return Some(formatted_sections);
}
}
}
}
// 回退到完整响应
if let Some(full_response) = cot_details.get("full_response") {
if let Some(response_str) = full_response.as_str() {
// 如果启用了思维链但没有特殊内容,至少返回标记
if cot_details.get("enabled").and_then(|v| v.as_bool()).unwrap_or(false) {
return Some(format!("## 完整推理过程\n{}", response_str));
}
}
}
None
}
None => None,
}
}
/// 获取默认的模型适配器选项
fn get_default_model_adapter_options() -> Vec<serde_json::Value> {
vec![
serde_json::json!({
"value": "general",
"label": "通用模型",
"description": "适用于大多数标准AI模型(如GPT、Claude、通义千问等)",
"is_default": true,
"capabilities": ["chat", "text_generation"],
"supported_features": ["streaming", "multimodal"]
}),
serde_json::json!({
"value": "deepseek-r1",
"label": "DeepSeek-R1",
"description": "专为DeepSeek-R1推理模型优化,支持思维链流式输出",
"is_default": true,
"capabilities": ["reasoning", "chain_of_thought", "problem_solving"],
"supported_features": ["streaming", "thinking_chain", "reasoning_output"]
}),
serde_json::json!({
"value": "google",
"label": "Google Gemini",
"description": "Google Gemini系列模型,支持多模态和高质量文本生成",
"is_default": true,
"capabilities": ["chat", "text_generation", "multimodal", "vision"],
"supported_features": ["streaming", "multimodal", "image_analysis"]
}),
serde_json::json!({
"value": "o1-series",
"label": "OpenAI o1系列",
"description": "OpenAI o1-preview和o1-mini等推理模型",
"is_default": true,
"capabilities": ["reasoning", "problem_solving", "scientific_analysis"],
"supported_features": ["reasoning_tokens", "thinking_process"]
}),
serde_json::json!({
"value": "claude-3-5-sonnet",
"label": "Claude 3.5 Sonnet",
"description": "Anthropic Claude 3.5 Sonnet高性能模型",
"is_default": true,
"capabilities": ["chat", "analysis", "coding", "multimodal"],
"supported_features": ["streaming", "vision", "long_context"]
})
]
}
// ============================================================================
// 回顾分析功能相关命令
// ============================================================================
/// 开始统一回顾分析 - 第一步:创建会话并缓存数据
#[tauri::command]
pub async fn start_consolidated_review_analysis(
request: StartConsolidatedReviewAnalysisRequest,
state: State<'_, AppState>,
) -> Result<StartConsolidatedReviewAnalysisResponse> {
// 安全地截取中文字符串,使用字符边界而非字节边界
let prompt_preview = if request.overall_prompt.chars().count() > 50 {
request.overall_prompt.chars().take(50).collect::<String>() + "..."
} else {
request.overall_prompt.clone()
};
println!("🔄 开始统一回顾分析: 科目={}, 输入长度={}, 问题={}, 错题数量={}",
request.subject,
request.consolidated_input.len(),
prompt_preview,
request.mistake_ids.len()
);
println!("🔍 调试: 错题ID列表={:?}", request.mistake_ids);
// 生成唯一的回顾会话ID
let review_session_id = format!("review_{}", Uuid::new_v4());
// 创建回顾会话数据
let review_session = ConsolidatedReviewSession {
review_session_id: review_session_id.clone(),
subject: request.subject.clone(),
consolidated_input: request.consolidated_input.clone(),
overall_prompt: request.overall_prompt.clone(),
enable_chain_of_thought: request.enable_chain_of_thought,
created_at: Utc::now(),
chat_history: Vec::new(),
mistake_ids: request.mistake_ids.clone(), // 🎯 修复:添加错题ID信息
};
// 存储到临时会话中
{
let mut sessions = state.review_sessions.lock().await;
sessions.insert(review_session_id.clone(), review_session.clone());
}
// 立即保存到数据库(创建初始记录)
let initial_review_analysis = ReviewAnalysisItem {
id: review_session_id.clone(),
name: "回顾分析会话".to_string(), // 默认名称
subject: request.subject.clone(),
created_at: Utc::now(),
updated_at: Utc::now(),
mistake_ids: request.mistake_ids.clone(), // 🔧 修复:使用传入的错题ID列表
consolidated_input: request.consolidated_input.clone(),
user_question: request.overall_prompt.clone(),
status: "pending".to_string(), // 待启动状态,等待流式分析
tags: Vec::new(),
analysis_type: "consolidated_review".to_string(),
chat_history: Vec::new(),
};
match state.database.save_review_analysis(&initial_review_analysis) {
Ok(_) => {
println!("✅ 初始回顾分析记录已保存到数据库");
}
Err(e) => {
println!("❌ 保存初始回顾分析记录失败: {}", e);
// 返回错误,因为数据库保存失败意味着数据不一致
return Err(AppError::database(format!("保存回顾分析失败: {}", e)));
}
}
println!("✅ 回顾分析会话已创建: {}", review_session_id);
Ok(StartConsolidatedReviewAnalysisResponse {
review_session_id,
})
}
/// 触发统一回顾分析流式处理 - 第二步:开始AI分析
#[tauri::command]
pub async fn trigger_consolidated_review_stream(
request: TriggerConsolidatedReviewStreamRequest,
window: Window,
state: State<'_, AppState>,
) -> Result<()> {
println!("🚀 触发统一回顾分析流式处理: {}", request.review_session_id);
// 从缓存中获取会话数据
let session_data = {
let sessions = state.review_sessions.lock().await;
sessions.get(&request.review_session_id)
.ok_or_else(|| AppError::not_found("回顾分析会话不存在"))?
.clone()
};
// 获取回顾分析模型配置
let model_assignments = state.llm_manager.get_model_assignments().await?;
let review_model_config_id = model_assignments.review_analysis_model_config_id
.ok_or_else(|| AppError::configuration("未配置回顾分析模型"))?;
let api_configs = state.llm_manager.get_api_configs().await?;
let review_model_config = api_configs.iter()
.find(|config| config.id == review_model_config_id)
.ok_or_else(|| AppError::configuration("找不到回顾分析模型配置"))?;
// 获取回顾分析提示词
let consolidated_review_prompt = state.llm_manager
.get_subject_prompt(&session_data.subject, "consolidated_review");
// 构造LLM请求消息
let system_message = consolidated_review_prompt.replace("{subject}", &session_data.subject);
let user_message = format!(
"{}\n\n---\n请基于以上所有错题信息,针对以下问题进行分析:\n{}",
session_data.consolidated_input,
session_data.overall_prompt
);
// 构造聊天历史(开始新对话)
let mut chat_history = session_data.chat_history.clone();
chat_history.push(ChatMessage {
role: "user".to_string(),
content: user_message,
timestamp: Utc::now(),
thinking_content: None,
rag_sources: None,
image_paths: None,
image_base64: None,
});
// 准备流式事件名称
let stream_event = format!("review_analysis_stream_{}", request.review_session_id);
let _thinking_stream_event = format!("review_analysis_stream_{}_reasoning", request.review_session_id);
println!("📡 开始调用回顾分析模型: {}", review_model_config.name);
// 调用LLM进行流式分析
let context = std::collections::HashMap::from([
("system_prompt".to_string(), serde_json::Value::String(system_message)),
("task_type".to_string(), serde_json::Value::String("consolidated_review".to_string())),
]);
let _result = state.llm_manager.call_unified_model_2_stream(
&context,
&chat_history,
&session_data.subject,
request.enable_chain_of_thought,
None, // 不需要图片
Some("consolidated_review"),
window,
&stream_event,
).await?;
println!("✅ 回顾分析流式处理已启动");
Ok(())
}
/// 继续统一回顾分析对话
#[tauri::command]
pub async fn continue_consolidated_review_stream(
request: ContinueConsolidatedReviewStreamRequest,
window: Window,
state: State<'_, AppState>,
) -> Result<()> {
println!("💬 继续统一回顾分析对话: {}", request.review_session_id);
// 获取会话数据(支持从数据库恢复)
let session_data = {
let mut sessions = state.review_sessions.lock().await;
// 首先尝试从内存获取
if let Some(session) = sessions.get(&request.review_session_id) {
session.clone()
} else {
// 如果内存中没有,尝试从数据库恢复
println!("🔄 内存中没有找到会话,尝试从数据库恢复: {}", request.review_session_id);
match state.database.get_review_analysis_by_id(&request.review_session_id) {
Ok(Some(review_analysis)) => {
// 从数据库记录重建会话数据
let restored_session = ConsolidatedReviewSession {
review_session_id: review_analysis.id.clone(),
subject: review_analysis.subject.clone(),
consolidated_input: review_analysis.consolidated_input.clone(),
overall_prompt: review_analysis.user_question.clone(),
enable_chain_of_thought: true, // 默认启用思维链
created_at: review_analysis.created_at,
chat_history: review_analysis.chat_history.clone(),
mistake_ids: review_analysis.mistake_ids.clone(), // 🎯 修复:保留错题ID信息
};
// 将恢复的会话存回内存缓存
sessions.insert(request.review_session_id.clone(), restored_session.clone());
println!("✅ 从数据库成功恢复会话: {}", request.review_session_id);
restored_session
},
Ok(None) => {
return Err(AppError::not_found("回顾分析会话不存在"));
},
Err(e) => {
println!("❌ 从数据库加载会话失败: {}", e);
return Err(AppError::database(format!("加载会话失败: {}", e)));
}
}
}
};
// 更新会话聊天历史
{
let mut sessions = state.review_sessions.lock().await;
if let Some(session) = sessions.get_mut(&request.review_session_id) {
session.chat_history = request.chat_history.clone();
}
}
// 获取回顾分析模型配置
let model_assignments = state.llm_manager.get_model_assignments().await?;
let _review_model_config_id = model_assignments.review_analysis_model_config_id
.ok_or_else(|| AppError::configuration("未配置回顾分析模型"))?;
// 获取回顾分析提示词
let consolidated_review_prompt = state.llm_manager
.get_subject_prompt(&session_data.subject, "consolidated_review");
let system_message = consolidated_review_prompt.replace("{subject}", &session_data.subject);
// 准备流式事件名称 - 🎯 修复:追问使用不同的事件名称,参考错题分析实现
let stream_event = format!("review_chat_stream_{}", request.review_session_id);
println!("📡 继续回顾分析对话,消息数量: {}", request.chat_history.len());
println!("🔍 [追问调试] 详细信息:");
println!(" - review_id: {}", request.review_session_id);
println!(" - stream_event: {}", stream_event);
println!(" - subject: {}", session_data.subject);
println!(" - enable_chain_of_thought: {}", request.enable_chain_of_thought);
println!(" - chat_history_length: {}", request.chat_history.len());
println!(" - system_message: {}", system_message);
// 输出聊天历史的详细信息
for (i, msg) in request.chat_history.iter().enumerate() {
println!(" - chat[{}]: {} - {}", i, msg.role,
if msg.content.chars().count() > 100 {
format!("{}...", msg.content.chars().take(100).collect::<String>())
} else {
msg.content.clone()
});
}
// 调用LLM进行流式对话
let context = std::collections::HashMap::from([
("system_prompt".to_string(), serde_json::Value::String(system_message)),
("task_type".to_string(), serde_json::Value::String("consolidated_review_chat".to_string())),
]);
// 🎯 修复:获取相关错题的图片信息
let mut all_image_paths = Vec::new();
for mistake_id in &session_data.mistake_ids {
if let Ok(Some(mistake)) = state.database.get_mistake_by_id(mistake_id) {
all_image_paths.extend(mistake.question_images);
}
}
// 🎯 修复:获取模型配置,为多模态模型传递图片信息
let model_config = state.llm_manager.get_model2_config().await?;
let image_paths = if model_config.is_multimodal && !all_image_paths.is_empty() {
Some(all_image_paths)
} else {
None
};
println!("🚀 [追问调试] 即将调用 call_unified_model_2_stream");
println!("📸 [图片调试] 错题数量: {}, 图片路径数量: {}", session_data.mistake_ids.len(), image_paths.as_ref().map(|p| p.len()).unwrap_or(0));
let result = state.llm_manager.call_unified_model_2_stream(
&context,
&request.chat_history,
&session_data.subject,
request.enable_chain_of_thought,
image_paths, // 🎯 修复:传递相关错题的图片信息
Some("consolidated_review_chat"),
window.clone(),
&stream_event,
).await?;
println!("✅ [追问调试] call_unified_model_2_stream 调用完成,返回内容长度: {}", result.assistant_message.len());
// 流式处理完成后,像错题分析一样自动保存到数据库
{
// 从内存缓存获取session信息
let session_data = {
let sessions = state.review_sessions.lock().await;
sessions.get(&request.review_session_id).cloned()
};
if let Some(session) = session_data {
// 构建更新后的聊天历史
let mut updated_chat_history = request.chat_history.clone();
updated_chat_history.push(ChatMessage {
role: "assistant".to_string(),
content: result.assistant_message.clone(),
timestamp: Utc::now(),
thinking_content: extract_thinking_content_from_model_output(&result),
rag_sources: None,
image_paths: None,
image_base64: None,
});
// 创建ReviewAnalysisItem并保存到数据库(复用错题分析模式)
let review_analysis = ReviewAnalysisItem {
id: request.review_session_id.clone(),
name: format!("回顾分析-{}", Utc::now().format("%Y%m%d")), // ConsolidatedReviewSession没有name字段
subject: session.subject.clone(),
created_at: session.created_at,
updated_at: Utc::now(),
mistake_ids: session.mistake_ids.clone(), // 🎯 修复:使用实际的错题ID列表
consolidated_input: session.consolidated_input.clone(),
user_question: "统一回顾分析".to_string(),
status: "completed".to_string(),
tags: vec![],
analysis_type: "consolidated_review".to_string(),
chat_history: updated_chat_history.clone(),
};
// 保存到数据库(自动保存,像错题分析一样)
if let Err(e) = state.database.save_review_analysis(&review_analysis) {
println!("❌ 自动保存回顾分析到数据库失败: {}", e);
} else {
println!("✅ 自动保存回顾分析到数据库成功");
}
// 同时更新内存缓存
{
let mut sessions = state.review_sessions.lock().await;
if let Some(cached_session) = sessions.get_mut(&request.review_session_id) {
cached_session.chat_history = updated_chat_history;
}
}
}
}
println!("✅ 回顾分析对话继续处理完成");
Ok(())
}
/// 获取回顾分析数据(从数据库加载)- 复用错题分析的加载模式
#[tauri::command]
pub async fn get_review_analysis_by_id(
id: String,
state: State<'_, AppState>,
) -> Result<Option<crate::models::ReviewAnalysisItem>> {
println!("🔍 从数据库获取回顾分析: {}", id);
match state.database.get_review_analysis_by_id(&id) {
Ok(review) => {
if let Some(ref r) = review {
println!("✅ 成功获取回顾分析,聊天记录数量: {}", r.chat_history.len());
} else {
println!("⚠️ 未找到回顾分析: {}", id);
}
Ok(review)
}
Err(e) => {
println!("❌ 获取回顾分析失败: {}", e);
Err(AppError::database(format!("获取回顾分析失败: {}", e)))
}
}
}
/// 获取统一回顾分析会话数据(兼容旧接口)
#[tauri::command]
pub async fn get_consolidated_review_session(
sessionId: String,
state: State<'_, AppState>,
) -> Result<Option<ConsolidatedReviewSession>> {
println!("🔍 获取统一回顾分析会话: {}", sessionId);
// 从缓存中获取会话数据
let sessions = state.review_sessions.lock().await;
let session = sessions.get(&sessionId).cloned();
Ok(session)
}
/// 生成ANKI卡片
#[tauri::command]
pub async fn generate_anki_cards_from_document(
request: AnkiDocumentGenerationRequest,
state: State<'_, AppState>,
) -> Result<AnkiDocumentGenerationResponse> {
println!("🎯 开始生成ANKI卡片: 科目={}, 文档长度={}", request.subject_name, request.document_content.len());
// 调用LLM Manager的ANKI制卡功能
match state.llm_manager.generate_anki_cards_from_document(
&request.document_content,
&request.subject_name,
request.options.as_ref(),
).await {
Ok(cards) => {
println!("✅ ANKI卡片生成成功: {} 张卡片", cards.len());
Ok(AnkiDocumentGenerationResponse {
success: true,
cards,
error_message: None,
})
}
Err(e) => {
println!("❌ ANKI卡片生成失败: {}", e);
Ok(AnkiDocumentGenerationResponse {
success: false,
cards: vec![],
error_message: Some(e.to_string()),
})
}
}
}
/// 从DOCX/PDF文档文件生成ANKI卡片
#[tauri::command]
pub async fn generate_anki_cards_from_document_file(
file_path: String,
subject_name: String,
options: Option<AnkiGenerationOptions>,
state: State<'_, AppState>,
) -> Result<AnkiDocumentGenerationResponse> {
println!("🎯 开始从文档文件生成ANKI卡片: 文件={}, 科目={}", file_path, subject_name);
// 1. 首先解析文档内容
let document_content = match parse_document_from_path(file_path.clone()).await {
Ok(content) => content,
Err(e) => {
println!("❌ 文档解析失败: {}", e);
return Ok(AnkiDocumentGenerationResponse {
success: false,
cards: vec![],
error_message: Some(format!("文档解析失败: {}", e)),
});
}
};
println!("✅ 文档解析成功,提取文本长度: {}", document_content.len());
// 2. 调用ANKI卡片生成
match state.llm_manager.generate_anki_cards_from_document(
&document_content,
&subject_name,
options.as_ref(),
).await {
Ok(cards) => {
println!("✅ ANKI卡片生成成功: {} 张卡片", cards.len());
Ok(AnkiDocumentGenerationResponse {
success: true,
cards,
error_message: None,
})
}
Err(e) => {
println!("❌ ANKI卡片生成失败: {}", e);
Ok(AnkiDocumentGenerationResponse {
success: false,
cards: vec![],
error_message: Some(e.to_string()),
})
}
}
}
/// 从Base64编码的DOCX/PDF文档生成ANKI卡片
#[tauri::command]
pub async fn generate_anki_cards_from_document_base64(
file_name: String,
base64_content: String,
subject_name: String,
options: Option<AnkiGenerationOptions>,
state: State<'_, AppState>,
) -> Result<AnkiDocumentGenerationResponse> {
println!("🎯 开始从Base64文档生成ANKI卡片: 文件={}, 科目={}", file_name, subject_name);
// 1. 首先解析文档内容
let document_content = match parse_document_from_base64(file_name.clone(), base64_content).await {
Ok(content) => content,
Err(e) => {
println!("❌ 文档解析失败: {}", e);
return Ok(AnkiDocumentGenerationResponse {
success: false,
cards: vec![],
error_message: Some(format!("文档解析失败: {}", e)),
});
}
};
println!("✅ 文档解析成功,提取文本长度: {}", document_content.len());
// 2. 调用ANKI卡片生成
match state.llm_manager.generate_anki_cards_from_document(
&document_content,
&subject_name,
options.as_ref(),
).await {
Ok(cards) => {
println!("✅ ANKI卡片生成成功: {} 张卡片", cards.len());
Ok(AnkiDocumentGenerationResponse {
success: true,
cards,
error_message: None,
})
}
Err(e) => {
println!("❌ ANKI卡片生成失败: {}", e);
Ok(AnkiDocumentGenerationResponse {
success: false,
cards: vec![],
error_message: Some(e.to_string()),
})
}
}
}
// ==================== AnkiConnect集成功能 ====================
/// 检查AnkiConnect连接状态
#[tauri::command]
pub async fn check_anki_connect_status() -> Result<bool> {
match crate::anki_connect_service::check_anki_connect_availability().await {
Ok(available) => Ok(available),
Err(e) => Err(AppError::validation(e)),
}
}
/// 获取所有牌组名称
#[tauri::command]
pub async fn get_anki_deck_names() -> Result<Vec<String>> {
match crate::anki_connect_service::get_deck_names().await {
Ok(deck_names) => Ok(deck_names),
Err(e) => Err(AppError::validation(e)),
}
}
/// 获取所有笔记类型名称
#[tauri::command]
pub async fn get_anki_model_names() -> Result<Vec<String>> {
match crate::anki_connect_service::get_model_names().await {
Ok(model_names) => Ok(model_names),
Err(e) => Err(AppError::validation(e)),
}
}
/// 创建牌组(如果不存在)
#[tauri::command]
pub async fn create_anki_deck(deck_name: String) -> Result<()> {
match crate::anki_connect_service::create_deck_if_not_exists(&deck_name).await {
Ok(_) => Ok(()),
Err(e) => Err(AppError::validation(e)),
}
}
/// 将选定的卡片添加到AnkiConnect
#[tauri::command]
pub async fn add_cards_to_anki_connect(
selected_cards: Vec<crate::models::AnkiCard>,
deck_name: String,
mut note_type: String,
) -> Result<Vec<Option<u64>>> {
if selected_cards.is_empty() {
return Err(AppError::validation("没有选择任何卡片".to_string()));
}
if deck_name.trim().is_empty() {
return Err(AppError::validation("牌组名称不能为空".to_string()));
}
if note_type.trim().is_empty() {
return Err(AppError::validation("笔记类型不能为空".to_string()));
}
// 检查是否为填空题
let is_cloze = selected_cards.iter().any(|card| {
let text_content = card.text.as_deref().unwrap_or("");
text_content.contains("{{c") && text_content.contains("}}")
});
if is_cloze {
println!("🔍 检测到填空题,开始验证笔记类型...");
// 检查Anki中是否存在名为"Cloze"的笔记类型
let model_names = crate::anki_connect_service::get_model_names().await
.map_err(|e| AppError::validation(format!("获取Anki笔记类型失败: {}", e)))?;
if !model_names.iter().any(|name| name == "Cloze") {
return Err(AppError::validation(
"Anki中缺少标准的'Cloze'笔记类型,请在Anki中手动添加一个。".to_string()
));
}
// 如果用户选择的不是"Cloze",但又是填空题,则强制使用"Cloze"
if note_type != "Cloze" {
println!("⚠️ 用户选择了非标准的填空题笔记类型 '{}',将强制使用 'Cloze'。", note_type);
note_type = "Cloze".to_string();
}
}
println!("📤 开始添加 {} 张卡片到Anki牌组: {} (笔记类型: {})", selected_cards.len(), deck_name, note_type);
// 首先尝试创建牌组(如果不存在)
if let Err(e) = crate::anki_connect_service::create_deck_if_not_exists(&deck_name).await {
println!("⚠️ 创建牌组失败(可能已存在): {}", e);
}
match crate::anki_connect_service::add_notes_to_anki(selected_cards, deck_name, note_type).await {
Ok(note_ids) => {
let successful_count = note_ids.iter().filter(|id| id.is_some()).count();
let failed_count = note_ids.len() - successful_count;
println!("✅ 卡片添加完成: 成功 {} 张, 失败 {} 张", successful_count, failed_count);
if failed_count > 0 {
println!("⚠️ 部分卡片添加失败,可能是重复卡片或格式错误");
}
Ok(note_ids)
}
Err(e) => {
println!("❌ 添加卡片到Anki失败: {}", e);
Err(AppError::validation(e))
}
}
}
/// 导出选定的卡片为.apkg文件
#[tauri::command]
pub async fn export_cards_as_apkg(
selected_cards: Vec<crate::models::AnkiCard>,
deck_name: String,
note_type: String,
) -> Result<String> {
export_cards_as_apkg_with_template(selected_cards, deck_name, note_type, None).await
}
/// 导出选定的卡片为.apkg文件(支持模板)
#[tauri::command]
pub async fn export_cards_as_apkg_with_template(
selected_cards: Vec<crate::models::AnkiCard>,
deck_name: String,
mut note_type: String,
template_id: Option<String>,
) -> Result<String> {
if selected_cards.is_empty() {
return Err(AppError::validation("没有选择任何卡片".to_string()));
}
// 获取模板配置
let template_config = if let Some(template_id) = template_id {
Some(get_template_config(&template_id).map_err(|e| AppError::validation(e))?)
} else {
None
};
if deck_name.trim().is_empty() {
return Err(AppError::validation("牌组名称不能为空".to_string()));
}
if note_type.trim().is_empty() {
return Err(AppError::validation("笔记类型不能为空".to_string()));
}
// 检查是否为填空题
let is_cloze = selected_cards.iter().any(|card| {
let text_content = card.text.as_deref().unwrap_or("");
text_content.contains("{{c") && text_content.contains("}}")
});
if is_cloze && note_type != "Cloze" {
println!("⚠️ 检测到填空题,但笔记类型不是 'Cloze'。导出时将强制使用 'Cloze' 类型。");
note_type = "Cloze".to_string();
}
println!("📦 开始导出 {} 张卡片为.apkg文件 (笔记类型: {})", selected_cards.len(), note_type);
// 生成默认文件名和路径
let home_dir = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE"))
.unwrap_or_else(|_| ".".to_string());
let output_path = std::path::PathBuf::from(home_dir)
.join("Downloads")
.join(format!("{}.apkg", deck_name.replace("/", "_").replace("\\", "_")));
println!("📁 导出路径: {:?}", output_path);
match crate::apkg_exporter_service::export_cards_to_apkg_with_template(
selected_cards,
deck_name,
note_type,
output_path.clone(),
template_config
).await {
Ok(_) => {
println!("✅ .apkg文件导出成功: {:?}", output_path);
Ok(format!("成功导出到: {}", output_path.display()))
}
Err(e) => {
println!("❌ .apkg文件导出失败: {}", e);
Err(AppError::validation(e))
}
}
}
// =================== Enhanced ANKI Commands ===================
/// 开始文档处理 - 增强版ANKI制卡
#[tauri::command]
pub async fn start_enhanced_document_processing(
document_content: String,
original_document_name: String,
subject_name: Option<String>,
options: AnkiGenerationOptions,
window: Window,
state: State<'_, AppState>,
) -> Result<String> {
// 使用默认科目名称如果未提供
let actual_subject_name = subject_name.unwrap_or_else(|| "通用学习材料".to_string());
println!("🚀 开始增强文档处理: 科目={}, 文档名={}, 内容长度={}",
actual_subject_name, original_document_name, document_content.len());
// 创建增强ANKI服务实例
let enhanced_service = crate::enhanced_anki_service::EnhancedAnkiService::new(
state.database.clone(),
state.llm_manager.clone(),
);
// 构建请求
let request = AnkiDocumentGenerationRequest {
document_content,
subject_name: actual_subject_name,
options: Some(options),
};
// 开始处理
let document_id = enhanced_service.start_document_processing(request, window).await?;
println!("✅ 文档处理已启动: {}", document_id);
Ok(document_id)
}
/// 手动触发任务处理
#[tauri::command]
pub async fn trigger_task_processing(
task_id: String,
window: Window,
state: State<'_, AppState>,
) -> Result<()> {
println!("🎯 触发任务处理: {}", task_id);
let enhanced_service = crate::enhanced_anki_service::EnhancedAnkiService::new(
state.database.clone(),
state.llm_manager.clone(),
);
enhanced_service.trigger_task_processing(task_id, window).await?;
Ok(())
}
/// 获取文档的所有任务
#[tauri::command]
pub async fn get_document_tasks(
documentId: String,
state: State<'_, AppState>,
) -> Result<Vec<crate::models::DocumentTask>> {
println!("📋 获取文档任务列表: {}", documentId);
let enhanced_service = crate::enhanced_anki_service::EnhancedAnkiService::new(
state.database.clone(),
state.llm_manager.clone(),
);
let tasks = enhanced_service.get_document_tasks(documentId)?;
println!("✅ 找到 {} 个任务", tasks.len());
Ok(tasks)
}
/// 获取任务的所有卡片
#[tauri::command]
pub async fn get_task_cards(
task_id: String,
state: State<'_, AppState>,
) -> Result<Vec<crate::models::AnkiCard>> {
println!("🃏 获取任务卡片: {}", task_id);
let enhanced_service = crate::enhanced_anki_service::EnhancedAnkiService::new(
state.database.clone(),
state.llm_manager.clone(),
);
let cards = enhanced_service.get_task_cards(task_id)?;
println!("✅ 找到 {} 张卡片", cards.len());
Ok(cards)
}
/// 更新ANKI卡片
#[tauri::command]
pub async fn update_anki_card(
card: crate::models::AnkiCard,
state: State<'_, AppState>,
) -> Result<()> {
println!("✏️ 更新ANKI卡片: {}", card.id);
// 验证卡片数据
if card.front.trim().is_empty() {
return Err(AppError::validation("卡片正面不能为空"));
}
if card.back.trim().is_empty() {
return Err(AppError::validation("卡片背面不能为空"));
}
let enhanced_service = crate::enhanced_anki_service::EnhancedAnkiService::new(
state.database.clone(),
state.llm_manager.clone(),
);
enhanced_service.update_anki_card(card)?;
println!("✅ 卡片更新成功");
Ok(())
}
/// 删除ANKI卡片
#[tauri::command]
pub async fn delete_anki_card(
card_id: String,
state: State<'_, AppState>,
) -> Result<bool> {
println!("🗑️ 删除ANKI卡片: {}", card_id);
if card_id.is_empty() {
return Err(AppError::validation("卡片ID不能为空"));
}
let enhanced_service = crate::enhanced_anki_service::EnhancedAnkiService::new(
state.database.clone(),
state.llm_manager.clone(),
);
enhanced_service.delete_anki_card(card_id)?;
println!("✅ 卡片删除成功");
Ok(true)
}
/// 删除文档任务及其所有卡片
#[tauri::command]
pub async fn delete_document_task(
task_id: String,
state: State<'_, AppState>,
) -> Result<bool> {
println!("🗑️ 删除文档任务: {}", task_id);
if task_id.is_empty() {
return Err(AppError::validation("任务ID不能为空"));
}
let enhanced_service = crate::enhanced_anki_service::EnhancedAnkiService::new(
state.database.clone(),
state.llm_manager.clone(),
);
enhanced_service.delete_document_task(task_id)?;
println!("✅ 任务删除成功");
Ok(true)
}
/// 删除整个文档会话(所有任务和卡片)
#[tauri::command]
pub async fn delete_document_session(
documentId: String,
state: State<'_, AppState>,
) -> Result<bool> {
println!("🗑️ 删除文档会话: {}", documentId);
if documentId.is_empty() {
return Err(AppError::validation("文档ID不能为空"));
}
let enhanced_service = crate::enhanced_anki_service::EnhancedAnkiService::new(
state.database.clone(),
state.llm_manager.clone(),
);
enhanced_service.delete_document_session(documentId)?;
println!("✅ 文档会话删除成功");
Ok(true)
}
/// 导出选定内容为APKG文件
#[tauri::command]
pub async fn export_apkg_for_selection(
documentId: Option<String>,
taskIds: Option<Vec<String>>,
cardIds: Option<Vec<String>>,
options: AnkiGenerationOptions,
state: State<'_, AppState>,
) -> Result<String> {
println!("📦 导出选定内容为APKG文件");
// 验证至少选择了一种导出内容
if documentId.is_none() && taskIds.is_none() && cardIds.is_none() {
return Err(AppError::validation("必须选择要导出的内容(文档、任务或卡片)"));
}
let enhanced_service = crate::enhanced_anki_service::EnhancedAnkiService::new(
state.database.clone(),
state.llm_manager.clone(),
);
let export_path = enhanced_service.export_apkg_for_selection(
documentId,
taskIds,
cardIds,
options,
).await?;
println!("✅ APKG文件导出成功: {}", export_path);
Ok(export_path)
}
/// 获取文档的所有卡片(用于导出预览)
#[tauri::command]
pub async fn get_document_cards(
documentId: String,
state: State<'_, AppState>,
) -> Result<Vec<crate::models::AnkiCard>> {
println!("📋 获取文档的所有卡片: {}", documentId);
let cards = state.database.get_cards_for_document(&documentId)
.map_err(|e| AppError::database(format!("获取文档卡片失败: {}", e)))?;
println!("✅ 找到 {} 张卡片", cards.len());
Ok(cards)
}
// ==================== RAG知识库管理命令 ====================
use crate::models::{
KnowledgeBaseStatusPayload, DocumentUploadRequest,
RagEnhancedAnalysisRequest, RagEnhancedChatRequest
};
/// 添加文档到知识库
#[tauri::command]
pub async fn rag_add_documents(
request: DocumentUploadRequest,
window: Window,
state: State<'_, AppState>,
) -> Result<String> {
println!("📚 添加文档到知识库: {} 个文件", request.file_paths.len());
// 立即读取文件并转换为内容模式,避免路径失效问题
let mut document_contents = Vec::new();
for (index, file_path) in request.file_paths.iter().enumerate() {
println!("📄 文件 {}: {}", index + 1, file_path);
// 尝试规范化路径
let normalized_path = match std::path::Path::new(file_path).canonicalize() {
Ok(canonical) => {
let canonical_str = canonical.display().to_string();
println!("🔧 规范化路径: {} -> {}", file_path, canonical_str);
canonical_str
}
Err(e) => {
println!("⚠️ 无法规范化路径 {}: {},使用原路径", file_path, e);
file_path.clone()
}
};
let path = std::path::Path::new(&normalized_path);
// 检查文件是否存在
if !path.exists() {
println!("❌ 文件不存在: {} (原路径: {})", normalized_path, file_path);
return Err(AppError::file_system(format!("文件不存在: {} (原路径: {})", normalized_path, file_path)));
}
if !path.is_file() {
println!("❌ 路径不是文件: {} (原路径: {})", normalized_path, file_path);
return Err(AppError::file_system(format!("指定路径不是文件: {} (原路径: {})", normalized_path, file_path)));
}
// 立即读取文件内容,避免后续路径失效
let file_name = path.file_name()
.and_then(|name| name.to_str())
.unwrap_or("unknown")
.to_string();
println!("📚 立即读取文件内容: {}", file_name);
let content = match path.extension().and_then(|ext| ext.to_str()).unwrap_or("").to_lowercase().as_str() {
"txt" | "md" | "markdown" => {
// 文本文件直接读取
match std::fs::read_to_string(&normalized_path) {
Ok(content) => content,
Err(e) => {
println!("❌ 读取文本文件失败: {} - {}", file_name, e);
return Err(AppError::file_system(format!("读取文本文件失败: {} - {}", file_name, e)));
}
}
}
"pdf" | "docx" => {
// 二进制文件读取为base64
match std::fs::read(&normalized_path) {
Ok(bytes) => {
use base64::{Engine as _, engine::general_purpose};
general_purpose::STANDARD.encode(&bytes)
}
Err(e) => {
println!("❌ 读取二进制文件失败: {} - {}", file_name, e);
return Err(AppError::file_system(format!("读取二进制文件失败: {} - {}", file_name, e)));
}
}
}
_ => {
println!("❌ 不支持的文件类型: {}", file_name);
return Err(AppError::validation(format!("不支持的文件类型: {}", file_name)));
}
};
println!("✅ 文件内容读取成功: {} ({} 字符)", file_name, content.len());
document_contents.push(serde_json::json!({
"fileName": file_name,
"content": content
}));
}
if document_contents.is_empty() {
return Err(AppError::validation("文件内容列表不能为空"));
}
// 使用内容模式添加文档,避免路径依赖
let result = state.rag_manager.add_documents_from_content(document_contents, window).await?;
println!("✅ 文档添加完成");
Ok(result)
}
/// 从文件内容添加文档到知识库
#[tauri::command]
pub async fn rag_add_documents_from_content(
documents: Vec<serde_json::Value>,
window: Window,
state: State<'_, AppState>,
) -> Result<String> {
println!("📚 从内容添加文档到知识库: {} 个文件", documents.len());
if documents.is_empty() {
return Err(AppError::validation("文档列表不能为空"));
}
let result = state.rag_manager.add_documents_from_content(documents, window).await?;
println!("✅ 从内容添加文档完成");
Ok(result)
}
/// 获取知识库状态
#[tauri::command]
pub async fn rag_get_knowledge_base_status(
state: State<'_, AppState>,
) -> Result<KnowledgeBaseStatusPayload> {
println!("📊 获取知识库状态");
let status = state.rag_manager.get_knowledge_base_status().await?;
println!("✅ 知识库状态获取完成: {} 个文档, {} 个块", status.total_documents, status.total_chunks);
Ok(status)
}
/// 删除知识库中的文档
#[tauri::command]
pub async fn rag_delete_document(
documentId: String,
state: State<'_, AppState>,
) -> Result<()> {
println!("🗑️ 删除知识库文档: {}", documentId);
if documentId.is_empty() {
return Err(AppError::validation("文档ID不能为空"));
}
state.rag_manager.delete_document_from_knowledge_base(&documentId).await?;
println!("✅ 文档删除完成");
Ok(())
}
/// 查询知识库
#[tauri::command]
pub async fn rag_query_knowledge_base(
query: String,
options: RagQueryOptions,
state: State<'_, AppState>,
) -> Result<RagQueryResponse> {
println!("🔍 查询知识库: '{}'", query);
if query.trim().is_empty() {
return Err(AppError::validation("查询字符串不能为空"));
}
let response = state.rag_manager.query_knowledge_base(&query, options).await?;
println!("✅ 知识库查询完成: {} 个结果", response.retrieved_chunks.len());
Ok(response)
}
/// 获取所有文档列表
#[tauri::command]
pub async fn rag_get_all_documents(
state: State<'_, AppState>,
) -> Result<Vec<serde_json::Value>> {
println!("📋 获取所有文档列表");
let documents = state.rag_manager.get_all_documents().await?;
println!("✅ 文档列表获取完成: {} 个文档", documents.len());
Ok(documents)
}
/// 清空知识库
#[tauri::command]
pub async fn rag_clear_knowledge_base(
state: State<'_, AppState>,
) -> Result<()> {
println!("🧹 清空知识库");
state.rag_manager.clear_knowledge_base().await?;
println!("✅ 知识库清空完成");
Ok(())
}
// ==================== RAG增强的AI分析命令 ====================
/// RAG增强的流式分析
#[tauri::command]
pub async fn start_rag_enhanced_streaming_answer(
request: RagEnhancedAnalysisRequest,
window: Window,
state: State<'_, AppState>,
) -> Result<()> {
println!("🚀 启动RAG增强的流式AI解答: {}, RAG: {:?}",
request.temp_id, request.enable_rag);
// 获取临时会话
let temp_session = {
let sessions = state.temp_sessions.lock().await;
sessions.get(&request.temp_id).cloned()
};
let session = temp_session.ok_or("临时会话不存在")?;
// 如果启用RAG,先进行知识库查询
let retrieved_context = if request.enable_rag.unwrap_or(false) {
let rag_options = request.rag_options.unwrap_or(RagQueryOptions {
top_k: 5,
enable_reranking: Some(false),
});
// 构建查询字符串(结合用户问题和OCR内容)
let query = format!("{} {}", session.user_question, session.ocr_text);
println!("🔍 RAG查询: '{}'", query);
let rag_response = state.rag_manager.query_knowledge_base(&query, rag_options).await?;
rag_response.retrieved_chunks
} else {
Vec::new()
};
// 启动RAG增强的流式AI解答
let stream_event = format!("analysis_stream_{}", request.temp_id);
let model2_result = if !retrieved_context.is_empty() {
// 构建完整的分析上下文
let mut analysis_context = std::collections::HashMap::new();
analysis_context.insert("user_question".to_string(), serde_json::Value::String(session.user_question.clone()));
analysis_context.insert("ocr_text".to_string(), serde_json::Value::String(session.ocr_text.clone()));
analysis_context.insert("tags".to_string(), serde_json::Value::Array(
session.tags.iter().map(|t| serde_json::Value::String(t.clone())).collect()
));
analysis_context.insert("mistake_type".to_string(), serde_json::Value::String(session.mistake_type.clone()));
analysis_context.insert("subject".to_string(), serde_json::Value::String(session.subject.clone()));
// 使用RAG增强的模型调用
state.llm_manager.call_rag_enhanced_model_stream(
&analysis_context,
retrieved_context.clone(),
&[], // 空的聊天历史
&session.subject,
request.enable_chain_of_thought,
Some(session.question_images.clone()), // 🎯 修复:传递图片信息
window,
&stream_event,
).await?
} else {
// 使用普通的模型调用
let mut context = std::collections::HashMap::new();
context.insert("ocr_text".to_string(), serde_json::json!(session.ocr_text));
context.insert("tags".to_string(), serde_json::json!(session.tags));
context.insert("mistake_type".to_string(), serde_json::json!(session.mistake_type));
context.insert("user_question".to_string(), serde_json::json!(session.user_question));
state.llm_manager.call_unified_model_2_stream(
&context,
&[],
&session.subject,
request.enable_chain_of_thought,
Some(session.question_images.clone()), // 🎯 修复:传递图片信息
None,
window,
&stream_event,
).await?
};
// 更新临时会话的聊天历史
{
let mut sessions = state.temp_sessions.lock().await;
if let Some(session) = sessions.get_mut(&request.temp_id) {
// 转换RAG来源信息
let rag_sources = if !retrieved_context.is_empty() {
Some(retrieved_context.iter().map(|chunk| crate::models::RagSourceInfo {
document_id: chunk.chunk.document_id.clone(),
file_name: chunk.chunk.metadata.get("file_name")
.unwrap_or(&"unknown".to_string()).clone(),
chunk_text: chunk.chunk.text.clone(),
score: chunk.score,
chunk_index: chunk.chunk.chunk_index,
}).collect())
} else {
None
};
session.chat_history.push(ChatMessage {
role: "assistant".to_string(),
content: model2_result.assistant_message,
timestamp: Utc::now(),
thinking_content: None,
rag_sources,
image_paths: None,
image_base64: None,
});
}
}
println!("✅ RAG增强的流式分析完成");
Ok(())
}
/// RAG增强的继续对话
#[tauri::command]
pub async fn continue_rag_enhanced_chat_stream(
request: RagEnhancedChatRequest,
window: Window,
state: State<'_, AppState>,
) -> Result<ContinueChatResponse> {
println!("💬 RAG增强的继续对话: {}, RAG: {:?}",
request.temp_id, request.enable_rag);
// 获取临时会话
let temp_session = {
let sessions = state.temp_sessions.lock().await;
sessions.get(&request.temp_id).cloned()
};
let mut session = temp_session.ok_or("临时会话不存在")?;
// 如果启用RAG,进行知识库查询
let retrieved_context = if request.enable_rag.unwrap_or(false) {
let rag_options = request.rag_options.unwrap_or(RagQueryOptions {
top_k: 5,
enable_reranking: Some(false),
});
// 从最新的用户消息中提取查询
let latest_user_message = request.chat_history.iter()
.filter(|msg| msg.role == "user")
.last()
.map(|msg| msg.content.clone())
.unwrap_or_else(|| session.user_question.clone());
println!("🔍 RAG查询: '{}'", latest_user_message);
let rag_response = state.rag_manager.query_knowledge_base(&latest_user_message, rag_options).await?;
rag_response.retrieved_chunks
} else {
Vec::new()
};
// 启动流式对话
let stream_event = format!("continue_chat_stream_{}", request.temp_id);
let model2_result = if !retrieved_context.is_empty() {
// 获取最新用户消息
let latest_user_query = request.chat_history.iter()
.filter(|msg| msg.role == "user")
.last()
.map(|msg| msg.content.clone())
.unwrap_or_else(|| "请继续分析".to_string());
// 构建完整的分析上下文(包含原始错题信息)
let mut analysis_context = std::collections::HashMap::new();
analysis_context.insert("user_question".to_string(), serde_json::Value::String(session.user_question.clone()));
analysis_context.insert("latest_user_query".to_string(), serde_json::Value::String(latest_user_query));
analysis_context.insert("ocr_text".to_string(), serde_json::Value::String(session.ocr_text.clone()));
analysis_context.insert("tags".to_string(), serde_json::Value::Array(
session.tags.iter().map(|t| serde_json::Value::String(t.clone())).collect()
));
analysis_context.insert("mistake_type".to_string(), serde_json::Value::String(session.mistake_type.clone()));
analysis_context.insert("subject".to_string(), serde_json::Value::String(session.subject.clone()));
// 使用RAG增强的模型调用
state.llm_manager.call_rag_enhanced_model_stream(
&analysis_context,
retrieved_context.clone(),
&request.chat_history,
&session.subject,
request.enable_chain_of_thought.unwrap_or(false),
Some(session.question_images.clone()), // 🎯 修复:传递图片信息
window,
&stream_event,
).await?
} else {
// 使用普通的模型调用
let mut context = std::collections::HashMap::new();
context.insert("ocr_text".to_string(), serde_json::json!(session.ocr_text));
context.insert("tags".to_string(), serde_json::json!(session.tags));
context.insert("mistake_type".to_string(), serde_json::json!(session.mistake_type));
context.insert("user_question".to_string(), serde_json::json!(session.user_question));
let model_config = state.llm_manager.get_model2_config().await
.map_err(|e| format!("获取模型配置失败: {}", e))?;
let enable_chain_of_thought = request.enable_chain_of_thought.unwrap_or(model_config.is_reasoning);
state.llm_manager.call_unified_model_2_stream(
&context,
&request.chat_history,
&session.subject,
enable_chain_of_thought,
Some(session.question_images.clone()), // 🎯 修复:传递图片信息
Some("基于题目信息继续对话解答用户问题"),
window,
&stream_event,
).await?
};
// 更新会话的聊天记录
session.chat_history = request.chat_history;
// 转换RAG来源信息(如果有的话)
let rag_sources = if !retrieved_context.is_empty() {
Some(retrieved_context.iter().map(|chunk| crate::models::RagSourceInfo {
document_id: chunk.chunk.document_id.clone(),
file_name: chunk.chunk.metadata.get("file_name")
.unwrap_or(&"unknown".to_string()).clone(),
chunk_text: chunk.chunk.text.clone(),
score: chunk.score,
chunk_index: chunk.chunk.chunk_index,
}).collect())
} else {
None
};
session.chat_history.push(ChatMessage {
role: "assistant".to_string(),
content: model2_result.assistant_message.clone(),
timestamp: Utc::now(),
thinking_content: None,
rag_sources,
image_paths: None,
image_base64: None,
});
// 保存更新后的会话
{
let mut sessions = state.temp_sessions.lock().await;
sessions.insert(request.temp_id, session);
}
println!("✅ RAG增强的对话完成");
Ok(ContinueChatResponse {
new_assistant_message: model2_result.assistant_message,
})
}
/// LLM基于上下文生成回答
#[tauri::command]
pub async fn llm_generate_answer_with_context(
user_query: String,
retrieved_chunks_json: String,
state: State<'_, AppState>,
) -> Result<String> {
println!("🤖 开始生成基于上下文的回答");
if user_query.trim().is_empty() {
return Err(AppError::validation("用户查询不能为空"));
}
// 解析检索到的文档块
let retrieved_chunks: Vec<crate::models::RetrievedChunk> = serde_json::from_str(&retrieved_chunks_json)
.map_err(|e| AppError::validation(format!("解析检索结果失败: {}", e)))?;
if retrieved_chunks.is_empty() {
return Err(AppError::validation("没有提供知识库上下文"));
}
// 构建RAG增强的Prompt
let mut context_text = String::new();
context_text.push_str("以下是从知识库中检索到的相关信息:\n\n");
for (index, chunk) in retrieved_chunks.iter().enumerate() {
context_text.push_str(&format!(
"[文档{}] 来源: {}\n{}\n\n",
index + 1,
chunk.chunk.metadata.get("file_name").unwrap_or(&"未知文档".to_string()),
chunk.chunk.text
));
}
context_text.push_str(&format!(
"基于以上知识库信息,请回答用户的问题:\n{}\n\n",
user_query
));
context_text.push_str("请确保回答准确、有用,并在适当时引用具体的来源信息。如果知识库中的信息不足以回答问题,请明确说明。");
// 构建上下文参数
let mut context_map = std::collections::HashMap::new();
context_map.insert("context".to_string(), serde_json::Value::String(context_text));
// 调用LLM生成回答
let answer = state.llm_manager.call_unified_model_2(
&context_map,
&[], // 空的聊天历史
"通用", // 科目
false, // 不启用思维链
None, // 没有图片
Some("RAG增强问答") // 任务上下文
).await.map_err(|e| AppError::llm(format!("LLM生成回答失败: {}", e)))?;
println!("✅ 基于上下文的回答生成完成,长度: {} 字符", answer.assistant_message.len());
Ok(answer.assistant_message)
}
// ==================== RAG配置管理命令 ====================
/// 获取RAG配置
#[tauri::command]
pub async fn get_rag_settings(
state: State<'_, AppState>,
) -> Result<crate::models::RagConfigResponse> {
println!("📖 获取RAG配置");
let config = state.database.get_rag_configuration()
.map_err(|e| AppError::database(format!("获取RAG配置失败: {}", e)))?;
match config {
Some(config) => {
println!("✅ RAG配置获取成功");
Ok(crate::models::RagConfigResponse {
chunk_size: config.chunk_size,
chunk_overlap: config.chunk_overlap,
chunking_strategy: config.chunking_strategy,
min_chunk_size: config.min_chunk_size,
default_top_k: config.default_top_k,
default_rerank_enabled: config.default_rerank_enabled,
})
}
None => {
// 如果没有配置,返回默认值
println!("⚠️ 未找到RAG配置,返回默认值");
Ok(crate::models::RagConfigResponse {
chunk_size: 512,
chunk_overlap: 50,
chunking_strategy: "fixed_size".to_string(),
min_chunk_size: 20,
default_top_k: 5,
default_rerank_enabled: false,
})
}
}
}
/// 更新RAG配置
#[tauri::command]
pub async fn update_rag_settings(
settings: crate::models::RagConfigRequest,
state: State<'_, AppState>,
) -> Result<()> {
println!("🔧 更新RAG配置");
// 验证配置参数
if settings.chunk_size < 50 || settings.chunk_size > 2048 {
return Err(AppError::validation("分块大小必须在50-2048之间"));
}
if settings.chunk_overlap < 0 || settings.chunk_overlap >= settings.chunk_size {
return Err(AppError::validation("重叠大小必须非负且小于分块大小"));
}
if settings.min_chunk_size < 10 || settings.min_chunk_size > settings.chunk_size {
return Err(AppError::validation("最小分块大小必须在10和分块大小之间"));
}
if settings.default_top_k < 1 || settings.default_top_k > 50 {
return Err(AppError::validation("默认检索数量必须在1-50之间"));
}
if !["fixed_size", "semantic"].contains(&settings.chunking_strategy.as_str()) {
return Err(AppError::validation("分块策略必须是 'fixed_size' 或 'semantic'"));
}
state.database.update_rag_configuration(&settings)
.map_err(|e| AppError::database(format!("更新RAG配置失败: {}", e)))?;
println!("✅ RAG配置更新成功");
Ok(())
}
/// 重置RAG配置为默认值
#[tauri::command]
pub async fn reset_rag_settings(
state: State<'_, AppState>,
) -> Result<()> {
println!("🔄 重置RAG配置为默认值");
state.database.reset_rag_configuration()
.map_err(|e| AppError::database(format!("重置RAG配置失败: {}", e)))?;
println!("✅ RAG配置已重置为默认值");
Ok(())
}
// ============================================================================
// RAG分库管理相关命令
// ============================================================================
/// 创建新的RAG分库
#[tauri::command]
pub async fn create_rag_sub_library(
request: CreateSubLibraryRequest,
state: State<'_, AppState>,
) -> Result<SubLibrary> {
println!("🏗️ 创建新分库: {}", request.name);
let sub_library = state.database.create_sub_library(&request)
.map_err(|e| AppError::database(format!("创建分库失败: {}", e)))?;
println!("✅ 分库创建成功: {} (ID: {})", sub_library.name, sub_library.id);
Ok(sub_library)
}
/// 获取所有RAG分库列表
#[tauri::command]
pub async fn get_rag_sub_libraries(
state: State<'_, AppState>,
) -> Result<Vec<SubLibrary>> {
println!("📚 获取分库列表");
let libraries = state.database.list_sub_libraries()
.map_err(|e| AppError::database(format!("获取分库列表失败: {}", e)))?;
println!("✅ 获取到 {} 个分库", libraries.len());
Ok(libraries)
}
/// 根据ID获取RAG分库详情
#[tauri::command]
pub async fn get_rag_sub_library_by_id(
libraryId: String,
state: State<'_, AppState>,
) -> Result<Option<SubLibrary>> {
println!("🔍 获取分库详情: {}", libraryId);
let library = state.database.get_sub_library_by_id(&libraryId)
.map_err(|e| AppError::database(format!("获取分库详情失败: {}", e)))?;
if let Some(ref lib) = library {
println!("✅ 找到分库: {}", lib.name);
} else {
println!("⚠️ 未找到分库: {}", libraryId);
}
Ok(library)
}
/// 更新RAG分库信息
#[tauri::command]
pub async fn update_rag_sub_library(
libraryId: String,
request: UpdateSubLibraryRequest,
state: State<'_, AppState>,
) -> Result<SubLibrary> {
println!("📝 更新分库: {}", libraryId);
let updated_library = state.database.update_sub_library(&libraryId, &request)
.map_err(|e| AppError::database(format!("更新分库失败: {}", e)))?;
println!("✅ 分库更新成功: {}", updated_library.name);
Ok(updated_library)
}
/// 删除RAG分库
#[tauri::command]
pub async fn delete_rag_sub_library(
libraryId: String,
deleteDocuments: Option<bool>,
state: State<'_, AppState>,
) -> Result<()> {
let delete_contained_documents = deleteDocuments.unwrap_or(false);
println!("🗑️ 删除分库: {} (删除文档: {})", libraryId, delete_contained_documents);
state.database.delete_sub_library(&libraryId, delete_contained_documents)
.map_err(|e| AppError::database(format!("删除分库失败: {}", e)))?;
println!("✅ 分库删除成功");
Ok(())
}
/// 向指定分库添加文档
#[tauri::command]
pub async fn rag_add_documents_to_library(
request: RagAddDocumentsRequest,
window: Window,
state: State<'_, AppState>,
) -> Result<String> {
let target_library = request.sub_library_id.as_deref();
println!("📄 向分库添加文档: {:?}, 文档数: {}", target_library, request.file_paths.len());
// 使用相同的修复方式:立即读取文件内容避免路径失效
let mut document_contents = Vec::new();
for (index, file_path) in request.file_paths.iter().enumerate() {
println!("📄 文件 {}: {}", index + 1, file_path);
// 尝试规范化路径
let normalized_path = match std::path::Path::new(file_path).canonicalize() {
Ok(canonical) => {
let canonical_str = canonical.display().to_string();
println!("🔧 规范化路径: {} -> {}", file_path, canonical_str);
canonical_str
}
Err(e) => {
println!("⚠️ 无法规范化路径 {}: {},使用原路径", file_path, e);
file_path.clone()
}
};
let path = std::path::Path::new(&normalized_path);
// 检查文件是否存在
if !path.exists() {
println!("❌ 文件不存在: {} (原路径: {})", normalized_path, file_path);
return Err(AppError::file_system(format!("文件不存在: {} (原路径: {})", normalized_path, file_path)));
}
if !path.is_file() {
println!("❌ 路径不是文件: {} (原路径: {})", normalized_path, file_path);
return Err(AppError::file_system(format!("指定路径不是文件: {} (原路径: {})", normalized_path, file_path)));
}
// 立即读取文件内容,避免后续路径失效
let file_name = path.file_name()
.and_then(|name| name.to_str())
.unwrap_or("unknown")
.to_string();
println!("📚 立即读取文件内容: {}", file_name);
let content = match path.extension().and_then(|ext| ext.to_str()).unwrap_or("").to_lowercase().as_str() {
"txt" | "md" | "markdown" => {
// 文本文件直接读取
match std::fs::read_to_string(&normalized_path) {
Ok(content) => content,
Err(e) => {
println!("❌ 读取文本文件失败: {} - {}", file_name, e);
return Err(AppError::file_system(format!("读取文本文件失败: {} - {}", file_name, e)));
}
}
}
"pdf" | "docx" => {
// 二进制文件读取为base64
match std::fs::read(&normalized_path) {
Ok(bytes) => {
use base64::{Engine as _, engine::general_purpose};
general_purpose::STANDARD.encode(&bytes)
}
Err(e) => {
println!("❌ 读取二进制文件失败: {} - {}", file_name, e);
return Err(AppError::file_system(format!("读取二进制文件失败: {} - {}", file_name, e)));
}
}
}
_ => {
println!("❌ 不支持的文件类型: {}", file_name);
return Err(AppError::validation(format!("不支持的文件类型: {}", file_name)));
}
};
println!("✅ 文件内容读取成功: {} ({} 字符)", file_name, content.len());
document_contents.push(serde_json::json!({
"fileName": file_name,
"content": content
}));
}
if document_contents.is_empty() {
return Err(AppError::validation("文件内容列表不能为空"));
}
// 需要创建支持分库的内容上传方法
let result = if let Some(sub_library_id) = request.sub_library_id {
// 向指定分库添加
state.rag_manager.add_documents_from_content_to_library(document_contents, window, Some(sub_library_id)).await?
} else {
// 添加到默认分库
state.rag_manager.add_documents_from_content(document_contents, window).await?
};
Ok(result)
}
/// 从Base64内容向指定分库添加文档
#[tauri::command]
pub async fn rag_add_documents_from_content_to_library(
request: RagAddDocumentsFromContentRequest,
window: Window,
state: State<'_, AppState>,
) -> Result<String> {
let target_library = request.sub_library_id.as_deref();
println!("📄 从内容向分库添加文档: {:?}, 文档数: {}", target_library, request.documents.len());
// 转换请求格式
let documents: Vec<serde_json::Value> = request.documents.into_iter().map(|doc| {
serde_json::json!({
"fileName": doc.file_name,
"content": doc.base64_content
})
}).collect();
let result = state.rag_manager.add_documents_from_content_to_library(documents, window, request.sub_library_id).await?;
Ok(result)
}
/// 获取指定分库的文档列表
#[tauri::command]
pub async fn get_rag_documents_by_library(
request: GetDocumentsRequest,
state: State<'_, AppState>,
) -> Result<Vec<serde_json::Value>> {
let library_id = request.sub_library_id.as_deref().unwrap_or("default");
println!("📑 获取分库文档列表: {}", library_id);
let documents = state.database.get_documents_by_sub_library(
library_id,
request.page,
request.page_size
).map_err(|e| AppError::database(format!("获取文档列表失败: {}", e)))?;
println!("✅ 获取到 {} 个文档", documents.len());
Ok(documents)
}
/// 将文档移动到指定分库
#[tauri::command]
pub async fn move_document_to_rag_library(
documentId: String,
targetLibraryId: String,
state: State<'_, AppState>,
) -> Result<()> {
println!("📦 移动文档到分库: {} -> {}", documentId, targetLibraryId);
state.database.move_document_to_sub_library(&documentId, &targetLibraryId)
.map_err(|e| AppError::database(format!("移动文档失败: {}", e)))?;
println!("✅ 文档移动成功");
Ok(())
}
/// 在指定分库中查询知识库
#[tauri::command]
pub async fn rag_query_knowledge_base_in_libraries(
query: String,
options: RagQueryOptionsWithLibraries,
state: State<'_, AppState>,
) -> Result<RagQueryResponse> {
println!("🔍 在指定分库中查询: '{}', 分库: {:?}", query, options.target_sub_library_ids);
let rag_options = RagQueryOptions {
top_k: options.top_k,
enable_reranking: options.enable_reranking,
};
let response = state.rag_manager.query_knowledge_base_in_libraries(
&query,
rag_options,
options.target_sub_library_ids
).await?;
println!("✅ 查询完成,返回 {} 个结果", response.retrieved_chunks.len());
Ok(response)
}
// ============================================================================
// 文档解析相关命令
// ============================================================================
/// 从文件路径解析文档文本
#[tauri::command]
pub async fn parse_document_from_path(
file_path: String,
) -> std::result::Result<String, String> {
println!("🔍 开始解析文档: {}", file_path);
let parser = crate::document_parser::DocumentParser::new();
match parser.extract_text_from_path(&file_path) {
Ok(text) => {
println!("✅ 文档解析成功,提取文本长度: {} 字符", text.len());
Ok(text)
}
Err(err) => {
let error_msg = format!("文档解析失败: {}", err);
println!("❌ {}", error_msg);
Err(error_msg)
}
}
}
/// 从Base64编码内容解析文档文本
#[tauri::command]
pub async fn parse_document_from_base64(
file_name: String,
base64_content: String,
) -> std::result::Result<String, String> {
println!("🔍 开始解析Base64文档: {}", file_name);
let parser = crate::document_parser::DocumentParser::new();
match parser.extract_text_from_base64(&file_name, &base64_content) {
Ok(text) => {
println!("✅ Base64文档解析成功,提取文本长度: {} 字符", text.len());
Ok(text)
}
Err(err) => {
let error_msg = format!("Base64文档解析失败: {}", err);
println!("❌ {}", error_msg);
Err(error_msg)
}
}
}
/// 生成错题总结 - 使用第二模型基于聊天记录生成结构化总结
#[tauri::command]
pub async fn generate_mistake_summary(
request: GenerateMistakeSummaryRequest,
state: State<'_, AppState>,
) -> Result<GenerateMistakeSummaryResponse> {
println!("🧠 开始生成错题总结: {}", request.mistake_id);
// 从数据库获取错题详情
let mistake = match state.database.get_mistake_by_id(&request.mistake_id)? {
Some(mistake) => mistake,
None => {
return Ok(GenerateMistakeSummaryResponse {
success: false,
mistake_summary: None,
user_error_analysis: None,
error_message: Some("错题不存在".to_string()),
});
}
};
// 检查是否需要重新生成
if !request.force_regenerate.unwrap_or(false) {
if mistake.mistake_summary.is_some() && mistake.user_error_analysis.is_some() {
return Ok(GenerateMistakeSummaryResponse {
success: true,
mistake_summary: mistake.mistake_summary.clone(),
user_error_analysis: mistake.user_error_analysis.clone(),
error_message: None,
});
}
}
// 验证聊天记录存在且非空
if mistake.chat_history.is_empty() {
return Ok(GenerateMistakeSummaryResponse {
success: false,
mistake_summary: None,
user_error_analysis: None,
error_message: Some("没有聊天记录,无法生成总结".to_string()),
});
}
// 获取模型配置
let model_assignments = state.llm_manager.get_model_assignments().await
.map_err(|e| AppError::configuration(format!("获取模型分配失败: {}", e)))?;
// 关键修改:优先使用专门的总结模型,如果未配置,则回退到模型二
let model_config_id = model_assignments.summary_model_config_id
.or(model_assignments.model2_config_id) // 如果总结模型为空,则使用模型二
.ok_or_else(|| AppError::configuration("没有为总结或分析配置任何可用模型"))?;
// 获取具体模型配置
let model_configs = match state.llm_manager.get_api_configs().await {
Ok(configs) => configs,
Err(e) => {
return Ok(GenerateMistakeSummaryResponse {
success: false,
mistake_summary: None,
user_error_analysis: None,
error_message: Some(format!("获取API配置失败: {}", e)),
});
}
};
let model_config = model_configs.iter()
.find(|config| config.id == model_config_id)
.ok_or_else(|| AppError::configuration("第二模型配置不存在"))?;
// 构建总结生成提示词
let summary_prompt = build_summary_generation_prompt(&mistake);
// 准备统一模型2的调用参数
let mut context = std::collections::HashMap::new();
context.insert("task".to_string(), serde_json::Value::String("mistake_summary".to_string()));
context.insert("prompt".to_string(), serde_json::Value::String(summary_prompt));
// 调用第二模型生成总结
match state.llm_manager.call_unified_model_2(&context, &[], &mistake.subject, false, None, Some("mistake_summary_generation")).await {
Ok(response) => {
// 解析AI回复,提取两个字段
let (mistake_summary, user_error_analysis) = parse_summary_response(&response.assistant_message);
// 🎯 修复BUG-02:更新数据库并设置状态为已完成
let mut updated_mistake = mistake.clone();
updated_mistake.mistake_summary = Some(mistake_summary.clone());
updated_mistake.user_error_analysis = Some(user_error_analysis.clone());
updated_mistake.status = "completed".to_string(); // 🎯 修复:生成总结后将状态设为已完成
updated_mistake.updated_at = Utc::now();
if let Err(e) = state.database.save_mistake(&updated_mistake) {
println!("⚠️ 保存错题总结失败: {}", e);
return Ok(GenerateMistakeSummaryResponse {
success: false,
mistake_summary: None,
user_error_analysis: None,
error_message: Some(format!("保存总结失败: {}", e)),
});
}
println!("✅ 错题总结生成成功");
Ok(GenerateMistakeSummaryResponse {
success: true,
mistake_summary: Some(mistake_summary),
user_error_analysis: Some(user_error_analysis),
error_message: None,
})
}
Err(e) => {
println!("❌ 总结生成失败: {}", e);
Ok(GenerateMistakeSummaryResponse {
success: false,
mistake_summary: None,
user_error_analysis: None,
error_message: Some(format!("AI生成失败: {}", e)),
})
}
}
}
/// 构建总结生成提示词
fn build_summary_generation_prompt(mistake: &MistakeItem) -> String {
let mut prompt = String::new();
prompt.push_str("你是一个专业的教育分析专家。请基于以下错题信息和师生对话记录,生成两个结构化总结:\n\n");
// 题目信息
prompt.push_str(&format!("【题目信息】\n科目:{}\n题目内容:{}\n学生原始问题:{}\n\n",
mistake.subject, mistake.ocr_text, mistake.user_question));
// 聊天记录
prompt.push_str("【师生对话记录】\n");
for (i, message) in mistake.chat_history.iter().enumerate() {
let role_name = match message.role.as_str() {
"user" => "学生",
"assistant" => "老师",
_ => &message.role,
};
prompt.push_str(&format!("{}. {}: {}\n", i + 1, role_name, message.content));
}
prompt.push_str("\n请基于以上信息,生成以下两个总结(用===分隔):\n\n");
prompt.push_str("【错题简要解析】\n");
prompt.push_str("简要描述题目要点、正确解法和涉及的关键知识点,150字以内。\n\n");
prompt.push_str("===\n\n");
prompt.push_str("【用户错误分析】\n");
prompt.push_str("总结学生在对话中暴露的错误原因、思维误区和薄弱点,150字以内。\n\n");
prompt.push_str("注意:请直接输出两个总结内容,不要包含其他解释性文字。");
prompt
}
/// 解析AI总结回复,提取两个字段
fn parse_summary_response(response: &str) -> (String, String) {
let parts: Vec<&str> = response.split("===").collect();
if parts.len() >= 2 {
let mistake_summary = parts[0].trim()
.lines()
.filter(|line| !line.trim().is_empty() && !line.contains("【错题简要解析】"))
.collect::<Vec<_>>()
.join("\n")
.trim()
.to_string();
let user_error_analysis = parts[1].trim()
.lines()
.filter(|line| !line.trim().is_empty() && !line.contains("【用户错误分析】"))
.collect::<Vec<_>>()
.join("\n")
.trim()
.to_string();
(mistake_summary, user_error_analysis)
} else {
// 解析失败,尝试简单分割
let fallback_summary = response.lines()
.take(3)
.collect::<Vec<_>>()
.join(" ")
.chars()
.take(150)
.collect();
let fallback_analysis = response.lines()
.skip(3)
.take(3)
.collect::<Vec<_>>()
.join(" ")
.chars()
.take(150)
.collect();
(fallback_summary, fallback_analysis)
}
}
// 自定义模板管理命令
/// 获取所有自定义模板
#[tauri::command]
pub async fn get_all_custom_templates(
state: State<'_, AppState>,
) -> Result<Vec<CustomAnkiTemplate>> {
let templates = state.database.get_all_custom_templates()
.map_err(|e| AppError::database(format!("获取模板列表失败: {}", e)))?;
Ok(templates)
}
/// 获取指定ID的自定义模板
#[tauri::command]
pub async fn get_custom_template_by_id(
template_id: String,
state: State<'_, AppState>,
) -> Result<Option<CustomAnkiTemplate>> {
let template = state.database.get_custom_template_by_id(&template_id)
.map_err(|e| AppError::database(format!("获取模板失败: {}", e)))?;
Ok(template)
}
/// 创建自定义模板
#[tauri::command]
pub async fn create_custom_template(
request: CreateTemplateRequest,
state: State<'_, AppState>,
) -> Result<String> {
// 验证模板数据
validate_template_request(&request)?;
let template_id = state.database.create_custom_template(&request)
.map_err(|e| AppError::database(format!("创建模板失败: {}", e)))?;
Ok(template_id)
}
/// 更新自定义模板
#[tauri::command]
pub async fn update_custom_template(
template_id: String,
request: UpdateTemplateRequest,
state: State<'_, AppState>,
) -> Result<()> {
// 验证模板是否存在且不是内置模板
let existing_template = state.database.get_custom_template_by_id(&template_id)
.map_err(|e| AppError::database(format!("查询模板失败: {}", e)))?;
match existing_template {
Some(template) => {
if template.is_built_in {
return Err(AppError::validation("不能修改内置模板".to_string()));
}
},
None => {
return Err(AppError::validation("模板不存在".to_string()));
}
}
state.database.update_custom_template(&template_id, &request)
.map_err(|e| AppError::database(format!("更新模板失败: {}", e)))?;
Ok(())
}
/// 删除自定义模板
#[tauri::command]
pub async fn delete_custom_template(
template_id: String,
state: State<'_, AppState>,
) -> Result<()> {
// 验证模板是否存在且不是内置模板
let existing_template = state.database.get_custom_template_by_id(&template_id)
.map_err(|e| AppError::database(format!("查询模板失败: {}", e)))?;
match existing_template {
Some(template) => {
if template.is_built_in {
return Err(AppError::validation("不能删除内置模板".to_string()));
}
},
None => {
return Err(AppError::validation("模板不存在".to_string()));
}
}
state.database.delete_custom_template(&template_id)
.map_err(|e| AppError::database(format!("删除模板失败: {}", e)))?;
Ok(())
}
/// 导出模板
#[tauri::command]
pub async fn export_template(
template_id: String,
state: State<'_, AppState>,
) -> Result<TemplateExportResponse> {
let template = state.database.get_custom_template_by_id(&template_id)
.map_err(|e| AppError::database(format!("查询模板失败: {}", e)))?;
match template {
Some(template) => {
let template_data = serde_json::to_string_pretty(&template)
.map_err(|e| AppError::validation(format!("序列化模板失败: {}", e)))?;
let filename = format!("{}_template.json", template.name.replace(" ", "_"));
Ok(TemplateExportResponse {
template_data,
filename,
})
},
None => Err(AppError::validation("模板不存在".to_string())),
}
}
/// 导入模板
#[tauri::command]
pub async fn import_template(
request: TemplateImportRequest,
state: State<'_, AppState>,
) -> Result<String> {
// 解析模板数据
let template: CustomAnkiTemplate = serde_json::from_str(&request.template_data)
.map_err(|e| AppError::validation(format!("解析模板数据失败: {}", e)))?;
// 检查是否已存在同名模板
let existing_templates = state.database.get_all_custom_templates()
.map_err(|e| AppError::database(format!("查询现有模板失败: {}", e)))?;
if existing_templates.iter().any(|t| t.name == template.name) {
if !request.overwrite_existing {
return Err(AppError::validation(format!("模板 '{}' 已存在", template.name)));
}
// 找到同名模板并删除(如果不是内置模板)
if let Some(existing) = existing_templates.iter().find(|t| t.name == template.name) {
if existing.is_built_in {
return Err(AppError::validation("不能覆盖内置模板".to_string()));
}
state.database.delete_custom_template(&existing.id)
.map_err(|e| AppError::database(format!("删除旧模板失败: {}", e)))?;
}
}
// 创建新模板
let create_request = CreateTemplateRequest {
name: template.name,
description: template.description,
author: template.author,
preview_front: template.preview_front,
preview_back: template.preview_back,
note_type: template.note_type,
fields: template.fields,
generation_prompt: template.generation_prompt,
front_template: template.front_template,
back_template: template.back_template,
css_style: template.css_style,
field_extraction_rules: template.field_extraction_rules,
};
validate_template_request(&create_request)?;
let template_id = state.database.create_custom_template(&create_request)
.map_err(|e| AppError::database(format!("导入模板失败: {}", e)))?;
Ok(template_id)
}
/// 验证模板请求数据
fn validate_template_request(request: &CreateTemplateRequest) -> Result<()> {
// 验证基本字段
if request.name.trim().is_empty() {
return Err(AppError::validation("模板名称不能为空".to_string()));
}
if request.fields.is_empty() {
return Err(AppError::validation("模板必须至少包含一个字段".to_string()));
}
// 验证必须包含 front 和 back 字段
let has_front = request.fields.iter().any(|f| f.to_lowercase() == "front");
let has_back = request.fields.iter().any(|f| f.to_lowercase() == "back");
if !has_front {
return Err(AppError::validation("模板必须包含 'Front' 字段".to_string()));
}
if !has_back {
return Err(AppError::validation("模板必须包含 'Back' 字段".to_string()));
}
// 验证模板语法
if request.front_template.trim().is_empty() {
return Err(AppError::validation("正面模板不能为空".to_string()));
}
if request.back_template.trim().is_empty() {
return Err(AppError::validation("背面模板不能为空".to_string()));
}
if request.generation_prompt.trim().is_empty() {
return Err(AppError::validation("生成提示词不能为空".to_string()));
}
// 验证字段提取规则
for field in &request.fields {
if !request.field_extraction_rules.contains_key(field) {
return Err(AppError::validation(format!("缺少字段 '{}' 的提取规则", field)));
}
}
Ok(())
}
// =================== 图片遮罩卡相关命令 ===================
/// 图片文字坐标识别
#[tauri::command]
pub async fn extract_image_text_coordinates(
request: ImageOcrRequest,
state: tauri::State<'_, AppState>,
) -> Result<ImageOcrResponse> {
Ok(state.image_occlusion_service.extract_text_coordinates(request).await?)
}
/// 创建图片遮罩卡
#[tauri::command]
pub async fn create_image_occlusion_card(
request: CreateImageOcclusionRequest,
state: tauri::State<'_, AppState>,
) -> Result<ImageOcclusionResponse> {
Ok(state.image_occlusion_service.create_image_occlusion_card(request).await?)
}
/// 获取所有图片遮罩卡
#[tauri::command]
pub async fn get_all_image_occlusion_cards(
state: tauri::State<'_, AppState>,
) -> Result<Vec<ImageOcclusionCard>> {
Ok(state.image_occlusion_service.get_all_image_occlusion_cards()?)
}
/// 根据ID获取图片遮罩卡
#[tauri::command]
pub async fn get_image_occlusion_card(
card_id: String,
state: tauri::State<'_, AppState>,
) -> Result<Option<ImageOcclusionCard>> {
Ok(state.image_occlusion_service.get_image_occlusion_card(&card_id)?)
}
/// 更新图片遮罩卡
#[tauri::command]
pub async fn update_image_occlusion_card(
card: ImageOcclusionCard,
state: tauri::State<'_, AppState>,
) -> Result<()> {
Ok(state.image_occlusion_service.update_image_occlusion_card(&card)?)
}
/// 删除图片遮罩卡
#[tauri::command]
pub async fn delete_image_occlusion_card(
card_id: String,
state: tauri::State<'_, AppState>,
) -> Result<()> {
Ok(state.image_occlusion_service.delete_image_occlusion_card(&card_id)?)
}
/// 设置默认模板
#[tauri::command]
pub async fn set_default_template(
template_id: String,
state: tauri::State<'_, AppState>,
) -> Result<()> {
Ok(state.database.set_default_template(&template_id)?)
}
/// 获取默认模板ID
#[tauri::command]
pub async fn get_default_template_id(
state: tauri::State<'_, AppState>,
) -> Result<Option<String>> {
Ok(state.database.get_default_template()?)
}
// ============= 测试日志相关命令 =============
/// 保存测试日志到文件
#[tauri::command]
pub async fn save_test_log(
file_name: String,
content: String,
log_type: String,
state: tauri::State<'_, AppState>,
) -> Result<()> {
use std::fs;
use std::path::PathBuf;
// 创建日志目录路径
let mut log_dir = state.file_manager.get_app_data_dir().to_path_buf();
log_dir.push("logs");
log_dir.push(&log_type);
// 确保目录存在
if let Err(e) = fs::create_dir_all(&log_dir) {
return Err(AppError::file_system(format!("创建日志目录失败: {}", e)));
}
// 构建完整文件路径
let file_path = log_dir.join(&file_name);
// 写入日志文件
if let Err(e) = fs::write(&file_path, content) {
return Err(AppError::file_system(format!("写入日志文件失败: {}", e)));
}
println!("测试日志已保存: {:?}", file_path);
Ok(())
}
/// 获取测试日志列表
#[tauri::command]
pub async fn get_test_logs(
log_type: String,
state: tauri::State<'_, AppState>,
) -> Result<Vec<String>> {
use std::fs;
let mut log_dir = state.file_manager.get_app_data_dir().to_path_buf();
log_dir.push("logs");
log_dir.push(&log_type);
if !log_dir.exists() {
return Ok(vec![]);
}
let mut log_files = Vec::new();
if let Ok(entries) = fs::read_dir(&log_dir) {
for entry in entries {
if let Ok(entry) = entry {
let path = entry.path();
if path.is_file() && path.extension().map_or(false, |ext| ext == "log") {
if let Some(file_name) = path.file_name() {
if let Some(file_name_str) = file_name.to_str() {
let relative_path = format!("logs/{}/{}", log_type, file_name_str);
log_files.push(relative_path);
}
}
}
}
}
}
// 按修改时间排序(最新的在前)
log_files.sort_by(|a, b| {
let path_a = state.file_manager.get_app_data_dir().join(a);
let path_b = state.file_manager.get_app_data_dir().join(b);
let time_a = path_a.metadata().and_then(|m| m.modified()).unwrap_or(std::time::UNIX_EPOCH);
let time_b = path_b.metadata().and_then(|m| m.modified()).unwrap_or(std::time::UNIX_EPOCH);
time_b.cmp(&time_a) // 降序
});
Ok(log_files)
}
/// 打开指定的日志文件
#[tauri::command]
pub async fn open_log_file(
log_path: String,
state: tauri::State<'_, AppState>,
) -> Result<()> {
use std::process::Command;
let full_path = state.file_manager.get_app_data_dir().join(&log_path);
if !full_path.exists() {
return Err(AppError::not_found(format!("日志文件不存在: {}", log_path)));
}
// 根据操作系统选择合适的命令打开文件
#[cfg(target_os = "windows")]
{
if let Err(e) = Command::new("notepad").arg(&full_path).spawn() {
// 如果notepad失败,尝试默认程序
if let Err(e2) = Command::new("cmd").args(&["/C", "start", "", full_path.to_str().unwrap_or("")]).spawn() {
return Err(AppError::file_system(format!("打开日志文件失败: {} (备用方案也失败: {})", e, e2)));
}
}
}
#[cfg(target_os = "macos")]
{
if let Err(e) = Command::new("open").arg(&full_path).spawn() {
return Err(AppError::file_system(format!("打开日志文件失败: {}", e)));
}
}
#[cfg(target_os = "linux")]
{
if let Err(e) = Command::new("xdg-open").arg(&full_path).spawn() {
return Err(AppError::file_system(format!("打开日志文件失败: {}", e)));
}
}
Ok(())
}
/// 打开日志文件夹
#[tauri::command]
pub async fn open_logs_folder(
log_type: String,
state: tauri::State<'_, AppState>,
) -> Result<()> {
use std::process::Command;
let mut log_dir = state.file_manager.get_app_data_dir().to_path_buf();
log_dir.push("logs");
log_dir.push(&log_type);
// 确保目录存在
if let Err(_) = std::fs::create_dir_all(&log_dir) {
return Err(AppError::file_system("创建日志目录失败".to_string()));
}
// 根据操作系统选择合适的命令打开文件夹
#[cfg(target_os = "windows")]
{
if let Err(e) = Command::new("explorer").arg(&log_dir).spawn() {
return Err(AppError::file_system(format!("打开日志文件夹失败: {}", e)));
}
}
#[cfg(target_os = "macos")]
{
if let Err(e) = Command::new("open").arg(&log_dir).spawn() {
return Err(AppError::file_system(format!("打开日志文件夹失败: {}", e)));
}
}
#[cfg(target_os = "linux")]
{
if let Err(e) = Command::new("xdg-open").arg(&log_dir).spawn() {
return Err(AppError::file_system(format!("打开日志文件夹失败: {}", e)));
}
}
Ok(())
}
| 158,584 | commands | rs | en | rust | code | {"qsc_code_num_words": 16769, "qsc_code_num_chars": 158584.0, "qsc_code_mean_word_length": 5.3935834, "qsc_code_frac_words_unique": 0.10221242, "qsc_code_frac_chars_top_2grams": 0.01777876, "qsc_code_frac_chars_top_3grams": 0.02056498, "qsc_code_frac_chars_top_4grams": 0.02741998, "qsc_code_frac_chars_dupe_5grams": 0.60982918, "qsc_code_frac_chars_dupe_6grams": 0.55076566, "qsc_code_frac_chars_dupe_7grams": 0.47393444, "qsc_code_frac_chars_dupe_8grams": 0.41110067, "qsc_code_frac_chars_dupe_9grams": 0.36719553, "qsc_code_frac_chars_dupe_10grams": 0.33379402, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0083638, "qsc_code_frac_chars_whitespace": 0.25133683, "qsc_code_size_file_byte": 158584.0, "qsc_code_num_lines": 5126.0, "qsc_code_num_chars_line_max": 181.0, "qsc_code_num_chars_line_mean": 30.93718299, "qsc_code_frac_chars_alphabet": 0.7514445, "qsc_code_frac_chars_comments": 0.05101397, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.47563109, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00349913, "qsc_code_frac_chars_string_length": 0.08122583, "qsc_code_frac_chars_long_word_length": 0.00813321, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
000haoji/deep-student | src-tauri/src/image_occlusion_service.rs | use crate::models::{
ImageOcrRequest, ImageOcrResponse, TextRegion, CreateImageOcclusionRequest,
ImageOcclusionResponse, ImageOcclusionCard, OcclusionMask, MaskStyle, AppError
};
use crate::llm_manager::{LLMManager, ApiConfig};
use crate::database::Database;
use std::sync::Arc;
use uuid::Uuid;
use chrono::Utc;
use base64::{Engine as _, engine::general_purpose};
use std::io::Cursor;
use image::{ImageFormat, DynamicImage};
use serde_json::{json, Value};
#[derive(Clone)]
pub struct ImageOcclusionService {
db: Arc<Database>,
llm_manager: Arc<LLMManager>,
}
impl ImageOcclusionService {
pub fn new(db: Arc<Database>, llm_manager: Arc<LLMManager>) -> Self {
Self {
db,
llm_manager,
}
}
/// 检测Base64编码图像的真实格式
fn detect_image_format_from_base64(base64_data: &str) -> &'static str {
// 解码Base64获取前几个字节来判断格式
if let Ok(decoded) = general_purpose::STANDARD.decode(base64_data.get(..100).unwrap_or(base64_data)) {
Self::detect_image_format_from_bytes(&decoded)
} else {
"jpeg" // 默认格式
}
}
/// 根据图像字节数据检测格式
fn detect_image_format_from_bytes(image_data: &[u8]) -> &'static str {
if image_data.len() < 4 {
return "jpeg"; // 默认格式
}
// JPEG: FF D8 FF
if image_data.starts_with(&[0xFF, 0xD8, 0xFF]) {
"jpeg"
}
// PNG: 89 50 4E 47 0D 0A 1A 0A
else if image_data.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) {
"png"
}
// GIF: 47 49 46 38 (GIF8)
else if image_data.starts_with(&[0x47, 0x49, 0x46, 0x38]) {
"gif"
}
// WebP: 52 49 46 46 ... 57 45 42 50 (RIFF...WEBP)
else if image_data.len() >= 12 &&
image_data.starts_with(&[0x52, 0x49, 0x46, 0x46]) &&
&image_data[8..12] == &[0x57, 0x45, 0x42, 0x50] {
"webp"
}
// BMP: 42 4D (BM)
else if image_data.starts_with(&[0x42, 0x4D]) {
"bmp"
}
else {
"jpeg" // 默认格式
}
}
/// 使用qwen2.5vl进行图片文字坐标识别
pub async fn extract_text_coordinates(&self, request: ImageOcrRequest) -> Result<ImageOcrResponse, AppError> {
eprintln!("🔍 开始OCR识别 - 高分辨率模式: {}", request.vl_high_resolution_images);
// 获取模型分配配置
let model_assignments = self.llm_manager.get_model_assignments().await
.map_err(|e| AppError::configuration(format!("获取模型分配失败: {}", e)))?;
// 获取第一模型配置(qwen2.5vl)
let model1_config_id = model_assignments.model1_config_id
.ok_or_else(|| AppError::configuration("第一模型在模型分配中未配置"))?;
let api_configs = self.llm_manager.get_api_configs().await
.map_err(|e| AppError::configuration(format!("获取API配置失败: {}", e)))?;
let api_config = api_configs.into_iter()
.find(|config| config.id == model1_config_id && config.enabled)
.ok_or_else(|| AppError::configuration("找不到有效的qwen2.5vl模型配置"))?;
// 解码图片获取尺寸
let (image_width, image_height) = self.get_image_dimensions(&request.image_base64)?;
// 构建提示词
let prompt = self.build_ocr_prompt(&request)?;
// 调用qwen2.5vl进行识别
let text_regions = self.call_vision_model(&api_config, &request.image_base64, &prompt, request.vl_high_resolution_images).await?;
// 提取完整文本
let full_text = text_regions.iter()
.map(|region| region.text.clone())
.collect::<Vec<_>>()
.join(" ");
Ok(ImageOcrResponse {
success: true,
text_regions,
full_text,
image_width,
image_height,
error_message: None,
})
}
/// 创建图片遮罩卡
pub async fn create_image_occlusion_card(&self, request: CreateImageOcclusionRequest) -> Result<ImageOcclusionResponse, AppError> {
// 首先进行OCR识别获取文字区域
let ocr_request = ImageOcrRequest {
image_base64: request.image_base64.clone(),
extract_coordinates: true,
target_text: None,
vl_high_resolution_images: request.use_high_resolution,
};
let ocr_response = self.extract_text_coordinates(ocr_request).await?;
// 根据用户选择的区域创建遮罩
let mut masks = Vec::new();
for region_id in &request.selected_regions {
if let Some(region) = ocr_response.text_regions.iter().find(|r| r.region_id == *region_id) {
let mask = OcclusionMask {
mask_id: Uuid::new_v4().to_string(),
bbox: region.bbox,
original_text: region.text.clone(),
hint: None,
mask_style: request.mask_style.clone(),
};
masks.push(mask);
}
}
// 保存图片到本地(可选)
let image_path = self.save_image(&request.image_base64)?;
// 创建图片遮罩卡
let now = Utc::now().to_rfc3339();
let card = ImageOcclusionCard {
id: Uuid::new_v4().to_string(),
task_id: Uuid::new_v4().to_string(), // 可以关联到具体任务
image_path,
image_base64: Some(request.image_base64),
image_width: ocr_response.image_width,
image_height: ocr_response.image_height,
masks,
title: request.title,
description: request.description,
tags: request.tags,
created_at: now.clone(),
updated_at: now,
subject: request.subject,
};
// 保存到数据库
self.save_card_to_database(&card)?;
Ok(ImageOcclusionResponse {
success: true,
card: Some(card),
error_message: None,
})
}
/// 构建OCR识别提示词
fn build_ocr_prompt(&self, request: &ImageOcrRequest) -> Result<String, AppError> {
let base_prompt = if request.extract_coordinates {
r#"请分析这张图片,识别图片中的所有文字内容,并提供每个文字区域的精确坐标位置。
要求:
1. 识别图片中的所有可见文字
2. 为每个文字区域提供边界框坐标
3. 坐标格式为 [x1, y1, x2, y2],其中(x1,y1)是左上角,(x2,y2)是右下角
4. 坐标值使用相对于图片的像素位置
5. 提供识别置信度
请以JSON格式返回结果:
{
"text_regions": [
{
"text": "识别到的文字",
"bbox": [x1, y1, x2, y2],
"confidence": 0.95
}
]
}
请确保返回的坐标准确,这将用于制作交互式学习卡片。"#
} else {
"请识别图片中的所有文字内容,以纯文本形式返回。"
};
let prompt = if let Some(target) = &request.target_text {
format!("{}\n\n特别注意:重点识别包含'{}'的文字区域。", base_prompt, target)
} else {
base_prompt.to_string()
};
Ok(prompt)
}
/// 调用视觉模型进行识别
async fn call_vision_model(&self, api_config: &ApiConfig, image_base64: &str, prompt: &str, vl_high_resolution_images: bool) -> Result<Vec<TextRegion>, AppError> {
// 🎯 优化:使用新的适配器架构
if api_config.model_adapter == "google" {
// 使用新的 Gemini 适配器
let message = crate::models::ChatMessage {
role: "user".to_string(),
content: prompt.to_string(),
timestamp: chrono::Utc::now(),
thinking_content: None,
rag_sources: None,
image_paths: None,
image_base64: Some(vec![image_base64.to_string()]),
};
let client = reqwest::Client::new();
let gemini_result = crate::gemini_adapter::non_stream_chat(
&client,
api_config,
&[message],
).await?;
// 解析 Gemini 响应
return self.parse_ocr_result(&gemini_result.assistant_message);
}
// 原有的 OpenAI 兼容逻辑
let client = reqwest::Client::new();
let model_name = api_config.model.to_lowercase();
// OpenAI / Qwen 格式
let url = format!("{}/chat/completions", api_config.base_url.trim_end_matches('/'));
// 检测图像格式并构建image URL
let image_format = Self::detect_image_format_from_base64(image_base64);
eprintln!("🖼️ OCR服务检测到图像格式: {}", image_format);
let image_url = format!("data:image/{};base64,{}", image_format, image_base64);
let mut body = json!({
"model": api_config.model,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
},
{
"type": "image_url",
"image_url": {
"url": image_url
}
}
]
}
],
"max_tokens": api_config.max_output_tokens,
"temperature": api_config.temperature
});
if vl_high_resolution_images {
if let Some(obj) = body.as_object_mut() {
obj.insert("vl_high_resolution_images".to_string(), json!(true));
eprintln!("✅ 已添加高分辨率参数到API请求");
}
} else {
eprintln!("📍 使用标准分辨率模式");
}
let response = client.post(&url)
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", api_config.api_key))
.json(&body)
.send()
.await
.map_err(|e| AppError::network(format!("视觉模型请求失败: {}", e)))?;
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_default();
eprintln!("❌ API请求失败: 状态码={}, 响应={}", status, error_text);
return Err(AppError::llm(format!("视觉模型API错误 (状态码: {}): {}", status, error_text)));
}
let response_json: Value = response.json().await
.map_err(|e| AppError::llm(format!("解析响应失败: {}", e)))?;
// 提取 OpenAI 格式的响应内容
let content = response_json["choices"][0]["message"]["content"]
.as_str()
.ok_or_else(|| AppError::llm("模型响应格式错误,无法提取content字段"))?;
// 解析JSON格式的识别结果
self.parse_ocr_result(content)
}
/// 解析OCR识别结果
fn parse_ocr_result(&self, content: &str) -> Result<Vec<TextRegion>, AppError> {
// 更强大的内容清理逻辑,处理多种AI响应格式
let cleaned_content = self.extract_json_from_ai_response(content)?;
// 解析JSON
let json_value: Value = serde_json::from_str(&cleaned_content)
.map_err(|e| AppError::validation(format!("解析OCR结果失败: {} - 清理后内容: {}", e, cleaned_content)))?;
// 提取text_regions数组
let regions_array = json_value["text_regions"]
.as_array()
.ok_or_else(|| AppError::validation("OCR结果中缺少text_regions字段"))?;
let mut text_regions = Vec::new();
for (index, region) in regions_array.iter().enumerate() {
let text = region["text"]
.as_str()
.ok_or_else(|| AppError::validation(format!("第{}个区域缺少text字段", index)))?
.to_string();
let bbox_array = region["bbox"]
.as_array()
.ok_or_else(|| AppError::validation(format!("第{}个区域缺少bbox字段", index)))?;
if bbox_array.len() != 4 {
return Err(AppError::validation(format!("第{}个区域的bbox格式错误,应该包含4个坐标值", index)));
}
let bbox = [
bbox_array[0].as_f64().unwrap_or(0.0) as f32,
bbox_array[1].as_f64().unwrap_or(0.0) as f32,
bbox_array[2].as_f64().unwrap_or(0.0) as f32,
bbox_array[3].as_f64().unwrap_or(0.0) as f32,
];
let confidence = region["confidence"]
.as_f64()
.unwrap_or(1.0) as f32;
text_regions.push(TextRegion {
text,
bbox,
confidence,
region_id: format!("region_{}", index),
});
}
Ok(text_regions)
}
/// 获取图片尺寸
fn get_image_dimensions(&self, image_base64: &str) -> Result<(u32, u32), AppError> {
let image_data = general_purpose::STANDARD.decode(image_base64)
.map_err(|e| AppError::validation(format!("base64解码失败: {}", e)))?;
let img = image::load_from_memory(&image_data)
.map_err(|e| AppError::validation(format!("图片加载失败: {}", e)))?;
Ok((img.width(), img.height()))
}
/// 保存图片到本地
fn save_image(&self, image_base64: &str) -> Result<String, AppError> {
let image_data = general_purpose::STANDARD.decode(image_base64)
.map_err(|e| AppError::validation(format!("base64解码失败: {}", e)))?;
// 创建图片目录
let app_data_dir = std::env::current_dir()
.map_err(|e| AppError::file_system(format!("获取当前目录失败: {}", e)))?
.join("app_data")
.join("images")
.join("occlusion");
std::fs::create_dir_all(&app_data_dir)
.map_err(|e| AppError::file_system(format!("创建图片目录失败: {}", e)))?;
// 生成文件名
let file_name = format!("{}.jpg", Uuid::new_v4());
let file_path = app_data_dir.join(&file_name);
// 保存图片
std::fs::write(&file_path, &image_data)
.map_err(|e| AppError::file_system(format!("保存图片失败: {}", e)))?;
Ok(file_path.to_string_lossy().to_string())
}
/// 保存卡片到数据库
fn save_card_to_database(&self, card: &ImageOcclusionCard) -> Result<(), AppError> {
self.db.save_image_occlusion_card(card)
.map_err(|e| AppError::database(format!("保存图片遮罩卡失败: {}", e)))
}
/// 获取所有图片遮罩卡
pub fn get_all_image_occlusion_cards(&self) -> Result<Vec<ImageOcclusionCard>, AppError> {
self.db.get_all_image_occlusion_cards()
.map_err(|e| AppError::database(format!("获取图片遮罩卡列表失败: {}", e)))
}
/// 根据ID获取图片遮罩卡
pub fn get_image_occlusion_card(&self, card_id: &str) -> Result<Option<ImageOcclusionCard>, AppError> {
self.db.get_image_occlusion_card_by_id(card_id)
.map_err(|e| AppError::database(format!("获取图片遮罩卡失败: {}", e)))
}
/// 更新图片遮罩卡
pub fn update_image_occlusion_card(&self, card: &ImageOcclusionCard) -> Result<(), AppError> {
self.db.update_image_occlusion_card(card)
.map_err(|e| AppError::database(format!("更新图片遮罩卡失败: {}", e)))
}
/// 删除图片遮罩卡
pub fn delete_image_occlusion_card(&self, card_id: &str) -> Result<(), AppError> {
self.db.delete_image_occlusion_card(card_id)
.map_err(|e| AppError::database(format!("删除图片遮罩卡失败: {}", e)))
}
/// 从AI响应中提取JSON内容,处理markdown格式和额外文本
fn extract_json_from_ai_response(&self, content: &str) -> Result<String, AppError> {
let content = content.trim();
// 方法1: 查找```json代码块
if let Some(start) = content.find("```json") {
let after_start = &content[start + 7..]; // 跳过```json
if let Some(end) = after_start.find("```") {
let json_part = after_start[..end].trim();
return Ok(json_part.to_string());
}
}
// 方法2: 查找普通```代码块(有时AI不会标记json)
if let Some(start) = content.find("```") {
let after_start = &content[start + 3..];
if let Some(end) = after_start.find("```") {
let potential_json = after_start[..end].trim();
// 验证这是否看起来像JSON
if potential_json.starts_with('{') && potential_json.ends_with('}') {
return Ok(potential_json.to_string());
}
}
}
// 方法3: 查找JSON对象(从第一个{到最后一个})
if let Some(start) = content.find('{') {
if let Some(end) = content.rfind('}') {
if start < end {
let json_part = &content[start..=end];
return Ok(json_part.to_string());
}
}
}
// 方法4: 尝试按行分割,查找以{开头的行
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('{') {
// 从这行开始,收集到对应的}结束
let from_here = &content[content.find(trimmed).unwrap()..];
if let Some(start) = from_here.find('{') {
if let Some(end) = from_here.rfind('}') {
if start < end {
let json_part = &from_here[start..=end];
return Ok(json_part.to_string());
}
}
}
}
}
// 如果所有方法都失败,返回错误
Err(AppError::validation(format!(
"无法从AI响应中提取有效的JSON内容。响应内容: {}",
content
)))
}
}
| 16,820 | image_occlusion_service | rs | en | rust | code | {"qsc_code_num_words": 1740, "qsc_code_num_chars": 16820.0, "qsc_code_mean_word_length": 4.97126437, "qsc_code_frac_words_unique": 0.25114943, "qsc_code_frac_chars_top_2grams": 0.0216185, "qsc_code_frac_chars_top_3grams": 0.01294798, "qsc_code_frac_chars_top_4grams": 0.02774566, "qsc_code_frac_chars_dupe_5grams": 0.25849711, "qsc_code_frac_chars_dupe_6grams": 0.18473988, "qsc_code_frac_chars_dupe_7grams": 0.13595376, "qsc_code_frac_chars_dupe_8grams": 0.08612717, "qsc_code_frac_chars_dupe_9grams": 0.04520231, "qsc_code_frac_chars_dupe_10grams": 0.04520231, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02235719, "qsc_code_frac_chars_whitespace": 0.3245541, "qsc_code_size_file_byte": 16820.0, "qsc_code_num_lines": 483.0, "qsc_code_num_chars_line_max": 168.0, "qsc_code_num_chars_line_mean": 34.82401656, "qsc_code_frac_chars_alphabet": 0.73840331, "qsc_code_frac_chars_comments": 0.060761, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.10140845, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0056338, "qsc_code_frac_chars_string_length": 0.05861501, "qsc_code_frac_chars_long_word_length": 0.01215344, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00632992, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
000haoji/deep-student | src-tauri/src/enhanced_anki_service.rs | use crate::models::{
DocumentTask, TaskStatus, AnkiCard, AnkiGenerationOptions, AppError, StreamedCardPayload,
StreamEvent, AnkiDocumentGenerationRequest
};
use crate::database::Database;
use crate::llm_manager::LLMManager;
use crate::document_processing_service::DocumentProcessingService;
use crate::streaming_anki_service::StreamingAnkiService;
use std::sync::Arc;
use tauri::{Window, Emitter};
use tokio::task::JoinHandle;
pub struct EnhancedAnkiService {
db: Arc<Database>,
doc_processor: DocumentProcessingService,
streaming_service: StreamingAnkiService,
}
impl EnhancedAnkiService {
pub fn new(db: Arc<Database>, llm_manager: Arc<LLMManager>) -> Self {
let doc_processor = DocumentProcessingService::new(db.clone());
let streaming_service = StreamingAnkiService::new(db.clone(), llm_manager);
Self {
db,
doc_processor,
streaming_service,
}
}
/// 开始文档处理 - 主要入口点
pub async fn start_document_processing(
&self,
request: AnkiDocumentGenerationRequest,
window: Window,
) -> Result<String, AppError> {
let document_content = request.document_content;
let subject_name = request.subject_name;
let options = request.options.unwrap_or_else(|| AnkiGenerationOptions {
deck_name: "默认牌组".to_string(),
note_type: "Basic".to_string(),
enable_images: false,
max_cards_per_mistake: 10,
max_tokens: None,
temperature: None,
max_output_tokens_override: None,
temperature_override: None,
template_id: None,
custom_anki_prompt: None,
template_fields: None,
field_extraction_rules: None,
custom_requirements: None,
segment_overlap_size: 200,
system_prompt: None,
});
// 确定文档名称
let document_name = format!("文档_{}", chrono::Utc::now().format("%Y%m%d_%H%M%S"));
// 创建分段任务
let (document_id, tasks) = self.doc_processor
.process_document_and_create_tasks(
document_content,
document_name,
subject_name,
options,
)
.await?;
// 发送文档处理开始事件
let start_event = StreamEvent {
payload: StreamedCardPayload::DocumentProcessingStarted {
document_id: document_id.clone(),
total_segments: tasks.len() as u32,
},
};
if let Err(e) = window.emit("anki_generation_event", &start_event) {
println!("发送文档处理开始事件失败: {}", e);
}
// 异步处理所有任务
let window_clone = window.clone();
let streaming_service = Arc::new(self.streaming_service.clone());
let document_id_clone = document_id.clone();
tokio::spawn(async move {
Self::process_all_tasks_async(streaming_service, tasks, window_clone, document_id_clone).await;
});
Ok(document_id)
}
/// 异步处理所有任务
async fn process_all_tasks_async(
streaming_service: Arc<StreamingAnkiService>,
tasks: Vec<DocumentTask>,
window: Window,
document_id: String,
) {
let mut task_handles: Vec<JoinHandle<()>> = Vec::new();
// 顺序处理任务以避免API限制
for task in tasks {
let service = streaming_service.clone();
let window_clone = window.clone();
let handle = tokio::spawn(async move {
if let Err(e) = service.process_task_and_generate_cards_stream(task, window_clone).await {
println!("任务处理失败: {}", e);
}
});
task_handles.push(handle);
// 等待当前任务完成再开始下一个,避免并发API调用
if let Some(handle) = task_handles.last_mut() {
let _ = handle.await;
}
}
// 所有任务已在循环内按顺序等待完成,这里不需要再次等待。
// for handle in task_handles {
// let _ = handle.await;
// }
// 发送文档处理完成事件
let complete_event = StreamEvent {
payload: StreamedCardPayload::DocumentProcessingCompleted {
document_id,
},
};
if let Err(e) = window.emit("anki_generation_event", &complete_event) {
println!("发送文档处理完成事件失败: {}", e);
}
}
/// 手动触发单个任务处理
pub async fn trigger_task_processing(
&self,
task_id: String,
window: Window,
) -> Result<(), AppError> {
let task = self.doc_processor.get_task(&task_id)?;
if task.status != TaskStatus::Pending {
return Err(AppError::validation("任务状态不是待处理"));
}
let streaming_service = Arc::new(self.streaming_service.clone());
let window_clone = window.clone();
tokio::spawn(async move {
if let Err(e) = streaming_service.process_task_and_generate_cards_stream(task, window_clone).await {
println!("任务处理失败: {}", e);
}
});
Ok(())
}
/// 获取文档任务列表
pub fn get_document_tasks(&self, document_id: String) -> Result<Vec<DocumentTask>, AppError> {
self.doc_processor.get_document_tasks(&document_id)
}
/// 获取任务的卡片列表
pub fn get_task_cards(&self, task_id: String) -> Result<Vec<AnkiCard>, AppError> {
self.db.get_cards_for_task(&task_id)
.map_err(|e| AppError::database(format!("获取任务卡片失败: {}", e)))
}
/// 更新卡片
pub fn update_anki_card(&self, card: AnkiCard) -> Result<(), AppError> {
self.db.update_anki_card(&card)
.map_err(|e| AppError::database(format!("更新卡片失败: {}", e)))
}
/// 删除卡片
pub fn delete_anki_card(&self, card_id: String) -> Result<(), AppError> {
self.db.delete_anki_card(&card_id)
.map_err(|e| AppError::database(format!("删除卡片失败: {}", e)))
}
/// 删除任务
pub fn delete_document_task(&self, task_id: String) -> Result<(), AppError> {
self.db.delete_document_task(&task_id)
.map_err(|e| AppError::database(format!("删除任务失败: {}", e)))
}
/// 删除文档会话
pub fn delete_document_session(&self, document_id: String) -> Result<(), AppError> {
self.db.delete_document_session(&document_id)
.map_err(|e| AppError::database(format!("删除文档会话失败: {}", e)))
}
/// 导出选定内容为APKG
pub async fn export_apkg_for_selection(
&self,
document_id: Option<String>,
task_ids: Option<Vec<String>>,
card_ids: Option<Vec<String>>,
options: AnkiGenerationOptions,
) -> Result<String, AppError> {
// 根据选择获取卡片
let cards = if let Some(ids) = card_ids {
self.db.get_cards_by_ids(&ids)
.map_err(|e| AppError::database(format!("获取指定卡片失败: {}", e)))?
} else if let Some(task_ids) = task_ids {
let mut all_cards = Vec::new();
for task_id in task_ids {
let mut task_cards = self.db.get_cards_for_task(&task_id)
.map_err(|e| AppError::database(format!("获取任务卡片失败: {}", e)))?;
all_cards.append(&mut task_cards);
}
all_cards
} else if let Some(doc_id) = document_id {
self.db.get_cards_for_document(&doc_id)
.map_err(|e| AppError::database(format!("获取文档卡片失败: {}", e)))?
} else {
return Err(AppError::validation("必须指定要导出的内容"));
};
// 过滤掉错误卡片(除非用户明确要求包含)
let valid_cards: Vec<AnkiCard> = cards.into_iter()
.filter(|card| !card.is_error_card)
.collect();
if valid_cards.is_empty() {
return Err(AppError::validation("没有有效的卡片可以导出"));
}
// 调用现有的APKG导出服务
// 注意:这里需要将enhanced AnkiCard转换为原始AnkiCard格式
let simple_cards: Vec<crate::models::AnkiCard> = valid_cards.into_iter()
.map(|card| crate::models::AnkiCard {
front: card.front,
back: card.back,
text: None, // enhanced_anki_service 中的卡片没有text字段
tags: card.tags,
images: card.images,
id: card.id,
task_id: card.task_id,
is_error_card: card.is_error_card,
error_content: card.error_content,
created_at: card.created_at,
updated_at: card.updated_at,
extra_fields: std::collections::HashMap::new(),
template_id: None,
})
.collect();
// 使用现有的导出服务
let output_path = std::env::temp_dir().join(format!("anki_export_{}.apkg", uuid::Uuid::new_v4()));
crate::apkg_exporter_service::export_cards_to_apkg(
simple_cards,
options.deck_name,
options.note_type,
output_path.clone()
).await
.map_err(|e| AppError::file_system(format!("导出APKG失败: {}", e)))?;
Ok(output_path.to_string_lossy().to_string())
}
}
| 9,108 | enhanced_anki_service | rs | en | rust | code | {"qsc_code_num_words": 931, "qsc_code_num_chars": 9108.0, "qsc_code_mean_word_length": 5.3329753, "qsc_code_frac_words_unique": 0.24167562, "qsc_code_frac_chars_top_2grams": 0.03021148, "qsc_code_frac_chars_top_3grams": 0.01268882, "qsc_code_frac_chars_top_4grams": 0.02719033, "qsc_code_frac_chars_dupe_5grams": 0.22940584, "qsc_code_frac_chars_dupe_6grams": 0.19979859, "qsc_code_frac_chars_dupe_7grams": 0.16797583, "qsc_code_frac_chars_dupe_8grams": 0.14239678, "qsc_code_frac_chars_dupe_9grams": 0.10050352, "qsc_code_frac_chars_dupe_10grams": 0.07734139, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00127146, "qsc_code_frac_chars_whitespace": 0.30917874, "qsc_code_size_file_byte": 9108.0, "qsc_code_num_lines": 267.0, "qsc_code_num_chars_line_max": 113.0, "qsc_code_num_chars_line_mean": 34.11235955, "qsc_code_frac_chars_alphabet": 0.78782581, "qsc_code_frac_chars_comments": 0.05248134, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.14285714, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.03151796, "qsc_code_frac_chars_long_word_length": 0.00486674, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
000haoji/deep-student | src-tauri/src/lib.rs | // Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
pub mod models;
pub mod llm_manager;
pub mod analysis_service;
pub mod commands;
pub mod crypto;
pub mod database;
pub mod file_manager;
pub mod batch_operations;
pub mod database_optimizations;
pub mod anki_connect_service;
pub mod apkg_exporter_service;
pub mod document_processing_service;
pub mod streaming_anki_service;
pub mod enhanced_anki_service;
pub mod image_occlusion_service;
pub mod vector_store;
pub mod rag_manager;
pub mod document_parser;
pub mod gemini_adapter;
pub mod cogni_graph;
pub use commands::{
AppState, TempSession,
analyze_new_mistake, analyze_new_mistake_stream, continue_chat, continue_chat_stream, save_mistake_from_analysis,
get_mistakes, get_review_analyses, delete_review_analysis, get_mistake_details, update_mistake, delete_mistake, continue_mistake_chat, continue_mistake_chat_stream, continue_mistake_chat_stream_v2,
analyze_review_session_stream, continue_review_chat, continue_review_chat_stream,
get_statistics, save_setting, get_setting,
test_api_connection, get_supported_subjects,
get_image_as_base64, save_image_from_base64_path, cleanup_orphaned_images, get_image_statistics,
get_api_configurations, save_api_configurations, get_model_assignments, save_model_assignments,
analyze_step_by_step, start_streaming_answer, get_model_adapter_options, save_model_adapter_options, reset_model_adapter_options,
// 科目配置管理
get_all_subject_configs, get_subject_config_by_id, get_subject_config_by_name,
create_subject_config, update_subject_config, delete_subject_config, initialize_default_subject_configs,
// 批量操作
batch_delete_mistakes, batch_update_mistake_statuses, batch_update_mistake_tags,
batch_cleanup_database, batch_export_mistakes, batch_save_mistakes,
// 数据库优化
get_mistakes_optimized, get_tag_statistics_optimized, search_mistakes_fulltext,
get_mistakes_by_date_range, create_performance_indexes, analyze_query_performance,
// 回顾分析功能
start_consolidated_review_analysis, trigger_consolidated_review_stream, continue_consolidated_review_stream,
get_consolidated_review_session, get_review_analysis_by_id,
// ANKI制卡功能
generate_anki_cards_from_document,
generate_anki_cards_from_document_file,
generate_anki_cards_from_document_base64,
// AnkiConnect集成功能
check_anki_connect_status, get_anki_deck_names, get_anki_model_names,
create_anki_deck, add_cards_to_anki_connect,
// APKG导出功能
export_cards_as_apkg, export_cards_as_apkg_with_template,
// 增强ANKI功能
start_enhanced_document_processing, trigger_task_processing,
get_document_tasks, get_task_cards, update_anki_card,
delete_anki_card, delete_document_task, delete_document_session,
export_apkg_for_selection, get_document_cards,
// RAG知识库管理功能
rag_add_documents, rag_add_documents_from_content, rag_get_knowledge_base_status, rag_delete_document,
rag_query_knowledge_base, rag_get_all_documents, rag_clear_knowledge_base,
// RAG增强的AI分析功能
start_rag_enhanced_streaming_answer, continue_rag_enhanced_chat_stream,
// 独立RAG查询功能
llm_generate_answer_with_context,
// RAG配置管理功能
get_rag_settings, update_rag_settings, reset_rag_settings,
// RAG分库管理功能
create_rag_sub_library, get_rag_sub_libraries, get_rag_sub_library_by_id,
update_rag_sub_library, delete_rag_sub_library, rag_add_documents_to_library,
rag_add_documents_from_content_to_library, get_rag_documents_by_library,
move_document_to_rag_library, rag_query_knowledge_base_in_libraries,
// 文档解析功能
parse_document_from_path, parse_document_from_base64,
// 错题总结生成功能
generate_mistake_summary,
// 自定义模板管理功能
get_all_custom_templates, get_custom_template_by_id, create_custom_template,
update_custom_template, delete_custom_template, export_template, import_template,
// 图片遮罩卡功能
extract_image_text_coordinates, create_image_occlusion_card, get_all_image_occlusion_cards,
get_image_occlusion_card, update_image_occlusion_card, delete_image_occlusion_card,
// 默认模板管理功能
set_default_template, get_default_template_id,
// 测试日志相关功能
save_test_log, get_test_logs, open_log_file, open_logs_folder
};
// CogniGraph模块导入
pub use cogni_graph::handlers::{
initialize_knowledge_graph, create_problem_card, get_problem_card, search_knowledge_graph,
get_ai_recommendations, search_similar_cards, get_cards_by_tag, get_all_tags,
get_graph_config, update_graph_config, test_neo4j_connection, process_handwritten_input,
// Tag管理功能
create_tag, get_tag_hierarchy, get_tags_by_type, initialize_default_tag_hierarchy
};
use analysis_service::AnalysisService;
use database::Database;
use file_manager::FileManager;
use llm_manager::LLMManager;
use cogni_graph::handlers::GraphState;
use std::sync::Arc;
use std::collections::HashMap;
use tauri::Manager;
use tokio::sync::RwLock;
#[tauri::command]
fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name)
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.setup(|app| {
// 获取系统级应用数据目录
let app_handle = app.handle().clone();
let app_data_dir = app_handle.path()
.app_data_dir()
.expect("无法获取应用数据目录")
.join("ai-mistake-manager");
// 确保目录存在
std::fs::create_dir_all(&app_data_dir).expect("无法创建应用数据目录");
// 初始化文件管理器
let file_manager = Arc::new(
FileManager::new(app_data_dir.clone())
.expect("Failed to initialize file manager")
);
// 初始化数据库
let database_path = file_manager.get_database_path();
let database = Arc::new(
Database::new(&database_path)
.expect("Failed to initialize database")
);
// 初始化默认科目配置
if let Err(e) = database.initialize_default_subject_configs() {
println!("警告:初始化默认科目配置失败: {}", e);
}
// 初始化LLM管理器
let llm_manager = Arc::new(LLMManager::new(database.clone(), file_manager.clone()));
// 初始化分析服务
let analysis_service = Arc::new(AnalysisService::new(database.clone(), file_manager.clone()));
// 初始化临时会话存储
let temp_sessions: Arc<tokio::sync::Mutex<HashMap<String, TempSession>>> =
Arc::new(tokio::sync::Mutex::new(HashMap::new()));
// 初始化回顾分析会话存储
let review_sessions: Arc<tokio::sync::Mutex<HashMap<String, models::ConsolidatedReviewSession>>> =
Arc::new(tokio::sync::Mutex::new(HashMap::new()));
// 初始化RAG管理器
let rag_manager = Arc::new(
rag_manager::RagManager::new(database.clone(), llm_manager.clone(), file_manager.clone())
.expect("Failed to initialize RAG manager")
);
// 初始化图片遮罩服务
let image_occlusion_service = Arc::new(
image_occlusion_service::ImageOcclusionService::new(database.clone(), llm_manager.clone())
);
// 初始化CogniGraph状态
let graph_state = Arc::new(RwLock::new(GraphState::new()));
let app_state = AppState {
analysis_service,
database,
file_manager,
temp_sessions,
llm_manager: llm_manager.clone(),
review_sessions,
rag_manager,
image_occlusion_service,
};
// 将状态注册到Tauri应用
app.manage(app_state);
app.manage(graph_state);
app.manage(llm_manager);
Ok(())
})
.invoke_handler(tauri::generate_handler![
greet,
// 错题分析相关
analyze_new_mistake,
analyze_new_mistake_stream,
continue_chat,
continue_chat_stream,
save_mistake_from_analysis,
// 分步骤分析
analyze_step_by_step,
start_streaming_answer,
// 错题库管理
get_mistakes,
get_review_analyses,
delete_review_analysis,
get_mistake_details,
update_mistake,
delete_mistake,
continue_mistake_chat,
continue_mistake_chat_stream,
continue_mistake_chat_stream_v2,
// 回顾分析
analyze_review_session_stream,
continue_review_chat,
continue_review_chat_stream,
// 统计和设置
get_statistics,
save_setting,
get_setting,
test_api_connection,
get_supported_subjects,
// 专用配置管理
get_api_configurations,
save_api_configurations,
get_model_assignments,
save_model_assignments,
get_model_adapter_options,
save_model_adapter_options,
reset_model_adapter_options,
// 文件管理
get_image_as_base64,
save_image_from_base64_path,
cleanup_orphaned_images,
get_image_statistics,
// 科目配置管理
get_all_subject_configs,
get_subject_config_by_id,
get_subject_config_by_name,
create_subject_config,
update_subject_config,
delete_subject_config,
initialize_default_subject_configs,
// 批量操作
batch_delete_mistakes,
batch_update_mistake_statuses,
batch_update_mistake_tags,
batch_cleanup_database,
batch_export_mistakes,
batch_save_mistakes,
// 数据库优化
get_mistakes_optimized,
get_tag_statistics_optimized,
search_mistakes_fulltext,
get_mistakes_by_date_range,
create_performance_indexes,
analyze_query_performance,
// 回顾分析功能
start_consolidated_review_analysis,
trigger_consolidated_review_stream,
continue_consolidated_review_stream,
get_consolidated_review_session,
get_review_analysis_by_id,
// ANKI制卡功能
generate_anki_cards_from_document,
generate_anki_cards_from_document_file,
generate_anki_cards_from_document_base64,
// AnkiConnect集成功能
check_anki_connect_status,
get_anki_deck_names,
get_anki_model_names,
create_anki_deck,
add_cards_to_anki_connect,
// APKG导出功能
export_cards_as_apkg,
export_cards_as_apkg_with_template,
// 增强ANKI功能
start_enhanced_document_processing,
trigger_task_processing,
get_document_tasks,
get_task_cards,
update_anki_card,
delete_anki_card,
delete_document_task,
delete_document_session,
export_apkg_for_selection,
get_document_cards,
// RAG知识库管理功能
rag_add_documents,
rag_add_documents_from_content,
rag_get_knowledge_base_status,
rag_delete_document,
rag_query_knowledge_base,
rag_get_all_documents,
rag_clear_knowledge_base,
// RAG增强的AI分析功能
start_rag_enhanced_streaming_answer,
continue_rag_enhanced_chat_stream,
// 独立RAG查询功能
llm_generate_answer_with_context,
// RAG配置管理功能
get_rag_settings,
update_rag_settings,
reset_rag_settings,
// RAG分库管理功能
create_rag_sub_library,
get_rag_sub_libraries,
get_rag_sub_library_by_id,
update_rag_sub_library,
delete_rag_sub_library,
rag_add_documents_to_library,
rag_add_documents_from_content_to_library,
get_rag_documents_by_library,
move_document_to_rag_library,
rag_query_knowledge_base_in_libraries,
// 文档解析功能
parse_document_from_path,
parse_document_from_base64,
// 错题总结生成
generate_mistake_summary,
// 自定义模板管理功能
get_all_custom_templates,
get_custom_template_by_id,
create_custom_template,
update_custom_template,
delete_custom_template,
export_template,
import_template,
// 图片遮罩卡功能
extract_image_text_coordinates,
create_image_occlusion_card,
get_all_image_occlusion_cards,
get_image_occlusion_card,
update_image_occlusion_card,
delete_image_occlusion_card,
// 默认模板管理功能
set_default_template,
get_default_template_id,
// 测试日志相关功能
save_test_log,
get_test_logs,
open_log_file,
open_logs_folder,
// CogniGraph知识图谱功能
initialize_knowledge_graph,
create_problem_card,
get_problem_card,
search_knowledge_graph,
get_ai_recommendations,
search_similar_cards,
get_cards_by_tag,
get_all_tags,
get_graph_config,
update_graph_config,
test_neo4j_connection,
process_handwritten_input,
// Tag管理功能
create_tag,
get_tag_hierarchy,
get_tags_by_type,
initialize_default_tag_hierarchy
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
| 13,878 | lib | rs | en | rust | code | {"qsc_code_num_words": 1499, "qsc_code_num_chars": 13878.0, "qsc_code_mean_word_length": 5.58438959, "qsc_code_frac_words_unique": 0.17745163, "qsc_code_frac_chars_top_2grams": 0.0143352, "qsc_code_frac_chars_top_3grams": 0.0143352, "qsc_code_frac_chars_top_4grams": 0.01505197, "qsc_code_frac_chars_dupe_5grams": 0.75450962, "qsc_code_frac_chars_dupe_6grams": 0.74758093, "qsc_code_frac_chars_dupe_7grams": 0.73252897, "qsc_code_frac_chars_dupe_8grams": 0.71460996, "qsc_code_frac_chars_dupe_9grams": 0.7067256, "qsc_code_frac_chars_dupe_10grams": 0.7067256, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00199164, "qsc_code_frac_chars_whitespace": 0.2764087, "qsc_code_size_file_byte": 13878.0, "qsc_code_num_lines": 361.0, "qsc_code_num_chars_line_max": 202.0, "qsc_code_num_chars_line_mean": 38.4432133, "qsc_code_frac_chars_alphabet": 0.83160725, "qsc_code_frac_chars_comments": 0.06016717, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.06713781, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01748064, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 1, "qsc_code_frac_chars_dupe_7grams": 1, "qsc_code_frac_chars_dupe_8grams": 1, "qsc_code_frac_chars_dupe_9grams": 1, "qsc_code_frac_chars_dupe_10grams": 1, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
000haoji/deep-student | src-tauri/src/rag_manager.rs | use crate::models::{
DocumentChunk, DocumentChunkWithEmbedding, RetrievedChunk, RagQueryOptions,
KnowledgeBaseStatusPayload, DocumentProcessingStatus, DocumentProcessingStage,
RagQueryResponse, AppError
};
use crate::vector_store::{SqliteVectorStore, VectorStore};
use crate::llm_manager::LLMManager;
use crate::database::Database;
use crate::file_manager::FileManager;
use std::sync::Arc;
use std::collections::HashMap;
use uuid::Uuid;
use tauri::{Window, Emitter};
use serde_json::Value;
use base64::{Engine as _, engine::general_purpose};
use regex::Regex;
type Result<T> = std::result::Result<T, AppError>;
/// 文档分块策略
#[derive(Debug, Clone, PartialEq)]
pub enum ChunkingStrategy {
FixedSize,
Semantic,
}
/// 分块配置
#[derive(Debug, Clone)]
pub struct ChunkingConfig {
pub strategy: ChunkingStrategy,
pub chunk_size: usize,
pub chunk_overlap: usize,
pub min_chunk_size: usize,
}
impl Default for ChunkingConfig {
fn default() -> Self {
Self {
strategy: ChunkingStrategy::FixedSize,
chunk_size: 512,
chunk_overlap: 50,
min_chunk_size: 20,
}
}
}
/// RAG管理器 - 协调整个RAG流程
pub struct RagManager {
vector_store: SqliteVectorStore,
llm_manager: Arc<LLMManager>,
file_manager: Arc<FileManager>,
database: Arc<Database>,
}
impl RagManager {
/// 创建新的RAG管理器实例
pub fn new(
database: Arc<Database>,
llm_manager: Arc<LLMManager>,
file_manager: Arc<FileManager>
) -> Result<Self> {
let vector_store = SqliteVectorStore::new(database.clone())?;
Ok(Self {
vector_store,
llm_manager,
file_manager,
database,
})
}
/// 添加文档到知识库
pub async fn add_documents_to_knowledge_base(
&self,
file_paths: Vec<String>,
window: Window
) -> Result<String> {
self.add_documents_to_knowledge_base_with_library(file_paths, window, None).await
}
/// 添加文档到指定分库
pub async fn add_documents_to_knowledge_base_with_library(
&self,
file_paths: Vec<String>,
window: Window,
sub_library_id: Option<String>
) -> Result<String> {
println!("🚀 开始处理 {} 个文档到知识库", file_paths.len());
let mut processed_documents = Vec::new();
let mut total_chunks = 0;
for (index, file_path) in file_paths.iter().enumerate() {
let progress = (index as f32) / (file_paths.len() as f32);
// 发送处理状态更新
self.emit_processing_status(&window, "overall", "processing", progress,
&format!("正在处理文档 {}/{}", index + 1, file_paths.len())).await;
match self.process_single_document_with_library(file_path, &window, sub_library_id.as_deref()).await {
Ok(chunk_count) => {
total_chunks += chunk_count;
processed_documents.push(file_path.clone());
println!("✅ 文档处理完成: {} ({} 个块)", file_path, chunk_count);
}
Err(e) => {
println!("❌ 文档处理失败: {} - {}", file_path, e);
self.emit_processing_status(&window, "overall", "error", progress,
&format!("文档处理失败: {}", e)).await;
}
}
}
// 发送完成状态
self.emit_processing_status(&window, "overall", "completed", 1.0,
&format!("处理完成:{} 个文档,{} 个文本块", processed_documents.len(), total_chunks)).await;
Ok(format!("成功处理 {} 个文档,共 {} 个文本块", processed_documents.len(), total_chunks))
}
/// 处理单个文档
async fn process_single_document(&self, file_path: &str, window: &Window) -> Result<usize> {
self.process_single_document_with_library(file_path, window, None).await
}
/// 处理单个文档到指定分库
async fn process_single_document_with_library(&self, file_path: &str, window: &Window, sub_library_id: Option<&str>) -> Result<usize> {
let document_id = Uuid::new_v4().to_string();
let file_name = std::path::Path::new(file_path)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("unknown")
.to_string();
println!("📄 开始处理文档: {} (ID: {})", file_name, document_id);
// 1. 读取文件内容
self.emit_document_status(window, &document_id, &file_name, DocumentProcessingStage::Reading, 0.1).await;
let content = self.read_file_content(file_path).await?;
// 2. 预处理
self.emit_document_status(window, &document_id, &file_name, DocumentProcessingStage::Preprocessing, 0.2).await;
let processed_content = self.preprocess_content(&content);
// 3. 文本分块
self.emit_document_status(window, &document_id, &file_name, DocumentProcessingStage::Chunking, 0.3).await;
let chunks = self.chunk_text_with_progress(&document_id, &processed_content, &file_name, Some(window), &document_id, &file_name).await?;
// 4. 生成向量嵌入
let chunks_with_embeddings = self.generate_embeddings_for_chunks_with_progress(chunks, Some(window), &document_id, &file_name).await?;
// 5. 存储到向量数据库
self.emit_document_status(window, &document_id, &file_name, DocumentProcessingStage::Storing, 0.8).await;
self.vector_store.add_chunks(chunks_with_embeddings.clone()).await?;
// 6. 更新文档记录
let target_library_id = sub_library_id.unwrap_or("default");
self.vector_store.add_document_record_with_library(&document_id, &file_name, Some(file_path), None, target_library_id)?;
self.vector_store.update_document_chunk_count(&document_id, chunks_with_embeddings.len())?;
// 7. 完成
self.emit_document_status(window, &document_id, &file_name, DocumentProcessingStage::Completed, 1.0).await;
Ok(chunks_with_embeddings.len())
}
/// 从文件内容添加文档到知识库
pub async fn add_documents_from_content(
&self,
documents: Vec<serde_json::Value>,
window: Window
) -> Result<String> {
println!("🚀 开始从内容处理 {} 个文档到知识库", documents.len());
let mut processed_documents = Vec::new();
let mut total_chunks = 0;
for (index, doc_data) in documents.iter().enumerate() {
let progress = (index as f32) / (documents.len() as f32);
// 解析文档数据
let file_name = doc_data.get("fileName")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
let content = doc_data.get("content")
.and_then(|v| v.as_str())
.unwrap_or("");
if content.is_empty() {
println!("⚠️ 跳过空内容文档: {}", file_name);
continue;
}
// 发送处理状态更新
self.emit_processing_status(&window, "overall", "processing", progress,
&format!("正在处理文档 {}/{}", index + 1, documents.len())).await;
match self.process_document_content(&file_name, content, &window).await {
Ok(chunk_count) => {
total_chunks += chunk_count;
processed_documents.push(file_name.clone());
println!("✅ 文档内容处理完成: {} ({} 个块)", file_name, chunk_count);
}
Err(e) => {
println!("❌ 文档内容处理失败: {} - {}", file_name, e);
self.emit_processing_status(&window, "overall", "error", progress,
&format!("文档处理失败: {}", e)).await;
}
}
}
// 发送完成状态
self.emit_processing_status(&window, "overall", "completed", 1.0,
&format!("处理完成:{} 个文档,{} 个文本块", processed_documents.len(), total_chunks)).await;
Ok(format!("成功处理 {} 个文档,共 {} 个文本块", processed_documents.len(), total_chunks))
}
/// 从文件内容添加文档到指定分库
pub async fn add_documents_from_content_to_library(
&self,
documents: Vec<serde_json::Value>,
window: Window,
sub_library_id: Option<String>
) -> Result<String> {
println!("🚀 开始从内容处理 {} 个文档到分库: {:?}", documents.len(), sub_library_id);
let mut processed_documents = Vec::new();
let mut total_chunks = 0;
for (index, doc_data) in documents.iter().enumerate() {
let progress = (index as f32) / (documents.len() as f32);
// 解析文档数据
let file_name = doc_data.get("fileName")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
let content = doc_data.get("content")
.and_then(|v| v.as_str())
.unwrap_or("");
if content.is_empty() {
println!("⚠️ 跳过空内容文档: {}", file_name);
continue;
}
// 发送处理状态更新
self.emit_processing_status(&window, "overall", "processing", progress,
&format!("正在处理文档 {}/{}", index + 1, documents.len())).await;
match self.process_document_content_with_library(&file_name, content, &window, sub_library_id.as_deref()).await {
Ok(chunk_count) => {
total_chunks += chunk_count;
processed_documents.push(file_name.clone());
println!("✅ 文档内容处理完成: {} ({} 个块)", file_name, chunk_count);
}
Err(e) => {
println!("❌ 文档内容处理失败: {} - {}", file_name, e);
self.emit_processing_status(&window, "overall", "error", progress,
&format!("文档处理失败: {}", e)).await;
}
}
}
// 发送完成状态
self.emit_processing_status(&window, "overall", "completed", 1.0,
&format!("处理完成:{} 个文档,{} 个文本块", processed_documents.len(), total_chunks)).await;
Ok(format!("成功处理 {} 个文档,共 {} 个文本块", processed_documents.len(), total_chunks))
}
/// 处理文档内容(不从文件路径读取,直接使用提供的内容)
async fn process_document_content(&self, file_name: &str, content: &str, window: &Window) -> Result<usize> {
let document_id = Uuid::new_v4().to_string();
println!("📄 开始处理文档内容: {} (ID: {})", file_name, document_id);
// 发送文档开始处理状态
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Reading, 0.1).await;
// 根据文件扩展名判断是否需要解码base64
let processed_content = if file_name.ends_with(".txt") || file_name.ends_with(".md") {
// 文本文件,直接使用内容
println!("📝 处理文本文件: {}", file_name);
content.to_string()
} else {
// 二进制文件,假设是base64编码,需要解码后处理
println!("🔄 开始解码Base64内容: {} 字节", content.len());
match general_purpose::STANDARD.decode(content) {
Ok(decoded_bytes) => {
println!("✅ Base64解码成功,解码后大小: {} 字节", decoded_bytes.len());
// 根据文件扩展名处理二进制文件
if file_name.ends_with(".pdf") {
println!("📄 开始解析PDF文件: {}", file_name);
self.extract_pdf_text_from_memory(&decoded_bytes).await?
} else if file_name.ends_with(".docx") {
println!("📄 开始解析DOCX文件: {}", file_name);
self.extract_docx_text_from_memory(&decoded_bytes).await?
} else {
return Err(AppError::validation(format!(
"不支持的文件格式: {}",
file_name
)));
}
}
Err(_) => {
// 不是有效的base64,当作普通文本处理
println!("⚠️ Base64解码失败,当作普通文本处理: {}", file_name);
content.to_string()
}
}
};
println!("📊 文档解析完成,提取文本长度: {} 字符", processed_content.len());
// 预处理内容
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Preprocessing, 0.2).await;
println!("🔧 开始预处理文档内容: {}", file_name);
let preprocessed_content = self.preprocess_content(&processed_content);
println!("✅ 预处理完成,处理后长度: {} 字符", preprocessed_content.len());
// 分块
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Chunking, 0.3).await;
println!("✂️ 开始文本分块: {}", file_name);
let chunks = self.chunk_text_with_progress(&document_id, &preprocessed_content, file_name, Some(window), &document_id, file_name).await?;
println!("✅ 分块完成,生成 {} 个文本块", chunks.len());
if chunks.is_empty() {
return Err(AppError::validation("文档内容为空或无法分块"));
}
// 生成嵌入
println!("🧠 开始生成向量嵌入: {} 个文本块", chunks.len());
let chunks_with_embeddings = self.generate_embeddings_for_chunks_with_progress(chunks, Some(window), &document_id, file_name).await?;
println!("✅ 向量嵌入生成完成: {} 个向量", chunks_with_embeddings.len());
// 记录文档信息
let file_size = processed_content.len() as u64;
self.vector_store.add_document_record(&document_id, file_name, None, Some(file_size))?;
// 存储到向量数据库
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Storing, 0.8).await;
self.vector_store.add_chunks(chunks_with_embeddings.clone()).await?;
// 更新文档块数统计
self.vector_store.update_document_chunk_count(&document_id, chunks_with_embeddings.len())?;
// 发送完成状态
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Completed, 1.0).await;
println!("🎉 文档处理完全完成: {} ({} 个文本块)", file_name, chunks_with_embeddings.len());
Ok(chunks_with_embeddings.len())
}
/// 处理文档内容到指定分库(不从文件路径读取,直接使用提供的内容)
async fn process_document_content_with_library(&self, file_name: &str, content: &str, window: &Window, sub_library_id: Option<&str>) -> Result<usize> {
let document_id = Uuid::new_v4().to_string();
println!("📄 开始处理文档内容到分库: {} (ID: {}, 分库: {:?})", file_name, document_id, sub_library_id);
println!("📊 文档原始大小: {} 字节", content.len());
// 发送文档开始处理状态
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Reading, 0.1).await;
// 根据文件扩展名判断是否需要解码base64
println!("🔍 开始解析文档内容: {}", file_name);
let processed_content = if file_name.ends_with(".txt") || file_name.ends_with(".md") {
// 文本文件,直接使用内容
println!("📝 处理文本文件: {}", file_name);
content.to_string()
} else {
// 二进制文件,假设是base64编码,需要解码后处理
println!("🔄 开始解码Base64内容: {} 字节", content.len());
match general_purpose::STANDARD.decode(content) {
Ok(decoded_bytes) => {
println!("✅ Base64解码成功,解码后大小: {} 字节", decoded_bytes.len());
// 根据文件扩展名处理二进制文件
if file_name.ends_with(".pdf") {
println!("📄 开始解析PDF文件: {}", file_name);
self.extract_pdf_text_from_memory(&decoded_bytes).await?
} else if file_name.ends_with(".docx") {
println!("📄 开始解析DOCX文件: {}", file_name);
self.extract_docx_text_from_memory(&decoded_bytes).await?
} else {
return Err(AppError::validation(format!(
"不支持的文件格式: {}",
file_name
)));
}
}
Err(_) => {
// 不是有效的base64,当作普通文本处理
println!("⚠️ Base64解码失败,当作普通文本处理: {}", file_name);
content.to_string()
}
}
};
println!("📊 文档解析完成,提取文本长度: {} 字符", processed_content.len());
// 预处理内容
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Preprocessing, 0.2).await;
println!("🔧 开始预处理文档内容: {}", file_name);
let preprocessed_content = self.preprocess_content(&processed_content);
println!("✅ 预处理完成,处理后长度: {} 字符", preprocessed_content.len());
// 分块
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Chunking, 0.3).await;
println!("✂️ 开始文本分块: {}", file_name);
let chunks = self.chunk_text_with_progress(&document_id, &preprocessed_content, file_name, Some(window), &document_id, file_name).await?;
println!("✅ 分块完成,生成 {} 个文本块", chunks.len());
if chunks.is_empty() {
return Err(AppError::validation("文档内容为空或无法分块"));
}
// 生成嵌入
println!("🧠 开始生成向量嵌入: {} 个文本块", chunks.len());
let chunks_with_embeddings = self.generate_embeddings_for_chunks_with_progress(chunks, Some(window), &document_id, file_name).await?;
println!("✅ 向量嵌入生成完成: {} 个向量", chunks_with_embeddings.len());
// 记录文档信息到指定分库
let file_size = processed_content.len() as u64;
let target_library_id = sub_library_id.unwrap_or("default");
println!("📋 添加文档记录到分库: {} -> {}", file_name, target_library_id);
self.vector_store.add_document_record_with_library(&document_id, file_name, None, Some(file_size), target_library_id)?;
// 存储到向量数据库
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Storing, 0.8).await;
println!("💾 开始存储到向量数据库: {} 个向量", chunks_with_embeddings.len());
self.vector_store.add_chunks(chunks_with_embeddings.clone()).await?;
println!("✅ 向量存储完成");
// 更新文档块数统计
println!("📊 更新文档统计信息");
self.vector_store.update_document_chunk_count(&document_id, chunks_with_embeddings.len())?;
// 发送完成状态
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Completed, 1.0).await;
println!("🎉 文档处理完全完成: {} ({} 个文本块)", file_name, chunks_with_embeddings.len());
Ok(chunks_with_embeddings.len())
}
/// 读取文件内容
async fn read_file_content(&self, file_path: &str) -> Result<String> {
let path = std::path::Path::new(file_path);
// 检查文件是否存在
if !path.exists() {
return Err(AppError::file_system(format!("读取文档文件失败: 系统找不到指定的文件。文件路径: {}", file_path)));
}
// 检查是否为文件(而非目录)
if !path.is_file() {
return Err(AppError::file_system(format!("读取文档文件失败: 指定路径不是文件。文件路径: {}", file_path)));
}
let extension = path.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("")
.to_lowercase();
println!("📖 正在读取文件: {} (类型: {})", file_path, extension);
match extension.as_str() {
"txt" | "md" | "markdown" => {
std::fs::read_to_string(file_path)
.map_err(|e| AppError::file_system(format!("读取文本文件失败: {} (文件路径: {})", e, file_path)))
}
"pdf" => {
self.extract_pdf_text(file_path).await
}
"docx" => {
self.extract_docx_text(file_path).await
}
_ => {
Err(AppError::validation(format!("不支持的文件类型: {} (文件路径: {})", extension, file_path)))
}
}
}
/// 预处理文本内容
fn preprocess_content(&self, content: &str) -> String {
// 基础文本清理
content
.lines()
.map(|line| line.trim())
.filter(|line| !line.is_empty())
.collect::<Vec<_>>()
.join("\n")
}
/// 从数据库加载分块配置
fn load_chunking_config(&self) -> Result<ChunkingConfig> {
match self.database.get_rag_configuration() {
Ok(Some(config)) => {
let strategy = match config.chunking_strategy.as_str() {
"semantic" => ChunkingStrategy::Semantic,
_ => ChunkingStrategy::FixedSize,
};
Ok(ChunkingConfig {
strategy,
chunk_size: config.chunk_size as usize,
chunk_overlap: config.chunk_overlap as usize,
min_chunk_size: config.min_chunk_size as usize,
})
}
Ok(None) => {
// 没有配置时使用默认值
Ok(ChunkingConfig::default())
}
Err(e) => {
println!("⚠️ 无法加载RAG配置,使用默认值: {}", e);
Ok(ChunkingConfig::default())
}
}
}
/// 将文本分块 - 支持不同策略
fn chunk_text(&self, document_id: &str, content: &str, file_name: &str) -> Result<Vec<DocumentChunk>> {
// 从数据库加载分块配置
let config = self.load_chunking_config()?;
match config.strategy {
ChunkingStrategy::FixedSize => {
self.chunk_text_fixed_size(document_id, content, file_name, &config)
}
ChunkingStrategy::Semantic => {
self.chunk_text_semantic(document_id, content, file_name, &config)
}
}
}
/// 将文本分块并发送进度更新
async fn chunk_text_with_progress(&self, document_id: &str, content: &str, file_name: &str, window: Option<&Window>, doc_id: &str, doc_name: &str) -> Result<Vec<DocumentChunk>> {
// 从数据库加载分块配置
let config = self.load_chunking_config()?;
match config.strategy {
ChunkingStrategy::FixedSize => {
self.chunk_text_fixed_size_with_progress(document_id, content, file_name, &config, window, doc_id, doc_name).await
}
ChunkingStrategy::Semantic => {
self.chunk_text_semantic_with_progress(document_id, content, file_name, &config, window, doc_id, doc_name).await
}
}
}
/// 固定大小分块策略
fn chunk_text_fixed_size(&self, document_id: &str, content: &str, file_name: &str, config: &ChunkingConfig) -> Result<Vec<DocumentChunk>> {
let mut chunks = Vec::new();
let chars: Vec<char> = content.chars().collect();
let mut start = 0;
let mut chunk_index = 0;
while start < chars.len() {
let end = std::cmp::min(start + config.chunk_size, chars.len());
let chunk_text: String = chars[start..end].iter().collect();
// 跳过过短的块
if chunk_text.trim().len() < config.min_chunk_size {
start = end;
continue;
}
let mut metadata = HashMap::new();
metadata.insert("file_name".to_string(), file_name.to_string());
metadata.insert("chunk_index".to_string(), chunk_index.to_string());
metadata.insert("start_pos".to_string(), start.to_string());
metadata.insert("end_pos".to_string(), end.to_string());
metadata.insert("chunking_strategy".to_string(), "fixed_size".to_string());
let chunk = DocumentChunk {
id: Uuid::new_v4().to_string(),
document_id: document_id.to_string(),
chunk_index,
text: chunk_text.trim().to_string(),
metadata,
};
chunks.push(chunk);
chunk_index += 1;
// 计算下一个起始位置,考虑重叠
start = if end == chars.len() {
end
} else {
std::cmp::max(start + 1, end - config.chunk_overlap)
};
}
println!("📝 固定大小分块完成: {} 个块", chunks.len());
Ok(chunks)
}
/// 固定大小分块策略(带进度更新)
async fn chunk_text_fixed_size_with_progress(&self, document_id: &str, content: &str, file_name: &str, config: &ChunkingConfig, window: Option<&Window>, doc_id: &str, doc_name: &str) -> Result<Vec<DocumentChunk>> {
let mut chunks = Vec::new();
let chars: Vec<char> = content.chars().collect();
let mut start = 0;
let mut chunk_index = 0;
// 估算总的分块数量(用于进度计算)
let estimated_total_chunks = (chars.len() / config.chunk_size) + 1;
while start < chars.len() {
let end = std::cmp::min(start + config.chunk_size, chars.len());
let chunk_text: String = chars[start..end].iter().collect();
// 跳过过短的块
if chunk_text.trim().len() < config.min_chunk_size {
start = end;
continue;
}
let mut metadata = HashMap::new();
metadata.insert("file_name".to_string(), file_name.to_string());
metadata.insert("chunk_index".to_string(), chunk_index.to_string());
metadata.insert("start_pos".to_string(), start.to_string());
metadata.insert("end_pos".to_string(), end.to_string());
metadata.insert("chunking_strategy".to_string(), "fixed_size".to_string());
let chunk = DocumentChunk {
id: Uuid::new_v4().to_string(),
document_id: document_id.to_string(),
chunk_index,
text: chunk_text.trim().to_string(),
metadata,
};
chunks.push(chunk);
chunk_index += 1;
// 发送进度更新
if let Some(w) = window {
let progress = 0.3 + (chunk_index as f32 / estimated_total_chunks as f32) * 0.15; // 从30%到45%
self.emit_document_status_with_chunks(w, doc_id, doc_name, DocumentProcessingStage::Chunking, progress, chunk_index, estimated_total_chunks).await;
}
// 计算下一个起始位置,考虑重叠
start = if end == chars.len() {
end
} else {
std::cmp::max(start + 1, end - config.chunk_overlap)
};
}
// 发送分块完成状态
if let Some(w) = window {
self.emit_document_status_with_chunks(w, doc_id, doc_name, DocumentProcessingStage::Chunking, 0.45, chunks.len(), chunks.len()).await;
}
println!("📝 固定大小分块完成: {} 个块", chunks.len());
Ok(chunks)
}
/// 语义分块策略
fn chunk_text_semantic(&self, document_id: &str, content: &str, file_name: &str, config: &ChunkingConfig) -> Result<Vec<DocumentChunk>> {
let mut chunks = Vec::new();
let mut chunk_index = 0;
// 1. 首先按段落分割
let paragraphs = self.split_into_paragraphs(content);
let mut current_chunk = String::new();
let mut current_sentences = Vec::new();
let mut paragraph_index = 0;
for paragraph in paragraphs {
if paragraph.trim().is_empty() {
continue;
}
// 2. 将段落按句子分割
let sentences = self.split_into_sentences(¶graph);
for sentence in sentences {
let sentence = sentence.trim();
if sentence.is_empty() {
continue;
}
// 检查当前块加上新句子是否超过目标大小
let potential_chunk = if current_chunk.is_empty() {
sentence.to_string()
} else {
format!("{} {}", current_chunk, sentence)
};
if potential_chunk.len() <= config.chunk_size {
// 可以添加到当前块
current_chunk = potential_chunk;
current_sentences.push(sentence.to_string());
} else {
// 当前块已满,保存当前块并开始新块
if !current_chunk.is_empty() && current_chunk.len() >= config.min_chunk_size {
let chunk = self.create_semantic_chunk(
document_id,
¤t_chunk,
file_name,
chunk_index,
paragraph_index,
¤t_sentences,
);
chunks.push(chunk);
chunk_index += 1;
// 实现重叠:保留最后1-2个句子作为新块的开始
let overlap_sentences = if current_sentences.len() > 2 {
current_sentences[current_sentences.len()-2..].to_vec()
} else if current_sentences.len() > 1 {
current_sentences[current_sentences.len()-1..].to_vec()
} else {
Vec::new()
};
current_chunk = if overlap_sentences.is_empty() {
sentence.to_string()
} else {
format!("{} {}", overlap_sentences.join(" "), sentence)
};
current_sentences = overlap_sentences;
current_sentences.push(sentence.to_string());
} else {
// 如果当前句子本身就很长,直接作为一个块
if sentence.len() >= config.min_chunk_size {
let chunk = self.create_semantic_chunk(
document_id,
sentence,
file_name,
chunk_index,
paragraph_index,
&vec![sentence.to_string()],
);
chunks.push(chunk);
chunk_index += 1;
}
current_chunk.clear();
current_sentences.clear();
}
}
}
paragraph_index += 1;
}
// 处理最后一个块
if !current_chunk.is_empty() && current_chunk.len() >= config.min_chunk_size {
let chunk = self.create_semantic_chunk(
document_id,
¤t_chunk,
file_name,
chunk_index,
paragraph_index,
¤t_sentences,
);
chunks.push(chunk);
}
println!("📝 语义分块完成: {} 个块", chunks.len());
Ok(chunks)
}
/// 语义分块策略(带进度更新)
async fn chunk_text_semantic_with_progress(&self, document_id: &str, content: &str, file_name: &str, config: &ChunkingConfig, window: Option<&Window>, doc_id: &str, doc_name: &str) -> Result<Vec<DocumentChunk>> {
let mut chunks = Vec::new();
let mut chunk_index = 0;
// 1. 首先按段落分割
let paragraphs = self.split_into_paragraphs(content);
let total_paragraphs = paragraphs.len();
let mut current_chunk = String::new();
let mut current_sentences = Vec::new();
let mut paragraph_index = 0;
for paragraph in paragraphs {
if paragraph.trim().is_empty() {
paragraph_index += 1;
continue;
}
// 2. 将段落按句子分割
let sentences = self.split_into_sentences(¶graph);
for sentence in sentences {
let sentence = sentence.trim();
if sentence.is_empty() {
continue;
}
// 检查当前块加上新句子是否超过目标大小
let potential_chunk = if current_chunk.is_empty() {
sentence.to_string()
} else {
format!("{} {}", current_chunk, sentence)
};
if potential_chunk.len() <= config.chunk_size {
// 可以添加到当前块
current_chunk = potential_chunk;
current_sentences.push(sentence.to_string());
} else {
// 当前块已满,保存当前块并开始新块
if !current_chunk.is_empty() && current_chunk.len() >= config.min_chunk_size {
let chunk = self.create_semantic_chunk(
document_id,
¤t_chunk,
file_name,
chunk_index,
paragraph_index,
¤t_sentences,
);
chunks.push(chunk);
chunk_index += 1;
// 发送进度更新
if let Some(w) = window {
let progress = 0.3 + (paragraph_index as f32 / total_paragraphs as f32) * 0.15; // 从30%到45%
let estimated_total_chunks = (content.len() / config.chunk_size) + 1;
self.emit_document_status_with_chunks(w, doc_id, doc_name, DocumentProcessingStage::Chunking, progress, chunk_index, estimated_total_chunks).await;
}
// 实现重叠:保留最后1-2个句子作为新块的开始
let overlap_sentences = if current_sentences.len() > 2 {
current_sentences[current_sentences.len()-2..].to_vec()
} else if current_sentences.len() > 1 {
current_sentences[current_sentences.len()-1..].to_vec()
} else {
Vec::new()
};
current_chunk = if overlap_sentences.is_empty() {
sentence.to_string()
} else {
format!("{} {}", overlap_sentences.join(" "), sentence)
};
current_sentences = overlap_sentences;
current_sentences.push(sentence.to_string());
} else {
// 如果当前句子本身就很长,直接作为一个块
if sentence.len() >= config.min_chunk_size {
let chunk = self.create_semantic_chunk(
document_id,
sentence,
file_name,
chunk_index,
paragraph_index,
&vec![sentence.to_string()],
);
chunks.push(chunk);
chunk_index += 1;
}
current_chunk.clear();
current_sentences.clear();
}
}
}
paragraph_index += 1;
}
// 处理最后一个块
if !current_chunk.is_empty() && current_chunk.len() >= config.min_chunk_size {
let chunk = self.create_semantic_chunk(
document_id,
¤t_chunk,
file_name,
chunk_index,
paragraph_index,
¤t_sentences,
);
chunks.push(chunk);
}
// 发送分块完成状态
if let Some(w) = window {
self.emit_document_status_with_chunks(w, doc_id, doc_name, DocumentProcessingStage::Chunking, 0.45, chunks.len(), chunks.len()).await;
}
println!("📝 语义分块完成: {} 个块", chunks.len());
Ok(chunks)
}
/// 按段落分割文本
fn split_into_paragraphs(&self, content: &str) -> Vec<String> {
// 使用双换行符或多个换行符分割段落
let paragraph_regex = Regex::new(r"\n\s*\n").unwrap();
paragraph_regex.split(content)
.map(|p| p.trim().to_string())
.filter(|p| !p.is_empty())
.collect()
}
/// 按句子分割文本
fn split_into_sentences(&self, text: &str) -> Vec<String> {
// 使用句号、问号、感叹号等标点符号分割句子
let sentence_regex = Regex::new(r"[.!?。!?]+").unwrap();
let mut sentences = Vec::new();
let mut last_end = 0;
for mat in sentence_regex.find_iter(text) {
let sentence = text[last_end..mat.end()].trim();
if !sentence.is_empty() {
sentences.push(sentence.to_string());
}
last_end = mat.end();
}
// 处理最后一个句子(如果没有以标点结尾)
if last_end < text.len() {
let sentence = text[last_end..].trim();
if !sentence.is_empty() {
sentences.push(sentence.to_string());
}
}
// 如果没有找到句子分隔符,将整个文本作为一个句子
if sentences.is_empty() {
sentences.push(text.trim().to_string());
}
sentences
}
/// 创建语义块
fn create_semantic_chunk(
&self,
document_id: &str,
content: &str,
file_name: &str,
chunk_index: usize,
paragraph_index: usize,
sentences: &[String],
) -> DocumentChunk {
let mut metadata = HashMap::new();
metadata.insert("file_name".to_string(), file_name.to_string());
metadata.insert("chunk_index".to_string(), chunk_index.to_string());
metadata.insert("paragraph_index".to_string(), paragraph_index.to_string());
metadata.insert("sentence_count".to_string(), sentences.len().to_string());
metadata.insert("chunking_strategy".to_string(), "semantic".to_string());
DocumentChunk {
id: Uuid::new_v4().to_string(),
document_id: document_id.to_string(),
chunk_index,
text: content.to_string(),
metadata,
}
}
/// 为文本块生成向量嵌入
async fn generate_embeddings_for_chunks(&self, chunks: Vec<DocumentChunk>) -> Result<Vec<DocumentChunkWithEmbedding>> {
self.generate_embeddings_for_chunks_with_progress(chunks, None, "", "").await
}
/// 为文本块生成向量嵌入并发送进度更新
async fn generate_embeddings_for_chunks_with_progress(
&self,
chunks: Vec<DocumentChunk>,
window: Option<&Window>,
document_id: &str,
file_name: &str
) -> Result<Vec<DocumentChunkWithEmbedding>> {
println!("🧠 开始为 {} 个文本块生成向量嵌入", chunks.len());
let mut chunks_with_embeddings = Vec::new();
let total_chunks = chunks.len();
// 如果提供了window,发送初始状态并显示总块数
if let Some(w) = window {
self.emit_document_status_with_chunks(w, document_id, file_name, DocumentProcessingStage::Embedding, 0.0, 0, total_chunks).await;
}
for (index, chunk) in chunks.into_iter().enumerate() {
if index % 10 == 0 || index == total_chunks - 1 {
println!("📊 向量生成进度: {}/{} ({:.1}%)", index + 1, total_chunks, (index + 1) as f32 / total_chunks as f32 * 100.0);
}
println!("🔤 正在为文本块 {} 生成向量 (长度: {} 字符)", index + 1, chunk.text.len());
// 获取嵌入模型配置
let model_assignments = self.llm_manager.get_model_assignments().await
.map_err(|e| AppError::configuration(format!("获取模型分配失败: {}", e)))?;
let embedding_model_id = model_assignments.embedding_model_config_id
.ok_or_else(|| AppError::configuration("未配置嵌入模型"))?;
// 调用LLM管理器生成嵌入
let embeddings = self.llm_manager.call_embedding_api(vec![chunk.text.clone()], &embedding_model_id).await
.map_err(|e| AppError::llm(format!("生成嵌入向量失败: {}", e)))?;
let embedding = embeddings.into_iter().next()
.ok_or_else(|| AppError::llm("嵌入向量生成失败"))?;
if index % 10 == 0 {
println!("✅ 文本块 {} 向量生成完成 (维度: {})", index + 1, embedding.len());
}
chunks_with_embeddings.push(DocumentChunkWithEmbedding {
chunk,
embedding,
});
// 发送进度更新
if let Some(w) = window {
let progress = 0.5 + (index + 1) as f32 / total_chunks as f32 * 0.3; // 从50%到80%
self.emit_document_status_with_chunks(w, document_id, file_name, DocumentProcessingStage::Embedding, progress, index + 1, total_chunks).await;
}
}
println!("🎉 所有向量嵌入生成完成: {} 个向量", chunks_with_embeddings.len());
Ok(chunks_with_embeddings)
}
/// 获取默认RAG查询选项
pub fn get_default_rag_query_options(&self) -> RagQueryOptions {
match self.database.get_rag_configuration() {
Ok(Some(config)) => {
RagQueryOptions {
top_k: config.default_top_k as usize,
enable_reranking: Some(config.default_rerank_enabled),
}
}
_ => {
// 使用默认值
RagQueryOptions {
top_k: 5,
enable_reranking: Some(false),
}
}
}
}
/// 查询知识库
pub async fn query_knowledge_base(&self, user_query: &str, options: RagQueryOptions) -> Result<RagQueryResponse> {
let start_time = std::time::Instant::now();
println!("🔍 开始RAG查询: '{}' (top_k: {})", user_query, options.top_k);
// 1. 生成查询向量
let query_vector_start = std::time::Instant::now();
let model_assignments = self.llm_manager.get_model_assignments().await
.map_err(|e| AppError::configuration(format!("获取模型分配失败: {}", e)))?;
let embedding_model_id = model_assignments.embedding_model_config_id
.ok_or_else(|| AppError::configuration("未配置嵌入模型"))?;
let query_embeddings = self.llm_manager.call_embedding_api(vec![user_query.to_string()], &embedding_model_id).await
.map_err(|e| AppError::llm(format!("生成查询向量失败: {}", e)))?;
let query_embedding = query_embeddings.into_iter().next()
.ok_or_else(|| AppError::llm("未获取到查询向量"))?;
let query_vector_time = query_vector_start.elapsed();
// 2. 向量搜索
let search_start = std::time::Instant::now();
let mut retrieved_chunks = self.vector_store.search_similar_chunks(query_embedding, options.top_k).await?;
let search_time = search_start.elapsed();
// 3. 可选的重排序
let reranking_time = if options.enable_reranking.unwrap_or(false) {
let rerank_start = std::time::Instant::now();
retrieved_chunks = self.rerank_chunks(user_query, retrieved_chunks).await?;
Some(rerank_start.elapsed())
} else {
None
};
let total_time = start_time.elapsed();
println!("✅ RAG查询完成: {} 个结果 (总耗时: {:?})", retrieved_chunks.len(), total_time);
Ok(RagQueryResponse {
retrieved_chunks,
query_vector_time_ms: query_vector_time.as_millis() as u64,
search_time_ms: search_time.as_millis() as u64,
reranking_time_ms: reranking_time.map(|t| t.as_millis() as u64),
total_time_ms: total_time.as_millis() as u64,
})
}
/// 在指定分库中查询知识库
pub async fn query_knowledge_base_in_libraries(&self, user_query: &str, options: RagQueryOptions, sub_library_ids: Option<Vec<String>>) -> Result<RagQueryResponse> {
let start_time = std::time::Instant::now();
let library_filter_msg = if let Some(ref lib_ids) = sub_library_ids {
format!(" (分库: {:?})", lib_ids)
} else {
" (所有分库)".to_string()
};
println!("🔍 开始RAG查询: '{}' (top_k: {}){}", user_query, options.top_k, library_filter_msg);
// 1. 生成查询向量
let query_vector_start = std::time::Instant::now();
let model_assignments = self.llm_manager.get_model_assignments().await
.map_err(|e| AppError::configuration(format!("获取模型分配失败: {}", e)))?;
let embedding_model_id = model_assignments.embedding_model_config_id
.ok_or_else(|| AppError::configuration("未配置嵌入模型"))?;
let query_embeddings = self.llm_manager.call_embedding_api(vec![user_query.to_string()], &embedding_model_id).await
.map_err(|e| AppError::llm(format!("生成查询向量失败: {}", e)))?;
if query_embeddings.is_empty() {
return Err(AppError::llm("查询向量生成失败"));
}
let query_vector = query_embeddings.into_iter().next().unwrap();
let query_vector_time = query_vector_start.elapsed();
// 2. 在指定分库中检索相似文档块
let search_start = std::time::Instant::now();
let mut retrieved_chunks = self.vector_store.search_similar_chunks_in_libraries(query_vector, options.top_k, sub_library_ids).await?;
let search_time = search_start.elapsed();
// 3. 可选的重排序
let reranking_time = if options.enable_reranking.unwrap_or(false) && !retrieved_chunks.is_empty() {
let rerank_start = std::time::Instant::now();
retrieved_chunks = self.rerank_chunks(user_query, retrieved_chunks).await?;
Some(rerank_start.elapsed())
} else {
None
};
let total_time = start_time.elapsed();
println!("✅ RAG查询完成: 返回 {} 个结果 (总耗时: {}ms){}",
retrieved_chunks.len(), total_time.as_millis(), library_filter_msg);
Ok(RagQueryResponse {
retrieved_chunks,
query_vector_time_ms: query_vector_time.as_millis() as u64,
search_time_ms: search_time.as_millis() as u64,
reranking_time_ms: reranking_time.map(|t| t.as_millis() as u64),
total_time_ms: total_time.as_millis() as u64,
})
}
/// 重排序检索结果
async fn rerank_chunks(&self, query: &str, chunks: Vec<RetrievedChunk>) -> Result<Vec<RetrievedChunk>> {
println!("🔄 开始重排序 {} 个检索结果", chunks.len());
let model_assignments = self.llm_manager.get_model_assignments().await
.map_err(|e| AppError::configuration(format!("获取模型分配失败: {}", e)))?;
if let Some(reranker_model_id) = model_assignments.reranker_model_config_id {
// 调用重排序模型
let reranked_chunks = self.llm_manager.call_reranker_api(query.to_string(), chunks, &reranker_model_id).await
.map_err(|e| AppError::llm(format!("重排序失败: {}", e)))?;
println!("✅ 重排序完成");
Ok(reranked_chunks)
} else {
println!("⚠️ 未配置重排序模型,跳过重排序");
Ok(chunks)
}
}
/// 获取知识库状态
pub async fn get_knowledge_base_status(&self) -> Result<KnowledgeBaseStatusPayload> {
let stats = self.vector_store.get_stats().await?;
// 获取当前嵌入模型名称
let embedding_model_name = match self.llm_manager.get_model_assignments().await {
Ok(assignments) => {
if let Some(model_id) = assignments.embedding_model_config_id {
match self.llm_manager.get_api_configs().await {
Ok(configs) => {
configs.iter()
.find(|config| config.id == model_id)
.map(|config| config.name.clone())
}
Err(_) => None
}
} else {
None
}
}
Err(_) => None
};
Ok(KnowledgeBaseStatusPayload {
total_documents: stats.total_documents,
total_chunks: stats.total_chunks,
embedding_model_name,
vector_store_type: "SQLite".to_string(),
})
}
/// 删除文档
pub async fn delete_document_from_knowledge_base(&self, document_id: &str) -> Result<()> {
println!("🗑️ 删除文档: {}", document_id);
self.vector_store.delete_chunks_by_document_id(document_id).await
}
/// 清空知识库
pub async fn clear_knowledge_base(&self) -> Result<()> {
println!("🧹 清空知识库");
self.vector_store.clear_all().await
}
/// 获取所有文档列表
pub async fn get_all_documents(&self) -> Result<Vec<Value>> {
self.vector_store.get_all_documents()
}
// 辅助方法:发送处理状态更新
async fn emit_processing_status(&self, window: &Window, id: &str, status: &str, progress: f32, message: &str) {
let payload = serde_json::json!({
"id": id,
"status": status,
"progress": progress,
"message": message,
"timestamp": chrono::Utc::now().to_rfc3339()
});
if let Err(e) = window.emit("rag_processing_status", payload) {
println!("⚠️ 发送处理状态失败: {}", e);
}
}
// 辅助方法:发送文档处理状态
async fn emit_document_status(&self, window: &Window, document_id: &str, file_name: &str, stage: DocumentProcessingStage, progress: f32) {
let status = DocumentProcessingStatus {
document_id: document_id.to_string(),
file_name: file_name.to_string(),
status: stage,
progress,
error_message: None,
chunks_processed: 0,
total_chunks: 0,
};
if let Err(e) = window.emit("rag_document_status", &status) {
println!("⚠️ 发送文档状态失败: {}", e);
}
}
// 辅助方法:发送带详细信息的文档处理状态
async fn emit_document_status_with_chunks(&self, window: &Window, document_id: &str, file_name: &str, stage: DocumentProcessingStage, progress: f32, chunks_processed: usize, total_chunks: usize) {
let status = DocumentProcessingStatus {
document_id: document_id.to_string(),
file_name: file_name.to_string(),
status: stage,
progress,
error_message: None,
chunks_processed,
total_chunks,
};
if let Err(e) = window.emit("rag_document_status", &status) {
println!("⚠️ 发送文档状态失败: {}", e);
}
}
/// 提取PDF文件文本内容
async fn extract_pdf_text(&self, file_path: &str) -> Result<String> {
use pdf_extract::extract_text;
println!("📕 开始提取PDF文本: {}", file_path);
// 再次检查文件是否存在
let path = std::path::Path::new(file_path);
if !path.exists() {
return Err(AppError::file_system(format!("PDF文件不存在: {}", file_path)));
}
let text = extract_text(file_path)
.map_err(|e| AppError::validation(format!("PDF文本提取失败: {} (文件路径: {})", e, file_path)))?;
if text.trim().is_empty() {
return Err(AppError::validation(format!("PDF文件没有可提取的文本内容 (文件路径: {})", file_path)));
}
println!("✅ PDF文本提取完成,长度: {} 字符", text.len());
Ok(text)
}
/// 提取DOCX文件文本内容
async fn extract_docx_text(&self, file_path: &str) -> Result<String> {
use docx_rs::*;
println!("📘 开始提取DOCX文本: {}", file_path);
// 再次检查文件是否存在
let path = std::path::Path::new(file_path);
if !path.exists() {
return Err(AppError::file_system(format!("DOCX文件不存在: {}", file_path)));
}
let bytes = std::fs::read(file_path)
.map_err(|e| AppError::file_system(format!("读取DOCX文件失败: {} (文件路径: {})", e, file_path)))?;
let docx = read_docx(&bytes)
.map_err(|e| AppError::validation(format!("DOCX文件解析失败: {} (文件路径: {})", e, file_path)))?;
// 提取文档中的所有文本
let mut text_content = String::new();
// 遍历文档的所有段落
for child in docx.document.children {
match child {
docx_rs::DocumentChild::Paragraph(paragraph) => {
for run in paragraph.children {
match run {
docx_rs::ParagraphChild::Run(run) => {
for run_child in run.children {
if let docx_rs::RunChild::Text(text) = run_child {
text_content.push_str(&text.text);
}
}
}
_ => {}
}
}
text_content.push('\n'); // 段落结束添加换行
}
_ => {}
}
}
if text_content.trim().is_empty() {
return Err(AppError::validation(format!("DOCX文件没有可提取的文本内容 (文件路径: {})", file_path)));
}
println!("✅ DOCX文本提取完成,长度: {} 字符", text_content.len());
Ok(text_content)
}
/// 从内存中的PDF字节数据提取文本
async fn extract_pdf_text_from_memory(&self, pdf_bytes: &[u8]) -> Result<String> {
println!("📄 开始解析PDF文件 (大小: {} 字节)", pdf_bytes.len());
// 使用文档解析器处理PDF
let parser = crate::document_parser::DocumentParser::new();
println!("🔧 初始化PDF解析器");
match parser.extract_text_from_bytes("document.pdf", pdf_bytes.to_vec()) {
Ok(text) => {
println!("✅ PDF解析成功,提取文本长度: {} 字符", text.len());
if text.trim().is_empty() {
println!("⚠️ PDF文件解析结果为空");
Err(AppError::validation("PDF文件内容为空或无法解析"))
} else {
Ok(text)
}
}
Err(e) => {
println!("❌ PDF解析失败: {}", e);
Err(AppError::file_system(format!("PDF解析失败: {}", e)))
}
}
}
/// 从内存中的DOCX字节数据提取文本
async fn extract_docx_text_from_memory(&self, docx_bytes: &[u8]) -> Result<String> {
println!("📄 开始解析DOCX文件 (大小: {} 字节)", docx_bytes.len());
// 使用文档解析器处理DOCX
let parser = crate::document_parser::DocumentParser::new();
println!("🔧 初始化DOCX解析器");
match parser.extract_text_from_bytes("document.docx", docx_bytes.to_vec()) {
Ok(text) => {
println!("✅ DOCX解析成功,提取文本长度: {} 字符", text.len());
if text.trim().is_empty() {
println!("⚠️ DOCX文件解析结果为空");
Err(AppError::validation("DOCX文件内容为空或无法解析"))
} else {
Ok(text)
}
}
Err(e) => {
println!("❌ DOCX解析失败: {}", e);
Err(AppError::file_system(format!("DOCX解析失败: {}", e)))
}
}
}
}
| 55,374 | rag_manager | rs | en | rust | code | {"qsc_code_num_words": 5378, "qsc_code_num_chars": 55374.0, "qsc_code_mean_word_length": 5.11193752, "qsc_code_frac_words_unique": 0.09985125, "qsc_code_frac_chars_top_2grams": 0.03026335, "qsc_code_frac_chars_top_3grams": 0.01018478, "qsc_code_frac_chars_top_4grams": 0.01702313, "qsc_code_frac_chars_dupe_5grams": 0.74239779, "qsc_code_frac_chars_dupe_6grams": 0.71264368, "qsc_code_frac_chars_dupe_7grams": 0.68321694, "qsc_code_frac_chars_dupe_8grams": 0.66117416, "qsc_code_frac_chars_dupe_9grams": 0.62614579, "qsc_code_frac_chars_dupe_10grams": 0.59450022, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00695438, "qsc_code_frac_chars_whitespace": 0.3559974, "qsc_code_size_file_byte": 55374.0, "qsc_code_num_lines": 1389.0, "qsc_code_num_chars_line_max": 219.0, "qsc_code_num_chars_line_mean": 39.86609071, "qsc_code_frac_chars_alphabet": 0.7611957, "qsc_code_frac_chars_comments": 0.03823094, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.54033042, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.05467928, "qsc_code_frac_chars_long_word_length": 0.00039432, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 1, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0} |
0015/map_tiles | README.md | # Map Tiles Component for LVGL 9.x
A comprehensive map tiles component for ESP-IDF projects using LVGL 9.x. This component provides functionality to load and display map tiles with GPS coordinate conversion, designed for embedded applications requiring offline map display capabilities.
## Features
- **LVGL 9.x Compatible**: Fully compatible with LVGL 9.x image handling
- **GPS Coordinate Conversion**: Convert GPS coordinates to tile coordinates and vice versa
- **Dynamic Tile Loading**: Load map tiles on demand from file system
- **Configurable Grid Size**: Support for different grid sizes (3x3, 5x5, 7x7, etc.)
- **Multiple Tile Types**: Support for up to 8 different tile types (street, satellite, terrain, hybrid, etc.)
- **Memory Efficient**: Configurable memory allocation (SPIRAM or regular RAM)
- **Multiple Zoom Levels**: Support for different map zoom levels
- **Error Handling**: Comprehensive error handling and logging
- **C API**: Clean C API for easy integration
## Requirements
- ESP-IDF 5.0 or later
- LVGL 9.3
- File system support (FAT/SPIFFS/LittleFS)
- Map tiles in binary format (RGB565, 256x256 pixels)
## Installation
### Using ESP-IDF Component Manager
You can easily add this component to your project using the idf.py command or by manually updating your idf_component.yml file.
#### Option 1: Using the idf.py add-dependency command (Recommended)
From your project's root directory, simply run the following command in your terminal:
```bash
idf.py add-dependency "0015/map_tiles^1.2.0"
```
This command will automatically add the component to your idf_component.yml file and download the required files the next time you build your project.
#### Option 2: Manual idf_component.yml update
Add to your project's `main/idf_component.yml`:
```yaml
dependencies:
map_tiles:
git: "https://github.com/0015/map_tiles.git"
version: "^1.2.0"
```
### Manual Installation
1. Copy the `map_tiles` folder to your project's `components` directory
2. The component will be automatically included in your build
## Usage
### Basic Setup
```c
#include "map_tiles.h"
// Configure the map tiles with multiple tile types and custom grid size
const char* tile_folders[] = {"street_map", "satellite", "terrain", "hybrid"};
map_tiles_config_t config = {
.base_path = "/sdcard", // Base path to tile storage
.tile_folders = {tile_folders[0], tile_folders[1], tile_folders[2], tile_folders[3]},
.tile_type_count = 4, // Number of tile types
.default_zoom = 10, // Default zoom level
.use_spiram = true, // Use SPIRAM if available
.default_tile_type = 0, // Start with street map (index 0)
.grid_cols = 5, // Grid width (tiles)
.grid_rows = 5 // Grid height (tiles)
};
// Initialize map tiles
map_tiles_handle_t map_handle = map_tiles_init(&config);
if (!map_handle) {
ESP_LOGE(TAG, "Failed to initialize map tiles");
return;
}
```
### Loading Tiles
```c
// Set center position from GPS coordinates
map_tiles_set_center_from_gps(map_handle, 37.7749, -122.4194); // San Francisco
// Get grid dimensions
int grid_cols, grid_rows;
map_tiles_get_grid_size(map_handle, &grid_cols, &grid_rows);
int tile_count = map_tiles_get_tile_count(map_handle);
// Load tiles for the configured grid size
for (int row = 0; row < grid_rows; row++) {
for (int col = 0; col < grid_cols; col++) {
int index = row * grid_cols + col;
int tile_x, tile_y;
map_tiles_get_position(map_handle, &tile_x, &tile_y);
bool loaded = map_tiles_load_tile(map_handle, index,
tile_x + col, tile_y + row);
if (!loaded) {
ESP_LOGW(TAG, "Failed to load tile %d", index);
}
}
}
```
### Displaying Tiles with LVGL
```c
// Get grid dimensions and tile count
int grid_cols, grid_rows;
map_tiles_get_grid_size(map_handle, &grid_cols, &grid_rows);
int tile_count = map_tiles_get_tile_count(map_handle);
// Create image widgets for each tile
lv_obj_t** tile_images = malloc(tile_count * sizeof(lv_obj_t*));
for (int i = 0; i < tile_count; i++) {
tile_images[i] = lv_image_create(parent_container);
// Get the tile image descriptor
lv_image_dsc_t* img_dsc = map_tiles_get_image(map_handle, i);
if (img_dsc) {
lv_image_set_src(tile_images[i], img_dsc);
// Position the tile in the grid
int row = i / grid_cols;
int col = i % grid_cols;
lv_obj_set_pos(tile_images[i],
col * MAP_TILES_TILE_SIZE,
row * MAP_TILES_TILE_SIZE);
}
}
```
### Switching Tile Types
```c
// Switch to different tile types
map_tiles_set_tile_type(map_handle, 0); // Street map
map_tiles_set_tile_type(map_handle, 1); // Satellite
map_tiles_set_tile_type(map_handle, 2); // Terrain
map_tiles_set_tile_type(map_handle, 3); // Hybrid
// Get current tile type
int current_type = map_tiles_get_tile_type(map_handle);
// Get available tile types
int type_count = map_tiles_get_tile_type_count(map_handle);
for (int i = 0; i < type_count; i++) {
const char* folder = map_tiles_get_tile_type_folder(map_handle, i);
printf("Tile type %d: %s\n", i, folder);
}
```
### GPS Coordinate Conversion
```c
// Convert GPS to tile coordinates
double tile_x, tile_y;
map_tiles_gps_to_tile_xy(map_handle, 37.7749, -122.4194, &tile_x, &tile_y);
// Check if GPS position is within current tile grid
bool within_tiles = map_tiles_is_gps_within_tiles(map_handle, 37.7749, -122.4194);
// Get marker offset for precise positioning
int offset_x, offset_y;
map_tiles_get_marker_offset(map_handle, &offset_x, &offset_y);
```
### Memory Management
```c
// Clean up when done
map_tiles_cleanup(map_handle);
```
## Tile File Format
The component expects map tiles in a specific binary format:
- **File Structure**: `{base_path}/{map_tile}/{zoom}/{tile_x}/{tile_y}.bin`
- **Format**: 12-byte header + raw RGB565 pixel data
- **Size**: 256x256 pixels
- **Color Format**: RGB565 (16-bit per pixel)
### Example Tile Structure
```
/sdcard/
├── street_map/ // Tile type 0
│ ├── 10/
│ │ ├── 164/
│ │ │ ├── 395.bin
│ │ │ ├── 396.bin
│ │ │ └── ...
│ │ └── ...
│ └── ...
├── satellite/ // Tile type 1
│ ├── 10/
│ │ ├── 164/
│ │ │ ├── 395.bin
│ │ │ └── ...
│ │ └── ...
│ └── ...
├── terrain/ // Tile type 2
│ └── ...
└── hybrid/ // Tile type 3
└── ...
```
## Configuration Options
| Parameter | Type | Description | Default |
|-----------|------|-------------|---------|
| `base_path` | `const char*` | Base directory for tile storage | Required |
| `tile_folders` | `const char*[]` | Array of folder names for different tile types | Required |
| `tile_type_count` | `int` | Number of tile types (max 8) | Required |
| `default_zoom` | `int` | Initial zoom level | Required |
| `use_spiram` | `bool` | Use SPIRAM for tile buffers | `false` |
| `default_tile_type` | `int` | Initial tile type index | Required |
| `grid_cols` | `int` | Number of tile columns (max 10) | 5 |
| `grid_rows` | `int` | Number of tile rows (max 10) | 5 |
## API Reference
### Initialization
- `map_tiles_init()` - Initialize map tiles system
- `map_tiles_cleanup()` - Clean up resources
### Tile Management
- `map_tiles_load_tile()` - Load a specific tile
- `map_tiles_get_image()` - Get LVGL image descriptor
- `map_tiles_get_buffer()` - Get raw tile buffer
### Grid Management
- `map_tiles_get_grid_size()` - Get current grid dimensions
- `map_tiles_get_tile_count()` - Get total number of tiles in grid
### Coordinate Conversion
- `map_tiles_gps_to_tile_xy()` - Convert GPS to tile coordinates
- `map_tiles_set_center_from_gps()` - Set center from GPS
- `map_tiles_is_gps_within_tiles()` - Check if GPS is within current tiles
### Position Management
- `map_tiles_get_position()` - Get current tile position
- `map_tiles_set_position()` - Set tile position
- `map_tiles_get_marker_offset()` - Get marker offset
- `map_tiles_set_marker_offset()` - Set marker offset
### Tile Type Management
- `map_tiles_set_tile_type()` - Set active tile type
- `map_tiles_get_tile_type()` - Get current tile type
- `map_tiles_get_tile_type_count()` - Get number of available types
- `map_tiles_get_tile_type_folder()` - Get folder name for a type
### Zoom Control
- `map_tiles_set_zoom()` - Set zoom level
- `map_tiles_get_zoom()` - Get current zoom level
### Error Handling
- `map_tiles_set_loading_error()` - Set error state
- `map_tiles_has_loading_error()` - Check error state
## Performance Considerations
- **Memory Usage**: Each tile uses ~128KB (256×256×2 bytes)
- **Grid Size**: Larger grids use more memory (3x3=9 tiles, 5x5=25 tiles, 7x7=49 tiles)
- **SPIRAM**: Recommended for ESP32-S3 with PSRAM for better performance
- **File System**: Ensure adequate file system performance for tile loading
- **Tile Caching**: Component maintains tile buffers until cleanup
## Example Projects
See the `examples` directory for complete implementation examples:
- Basic map display
- GPS tracking with map updates
- Interactive map with touch controls
## License
This component is released under the MIT License. See LICENSE file for details.
## Contributing
Contributions are welcome! Please feel free to submit pull requests or open issues for bugs and feature requests.
## Support
For questions and support, please open an issue on the GitHub repository.
| 9,617 | README | md | en | markdown | text | {"qsc_doc_frac_chars_curly_bracket": 0.00311948, "qsc_doc_frac_words_redpajama_stop": 0.10195228, "qsc_doc_num_sentences": 57.0, "qsc_doc_num_words": 1426, "qsc_doc_num_chars": 9617.0, "qsc_doc_num_lines": 291.0, "qsc_doc_mean_word_length": 4.45301543, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.02749141, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.23702665, "qsc_doc_entropy_unigram": 4.97324101, "qsc_doc_frac_words_all_caps": 0.02819957, "qsc_doc_frac_lines_dupe_lines": 0.18666667, "qsc_doc_frac_chars_dupe_lines": 0.05981391, "qsc_doc_frac_chars_top_2grams": 0.07685039, "qsc_doc_frac_chars_top_3grams": 0.03464567, "qsc_doc_frac_chars_top_4grams": 0.02125984, "qsc_doc_frac_chars_dupe_5grams": 0.16566929, "qsc_doc_frac_chars_dupe_6grams": 0.12913386, "qsc_doc_frac_chars_dupe_7grams": 0.08472441, "qsc_doc_frac_chars_dupe_8grams": 0.04755906, "qsc_doc_frac_chars_dupe_9grams": 0.04755906, "qsc_doc_frac_chars_dupe_10grams": 0.04755906, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 25.06504065, "qsc_doc_frac_chars_hyperlink_html_tag": 0.0, "qsc_doc_frac_chars_alphabet": 0.78996499, "qsc_doc_frac_chars_digital": 0.02204071, "qsc_doc_frac_chars_whitespace": 0.19798274, "qsc_doc_frac_chars_hex_words": 0.0} | 1 | {"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0} |
0015/esp_rlottie | rlottie/src/lottie/rapidjson/schema.h | // Tencent is pleased to support the open source community by making RapidJSON available->
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip-> All rights reserved->
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License-> You may obtain a copy of the License at
//
// http://opensource->org/licenses/MIT
//
// 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 RAPIDJSON_SCHEMA_H_
#define RAPIDJSON_SCHEMA_H_
#include "document.h"
#include "pointer.h"
#include "stringbuffer.h"
#include <cmath> // abs, floor
#if !defined(RAPIDJSON_SCHEMA_USE_INTERNALREGEX)
#define RAPIDJSON_SCHEMA_USE_INTERNALREGEX 1
#else
#define RAPIDJSON_SCHEMA_USE_INTERNALREGEX 0
#endif
#if !RAPIDJSON_SCHEMA_USE_INTERNALREGEX && defined(RAPIDJSON_SCHEMA_USE_STDREGEX) && (__cplusplus >=201103L || (defined(_MSC_VER) && _MSC_VER >= 1800))
#define RAPIDJSON_SCHEMA_USE_STDREGEX 1
#else
#define RAPIDJSON_SCHEMA_USE_STDREGEX 0
#endif
#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX
#include "internal/regex.h"
#elif RAPIDJSON_SCHEMA_USE_STDREGEX
#include <regex>
#endif
#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX || RAPIDJSON_SCHEMA_USE_STDREGEX
#define RAPIDJSON_SCHEMA_HAS_REGEX 1
#else
#define RAPIDJSON_SCHEMA_HAS_REGEX 0
#endif
#ifndef RAPIDJSON_SCHEMA_VERBOSE
#define RAPIDJSON_SCHEMA_VERBOSE 0
#endif
#if RAPIDJSON_SCHEMA_VERBOSE
#include "stringbuffer.h"
#endif
RAPIDJSON_DIAG_PUSH
#if defined(__GNUC__)
RAPIDJSON_DIAG_OFF(effc++)
#endif
#ifdef __clang__
RAPIDJSON_DIAG_OFF(weak-vtables)
RAPIDJSON_DIAG_OFF(exit-time-destructors)
RAPIDJSON_DIAG_OFF(c++98-compat-pedantic)
RAPIDJSON_DIAG_OFF(variadic-macros)
#elif defined(_MSC_VER)
RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated
#endif
RAPIDJSON_NAMESPACE_BEGIN
///////////////////////////////////////////////////////////////////////////////
// Verbose Utilities
#if RAPIDJSON_SCHEMA_VERBOSE
namespace internal {
inline void PrintInvalidKeyword(const char* keyword) {
printf("Fail keyword: %s\n", keyword);
}
inline void PrintInvalidKeyword(const wchar_t* keyword) {
wprintf(L"Fail keyword: %ls\n", keyword);
}
inline void PrintInvalidDocument(const char* document) {
printf("Fail document: %s\n\n", document);
}
inline void PrintInvalidDocument(const wchar_t* document) {
wprintf(L"Fail document: %ls\n\n", document);
}
inline void PrintValidatorPointers(unsigned depth, const char* s, const char* d) {
printf("S: %*s%s\nD: %*s%s\n\n", depth * 4, " ", s, depth * 4, " ", d);
}
inline void PrintValidatorPointers(unsigned depth, const wchar_t* s, const wchar_t* d) {
wprintf(L"S: %*ls%ls\nD: %*ls%ls\n\n", depth * 4, L" ", s, depth * 4, L" ", d);
}
} // namespace internal
#endif // RAPIDJSON_SCHEMA_VERBOSE
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_INVALID_KEYWORD_RETURN
#if RAPIDJSON_SCHEMA_VERBOSE
#define RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword) internal::PrintInvalidKeyword(keyword)
#else
#define RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword)
#endif
#define RAPIDJSON_INVALID_KEYWORD_RETURN(keyword)\
RAPIDJSON_MULTILINEMACRO_BEGIN\
context.invalidKeyword = keyword.GetString();\
RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword.GetString());\
return false;\
RAPIDJSON_MULTILINEMACRO_END
///////////////////////////////////////////////////////////////////////////////
// Forward declarations
template <typename ValueType, typename Allocator>
class GenericSchemaDocument;
namespace internal {
template <typename SchemaDocumentType>
class Schema;
///////////////////////////////////////////////////////////////////////////////
// ISchemaValidator
class ISchemaValidator {
public:
virtual ~ISchemaValidator() {}
virtual bool IsValid() const = 0;
};
///////////////////////////////////////////////////////////////////////////////
// ISchemaStateFactory
template <typename SchemaType>
class ISchemaStateFactory {
public:
virtual ~ISchemaStateFactory() {}
virtual ISchemaValidator* CreateSchemaValidator(const SchemaType&) = 0;
virtual void DestroySchemaValidator(ISchemaValidator* validator) = 0;
virtual void* CreateHasher() = 0;
virtual uint64_t GetHashCode(void* hasher) = 0;
virtual void DestroryHasher(void* hasher) = 0;
virtual void* MallocState(size_t size) = 0;
virtual void FreeState(void* p) = 0;
};
///////////////////////////////////////////////////////////////////////////////
// IValidationErrorHandler
template <typename SchemaType>
class IValidationErrorHandler {
public:
typedef typename SchemaType::Ch Ch;
typedef typename SchemaType::SValue SValue;
virtual ~IValidationErrorHandler() {}
virtual void NotMultipleOf(int64_t actual, const SValue& expected) = 0;
virtual void NotMultipleOf(uint64_t actual, const SValue& expected) = 0;
virtual void NotMultipleOf(double actual, const SValue& expected) = 0;
virtual void AboveMaximum(int64_t actual, const SValue& expected, bool exclusive) = 0;
virtual void AboveMaximum(uint64_t actual, const SValue& expected, bool exclusive) = 0;
virtual void AboveMaximum(double actual, const SValue& expected, bool exclusive) = 0;
virtual void BelowMinimum(int64_t actual, const SValue& expected, bool exclusive) = 0;
virtual void BelowMinimum(uint64_t actual, const SValue& expected, bool exclusive) = 0;
virtual void BelowMinimum(double actual, const SValue& expected, bool exclusive) = 0;
virtual void TooLong(const Ch* str, SizeType length, SizeType expected) = 0;
virtual void TooShort(const Ch* str, SizeType length, SizeType expected) = 0;
virtual void DoesNotMatch(const Ch* str, SizeType length) = 0;
virtual void DisallowedItem(SizeType index) = 0;
virtual void TooFewItems(SizeType actualCount, SizeType expectedCount) = 0;
virtual void TooManyItems(SizeType actualCount, SizeType expectedCount) = 0;
virtual void DuplicateItems(SizeType index1, SizeType index2) = 0;
virtual void TooManyProperties(SizeType actualCount, SizeType expectedCount) = 0;
virtual void TooFewProperties(SizeType actualCount, SizeType expectedCount) = 0;
virtual void StartMissingProperties() = 0;
virtual void AddMissingProperty(const SValue& name) = 0;
virtual bool EndMissingProperties() = 0;
virtual void PropertyViolations(ISchemaValidator** subvalidators, SizeType count) = 0;
virtual void DisallowedProperty(const Ch* name, SizeType length) = 0;
virtual void StartDependencyErrors() = 0;
virtual void StartMissingDependentProperties() = 0;
virtual void AddMissingDependentProperty(const SValue& targetName) = 0;
virtual void EndMissingDependentProperties(const SValue& sourceName) = 0;
virtual void AddDependencySchemaError(const SValue& souceName, ISchemaValidator* subvalidator) = 0;
virtual bool EndDependencyErrors() = 0;
virtual void DisallowedValue() = 0;
virtual void StartDisallowedType() = 0;
virtual void AddExpectedType(const typename SchemaType::ValueType& expectedType) = 0;
virtual void EndDisallowedType(const typename SchemaType::ValueType& actualType) = 0;
virtual void NotAllOf(ISchemaValidator** subvalidators, SizeType count) = 0;
virtual void NoneOf(ISchemaValidator** subvalidators, SizeType count) = 0;
virtual void NotOneOf(ISchemaValidator** subvalidators, SizeType count) = 0;
virtual void Disallowed() = 0;
};
///////////////////////////////////////////////////////////////////////////////
// Hasher
// For comparison of compound value
template<typename Encoding, typename Allocator>
class Hasher {
public:
typedef typename Encoding::Ch Ch;
Hasher(Allocator* allocator = 0, size_t stackCapacity = kDefaultSize) : stack_(allocator, stackCapacity) {}
bool Null() { return WriteType(kNullType); }
bool Bool(bool b) { return WriteType(b ? kTrueType : kFalseType); }
bool Int(int i) { Number n; n.u.i = i; n.d = static_cast<double>(i); return WriteNumber(n); }
bool Uint(unsigned u) { Number n; n.u.u = u; n.d = static_cast<double>(u); return WriteNumber(n); }
bool Int64(int64_t i) { Number n; n.u.i = i; n.d = static_cast<double>(i); return WriteNumber(n); }
bool Uint64(uint64_t u) { Number n; n.u.u = u; n.d = static_cast<double>(u); return WriteNumber(n); }
bool Double(double d) {
Number n;
if (d < 0) n.u.i = static_cast<int64_t>(d);
else n.u.u = static_cast<uint64_t>(d);
n.d = d;
return WriteNumber(n);
}
bool RawNumber(const Ch* str, SizeType len, bool) {
WriteBuffer(kNumberType, str, len * sizeof(Ch));
return true;
}
bool String(const Ch* str, SizeType len, bool) {
WriteBuffer(kStringType, str, len * sizeof(Ch));
return true;
}
bool StartObject() { return true; }
bool Key(const Ch* str, SizeType len, bool copy) { return String(str, len, copy); }
bool EndObject(SizeType memberCount) {
uint64_t h = Hash(0, kObjectType);
uint64_t* kv = stack_.template Pop<uint64_t>(memberCount * 2);
for (SizeType i = 0; i < memberCount; i++)
h ^= Hash(kv[i * 2], kv[i * 2 + 1]); // Use xor to achieve member order insensitive
*stack_.template Push<uint64_t>() = h;
return true;
}
bool StartArray() { return true; }
bool EndArray(SizeType elementCount) {
uint64_t h = Hash(0, kArrayType);
uint64_t* e = stack_.template Pop<uint64_t>(elementCount);
for (SizeType i = 0; i < elementCount; i++)
h = Hash(h, e[i]); // Use hash to achieve element order sensitive
*stack_.template Push<uint64_t>() = h;
return true;
}
bool IsValid() const { return stack_.GetSize() == sizeof(uint64_t); }
uint64_t GetHashCode() const {
RAPIDJSON_ASSERT(IsValid());
return *stack_.template Top<uint64_t>();
}
private:
static const size_t kDefaultSize = 256;
struct Number {
union U {
uint64_t u;
int64_t i;
}u;
double d;
};
bool WriteType(Type type) { return WriteBuffer(type, 0, 0); }
bool WriteNumber(const Number& n) { return WriteBuffer(kNumberType, &n, sizeof(n)); }
bool WriteBuffer(Type type, const void* data, size_t len) {
// FNV-1a from http://isthe.com/chongo/tech/comp/fnv/
uint64_t h = Hash(RAPIDJSON_UINT64_C2(0x84222325, 0xcbf29ce4), type);
const unsigned char* d = static_cast<const unsigned char*>(data);
for (size_t i = 0; i < len; i++)
h = Hash(h, d[i]);
*stack_.template Push<uint64_t>() = h;
return true;
}
static uint64_t Hash(uint64_t h, uint64_t d) {
static const uint64_t kPrime = RAPIDJSON_UINT64_C2(0x00000100, 0x000001b3);
h ^= d;
h *= kPrime;
return h;
}
Stack<Allocator> stack_;
};
///////////////////////////////////////////////////////////////////////////////
// SchemaValidationContext
template <typename SchemaDocumentType>
struct SchemaValidationContext {
typedef Schema<SchemaDocumentType> SchemaType;
typedef ISchemaStateFactory<SchemaType> SchemaValidatorFactoryType;
typedef IValidationErrorHandler<SchemaType> ErrorHandlerType;
typedef typename SchemaType::ValueType ValueType;
typedef typename ValueType::Ch Ch;
enum PatternValidatorType {
kPatternValidatorOnly,
kPatternValidatorWithProperty,
kPatternValidatorWithAdditionalProperty
};
SchemaValidationContext(SchemaValidatorFactoryType& f, ErrorHandlerType& eh, const SchemaType* s) :
factory(f),
error_handler(eh),
schema(s),
valueSchema(),
invalidKeyword(),
hasher(),
arrayElementHashCodes(),
validators(),
validatorCount(),
patternPropertiesValidators(),
patternPropertiesValidatorCount(),
patternPropertiesSchemas(),
patternPropertiesSchemaCount(),
valuePatternValidatorType(kPatternValidatorOnly),
propertyExist(),
inArray(false),
valueUniqueness(false),
arrayUniqueness(false)
{
}
~SchemaValidationContext() {
if (hasher)
factory.DestroryHasher(hasher);
if (validators) {
for (SizeType i = 0; i < validatorCount; i++)
factory.DestroySchemaValidator(validators[i]);
factory.FreeState(validators);
}
if (patternPropertiesValidators) {
for (SizeType i = 0; i < patternPropertiesValidatorCount; i++)
factory.DestroySchemaValidator(patternPropertiesValidators[i]);
factory.FreeState(patternPropertiesValidators);
}
if (patternPropertiesSchemas)
factory.FreeState(patternPropertiesSchemas);
if (propertyExist)
factory.FreeState(propertyExist);
}
SchemaValidatorFactoryType& factory;
ErrorHandlerType& error_handler;
const SchemaType* schema;
const SchemaType* valueSchema;
const Ch* invalidKeyword;
void* hasher; // Only validator access
void* arrayElementHashCodes; // Only validator access this
ISchemaValidator** validators;
SizeType validatorCount;
ISchemaValidator** patternPropertiesValidators;
SizeType patternPropertiesValidatorCount;
const SchemaType** patternPropertiesSchemas;
SizeType patternPropertiesSchemaCount;
PatternValidatorType valuePatternValidatorType;
PatternValidatorType objectPatternValidatorType;
SizeType arrayElementIndex;
bool* propertyExist;
bool inArray;
bool valueUniqueness;
bool arrayUniqueness;
};
///////////////////////////////////////////////////////////////////////////////
// Schema
template <typename SchemaDocumentType>
class Schema {
public:
typedef typename SchemaDocumentType::ValueType ValueType;
typedef typename SchemaDocumentType::AllocatorType AllocatorType;
typedef typename SchemaDocumentType::PointerType PointerType;
typedef typename ValueType::EncodingType EncodingType;
typedef typename EncodingType::Ch Ch;
typedef SchemaValidationContext<SchemaDocumentType> Context;
typedef Schema<SchemaDocumentType> SchemaType;
typedef GenericValue<EncodingType, AllocatorType> SValue;
typedef IValidationErrorHandler<Schema> ErrorHandler;
friend class GenericSchemaDocument<ValueType, AllocatorType>;
Schema(SchemaDocumentType* schemaDocument, const PointerType& p, const ValueType& value, const ValueType& document, AllocatorType* allocator) :
allocator_(allocator),
uri_(schemaDocument->GetURI(), *allocator),
pointer_(p, allocator),
typeless_(schemaDocument->GetTypeless()),
enum_(),
enumCount_(),
not_(),
type_((1 << kTotalSchemaType) - 1), // typeless
validatorCount_(),
notValidatorIndex_(),
properties_(),
additionalPropertiesSchema_(),
patternProperties_(),
patternPropertyCount_(),
propertyCount_(),
minProperties_(),
maxProperties_(SizeType(~0)),
additionalProperties_(true),
hasDependencies_(),
hasRequired_(),
hasSchemaDependencies_(),
additionalItemsSchema_(),
itemsList_(),
itemsTuple_(),
itemsTupleCount_(),
minItems_(),
maxItems_(SizeType(~0)),
additionalItems_(true),
uniqueItems_(false),
pattern_(),
minLength_(0),
maxLength_(~SizeType(0)),
exclusiveMinimum_(false),
exclusiveMaximum_(false),
defaultValueLength_(0)
{
typedef typename ValueType::ConstValueIterator ConstValueIterator;
typedef typename ValueType::ConstMemberIterator ConstMemberIterator;
if (!value.IsObject())
return;
if (const ValueType* v = GetMember(value, GetTypeString())) {
type_ = 0;
if (v->IsString())
AddType(*v);
else if (v->IsArray())
for (ConstValueIterator itr = v->Begin(); itr != v->End(); ++itr)
AddType(*itr);
}
if (const ValueType* v = GetMember(value, GetEnumString()))
if (v->IsArray() && v->Size() > 0) {
enum_ = static_cast<uint64_t*>(allocator_->Malloc(sizeof(uint64_t) * v->Size()));
for (ConstValueIterator itr = v->Begin(); itr != v->End(); ++itr) {
typedef Hasher<EncodingType, MemoryPoolAllocator<> > EnumHasherType;
char buffer[256u + 24];
MemoryPoolAllocator<> hasherAllocator(buffer, sizeof(buffer));
EnumHasherType h(&hasherAllocator, 256);
itr->Accept(h);
enum_[enumCount_++] = h.GetHashCode();
}
}
if (schemaDocument) {
AssignIfExist(allOf_, *schemaDocument, p, value, GetAllOfString(), document);
AssignIfExist(anyOf_, *schemaDocument, p, value, GetAnyOfString(), document);
AssignIfExist(oneOf_, *schemaDocument, p, value, GetOneOfString(), document);
}
if (const ValueType* v = GetMember(value, GetNotString())) {
schemaDocument->CreateSchema(¬_, p.Append(GetNotString(), allocator_), *v, document);
notValidatorIndex_ = validatorCount_;
validatorCount_++;
}
// Object
const ValueType* properties = GetMember(value, GetPropertiesString());
const ValueType* required = GetMember(value, GetRequiredString());
const ValueType* dependencies = GetMember(value, GetDependenciesString());
{
// Gather properties from properties/required/dependencies
SValue allProperties(kArrayType);
if (properties && properties->IsObject())
for (ConstMemberIterator itr = properties->MemberBegin(); itr != properties->MemberEnd(); ++itr)
AddUniqueElement(allProperties, itr->name);
if (required && required->IsArray())
for (ConstValueIterator itr = required->Begin(); itr != required->End(); ++itr)
if (itr->IsString())
AddUniqueElement(allProperties, *itr);
if (dependencies && dependencies->IsObject())
for (ConstMemberIterator itr = dependencies->MemberBegin(); itr != dependencies->MemberEnd(); ++itr) {
AddUniqueElement(allProperties, itr->name);
if (itr->value.IsArray())
for (ConstValueIterator i = itr->value.Begin(); i != itr->value.End(); ++i)
if (i->IsString())
AddUniqueElement(allProperties, *i);
}
if (allProperties.Size() > 0) {
propertyCount_ = allProperties.Size();
properties_ = static_cast<Property*>(allocator_->Malloc(sizeof(Property) * propertyCount_));
for (SizeType i = 0; i < propertyCount_; i++) {
new (&properties_[i]) Property();
properties_[i].name = allProperties[i];
properties_[i].schema = typeless_;
}
}
}
if (properties && properties->IsObject()) {
PointerType q = p.Append(GetPropertiesString(), allocator_);
for (ConstMemberIterator itr = properties->MemberBegin(); itr != properties->MemberEnd(); ++itr) {
SizeType index;
if (FindPropertyIndex(itr->name, &index))
schemaDocument->CreateSchema(&properties_[index].schema, q.Append(itr->name, allocator_), itr->value, document);
}
}
if (const ValueType* v = GetMember(value, GetPatternPropertiesString())) {
PointerType q = p.Append(GetPatternPropertiesString(), allocator_);
patternProperties_ = static_cast<PatternProperty*>(allocator_->Malloc(sizeof(PatternProperty) * v->MemberCount()));
patternPropertyCount_ = 0;
for (ConstMemberIterator itr = v->MemberBegin(); itr != v->MemberEnd(); ++itr) {
new (&patternProperties_[patternPropertyCount_]) PatternProperty();
patternProperties_[patternPropertyCount_].pattern = CreatePattern(itr->name);
schemaDocument->CreateSchema(&patternProperties_[patternPropertyCount_].schema, q.Append(itr->name, allocator_), itr->value, document);
patternPropertyCount_++;
}
}
if (required && required->IsArray())
for (ConstValueIterator itr = required->Begin(); itr != required->End(); ++itr)
if (itr->IsString()) {
SizeType index;
if (FindPropertyIndex(*itr, &index)) {
properties_[index].required = true;
hasRequired_ = true;
}
}
if (dependencies && dependencies->IsObject()) {
PointerType q = p.Append(GetDependenciesString(), allocator_);
hasDependencies_ = true;
for (ConstMemberIterator itr = dependencies->MemberBegin(); itr != dependencies->MemberEnd(); ++itr) {
SizeType sourceIndex;
if (FindPropertyIndex(itr->name, &sourceIndex)) {
if (itr->value.IsArray()) {
properties_[sourceIndex].dependencies = static_cast<bool*>(allocator_->Malloc(sizeof(bool) * propertyCount_));
std::memset(properties_[sourceIndex].dependencies, 0, sizeof(bool)* propertyCount_);
for (ConstValueIterator targetItr = itr->value.Begin(); targetItr != itr->value.End(); ++targetItr) {
SizeType targetIndex;
if (FindPropertyIndex(*targetItr, &targetIndex))
properties_[sourceIndex].dependencies[targetIndex] = true;
}
}
else if (itr->value.IsObject()) {
hasSchemaDependencies_ = true;
schemaDocument->CreateSchema(&properties_[sourceIndex].dependenciesSchema, q.Append(itr->name, allocator_), itr->value, document);
properties_[sourceIndex].dependenciesValidatorIndex = validatorCount_;
validatorCount_++;
}
}
}
}
if (const ValueType* v = GetMember(value, GetAdditionalPropertiesString())) {
if (v->IsBool())
additionalProperties_ = v->GetBool();
else if (v->IsObject())
schemaDocument->CreateSchema(&additionalPropertiesSchema_, p.Append(GetAdditionalPropertiesString(), allocator_), *v, document);
}
AssignIfExist(minProperties_, value, GetMinPropertiesString());
AssignIfExist(maxProperties_, value, GetMaxPropertiesString());
// Array
if (const ValueType* v = GetMember(value, GetItemsString())) {
PointerType q = p.Append(GetItemsString(), allocator_);
if (v->IsObject()) // List validation
schemaDocument->CreateSchema(&itemsList_, q, *v, document);
else if (v->IsArray()) { // Tuple validation
itemsTuple_ = static_cast<const Schema**>(allocator_->Malloc(sizeof(const Schema*) * v->Size()));
SizeType index = 0;
for (ConstValueIterator itr = v->Begin(); itr != v->End(); ++itr, index++)
schemaDocument->CreateSchema(&itemsTuple_[itemsTupleCount_++], q.Append(index, allocator_), *itr, document);
}
}
AssignIfExist(minItems_, value, GetMinItemsString());
AssignIfExist(maxItems_, value, GetMaxItemsString());
if (const ValueType* v = GetMember(value, GetAdditionalItemsString())) {
if (v->IsBool())
additionalItems_ = v->GetBool();
else if (v->IsObject())
schemaDocument->CreateSchema(&additionalItemsSchema_, p.Append(GetAdditionalItemsString(), allocator_), *v, document);
}
AssignIfExist(uniqueItems_, value, GetUniqueItemsString());
// String
AssignIfExist(minLength_, value, GetMinLengthString());
AssignIfExist(maxLength_, value, GetMaxLengthString());
if (const ValueType* v = GetMember(value, GetPatternString()))
pattern_ = CreatePattern(*v);
// Number
if (const ValueType* v = GetMember(value, GetMinimumString()))
if (v->IsNumber())
minimum_.CopyFrom(*v, *allocator_);
if (const ValueType* v = GetMember(value, GetMaximumString()))
if (v->IsNumber())
maximum_.CopyFrom(*v, *allocator_);
AssignIfExist(exclusiveMinimum_, value, GetExclusiveMinimumString());
AssignIfExist(exclusiveMaximum_, value, GetExclusiveMaximumString());
if (const ValueType* v = GetMember(value, GetMultipleOfString()))
if (v->IsNumber() && v->GetDouble() > 0.0)
multipleOf_.CopyFrom(*v, *allocator_);
// Default
if (const ValueType* v = GetMember(value, GetDefaultValueString()))
if (v->IsString())
defaultValueLength_ = v->GetStringLength();
}
~Schema() {
AllocatorType::Free(enum_);
if (properties_) {
for (SizeType i = 0; i < propertyCount_; i++)
properties_[i].~Property();
AllocatorType::Free(properties_);
}
if (patternProperties_) {
for (SizeType i = 0; i < patternPropertyCount_; i++)
patternProperties_[i].~PatternProperty();
AllocatorType::Free(patternProperties_);
}
AllocatorType::Free(itemsTuple_);
#if RAPIDJSON_SCHEMA_HAS_REGEX
if (pattern_) {
pattern_->~RegexType();
AllocatorType::Free(pattern_);
}
#endif
}
const SValue& GetURI() const {
return uri_;
}
const PointerType& GetPointer() const {
return pointer_;
}
bool BeginValue(Context& context) const {
if (context.inArray) {
if (uniqueItems_)
context.valueUniqueness = true;
if (itemsList_)
context.valueSchema = itemsList_;
else if (itemsTuple_) {
if (context.arrayElementIndex < itemsTupleCount_)
context.valueSchema = itemsTuple_[context.arrayElementIndex];
else if (additionalItemsSchema_)
context.valueSchema = additionalItemsSchema_;
else if (additionalItems_)
context.valueSchema = typeless_;
else {
context.error_handler.DisallowedItem(context.arrayElementIndex);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetItemsString());
}
}
else
context.valueSchema = typeless_;
context.arrayElementIndex++;
}
return true;
}
RAPIDJSON_FORCEINLINE bool EndValue(Context& context) const {
if (context.patternPropertiesValidatorCount > 0) {
bool otherValid = false;
SizeType count = context.patternPropertiesValidatorCount;
if (context.objectPatternValidatorType != Context::kPatternValidatorOnly)
otherValid = context.patternPropertiesValidators[--count]->IsValid();
bool patternValid = true;
for (SizeType i = 0; i < count; i++)
if (!context.patternPropertiesValidators[i]->IsValid()) {
patternValid = false;
break;
}
if (context.objectPatternValidatorType == Context::kPatternValidatorOnly) {
if (!patternValid) {
context.error_handler.PropertyViolations(context.patternPropertiesValidators, count);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString());
}
}
else if (context.objectPatternValidatorType == Context::kPatternValidatorWithProperty) {
if (!patternValid || !otherValid) {
context.error_handler.PropertyViolations(context.patternPropertiesValidators, count + 1);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString());
}
}
else if (!patternValid && !otherValid) { // kPatternValidatorWithAdditionalProperty)
context.error_handler.PropertyViolations(context.patternPropertiesValidators, count + 1);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString());
}
}
if (enum_) {
const uint64_t h = context.factory.GetHashCode(context.hasher);
for (SizeType i = 0; i < enumCount_; i++)
if (enum_[i] == h)
goto foundEnum;
context.error_handler.DisallowedValue();
RAPIDJSON_INVALID_KEYWORD_RETURN(GetEnumString());
foundEnum:;
}
if (allOf_.schemas)
for (SizeType i = allOf_.begin; i < allOf_.begin + allOf_.count; i++)
if (!context.validators[i]->IsValid()) {
context.error_handler.NotAllOf(&context.validators[allOf_.begin], allOf_.count);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetAllOfString());
}
if (anyOf_.schemas) {
for (SizeType i = anyOf_.begin; i < anyOf_.begin + anyOf_.count; i++)
if (context.validators[i]->IsValid())
goto foundAny;
context.error_handler.NoneOf(&context.validators[anyOf_.begin], anyOf_.count);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetAnyOfString());
foundAny:;
}
if (oneOf_.schemas) {
bool oneValid = false;
for (SizeType i = oneOf_.begin; i < oneOf_.begin + oneOf_.count; i++)
if (context.validators[i]->IsValid()) {
if (oneValid) {
context.error_handler.NotOneOf(&context.validators[oneOf_.begin], oneOf_.count);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString());
} else
oneValid = true;
}
if (!oneValid) {
context.error_handler.NotOneOf(&context.validators[oneOf_.begin], oneOf_.count);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString());
}
}
if (not_ && context.validators[notValidatorIndex_]->IsValid()) {
context.error_handler.Disallowed();
RAPIDJSON_INVALID_KEYWORD_RETURN(GetNotString());
}
return true;
}
bool Null(Context& context) const {
if (!(type_ & (1 << kNullSchemaType))) {
DisallowedType(context, GetNullString());
RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
}
return CreateParallelValidator(context);
}
bool Bool(Context& context, bool) const {
if (!(type_ & (1 << kBooleanSchemaType))) {
DisallowedType(context, GetBooleanString());
RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
}
return CreateParallelValidator(context);
}
bool Int(Context& context, int i) const {
if (!CheckInt(context, i))
return false;
return CreateParallelValidator(context);
}
bool Uint(Context& context, unsigned u) const {
if (!CheckUint(context, u))
return false;
return CreateParallelValidator(context);
}
bool Int64(Context& context, int64_t i) const {
if (!CheckInt(context, i))
return false;
return CreateParallelValidator(context);
}
bool Uint64(Context& context, uint64_t u) const {
if (!CheckUint(context, u))
return false;
return CreateParallelValidator(context);
}
bool Double(Context& context, double d) const {
if (!(type_ & (1 << kNumberSchemaType))) {
DisallowedType(context, GetNumberString());
RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
}
if (!minimum_.IsNull() && !CheckDoubleMinimum(context, d))
return false;
if (!maximum_.IsNull() && !CheckDoubleMaximum(context, d))
return false;
if (!multipleOf_.IsNull() && !CheckDoubleMultipleOf(context, d))
return false;
return CreateParallelValidator(context);
}
bool String(Context& context, const Ch* str, SizeType length, bool) const {
if (!(type_ & (1 << kStringSchemaType))) {
DisallowedType(context, GetStringString());
RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
}
if (minLength_ != 0 || maxLength_ != SizeType(~0)) {
SizeType count;
if (internal::CountStringCodePoint<EncodingType>(str, length, &count)) {
if (count < minLength_) {
context.error_handler.TooShort(str, length, minLength_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinLengthString());
}
if (count > maxLength_) {
context.error_handler.TooLong(str, length, maxLength_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxLengthString());
}
}
}
if (pattern_ && !IsPatternMatch(pattern_, str, length)) {
context.error_handler.DoesNotMatch(str, length);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternString());
}
return CreateParallelValidator(context);
}
bool StartObject(Context& context) const {
if (!(type_ & (1 << kObjectSchemaType))) {
DisallowedType(context, GetObjectString());
RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
}
if (hasDependencies_ || hasRequired_) {
context.propertyExist = static_cast<bool*>(context.factory.MallocState(sizeof(bool) * propertyCount_));
std::memset(context.propertyExist, 0, sizeof(bool) * propertyCount_);
}
if (patternProperties_) { // pre-allocate schema array
SizeType count = patternPropertyCount_ + 1; // extra for valuePatternValidatorType
context.patternPropertiesSchemas = static_cast<const SchemaType**>(context.factory.MallocState(sizeof(const SchemaType*) * count));
context.patternPropertiesSchemaCount = 0;
std::memset(context.patternPropertiesSchemas, 0, sizeof(SchemaType*) * count);
}
return CreateParallelValidator(context);
}
bool Key(Context& context, const Ch* str, SizeType len, bool) const {
if (patternProperties_) {
context.patternPropertiesSchemaCount = 0;
for (SizeType i = 0; i < patternPropertyCount_; i++)
if (patternProperties_[i].pattern && IsPatternMatch(patternProperties_[i].pattern, str, len)) {
context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = patternProperties_[i].schema;
context.valueSchema = typeless_;
}
}
SizeType index = 0;
if (FindPropertyIndex(ValueType(str, len).Move(), &index)) {
if (context.patternPropertiesSchemaCount > 0) {
context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = properties_[index].schema;
context.valueSchema = typeless_;
context.valuePatternValidatorType = Context::kPatternValidatorWithProperty;
}
else
context.valueSchema = properties_[index].schema;
if (context.propertyExist)
context.propertyExist[index] = true;
return true;
}
if (additionalPropertiesSchema_) {
if (additionalPropertiesSchema_ && context.patternPropertiesSchemaCount > 0) {
context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = additionalPropertiesSchema_;
context.valueSchema = typeless_;
context.valuePatternValidatorType = Context::kPatternValidatorWithAdditionalProperty;
}
else
context.valueSchema = additionalPropertiesSchema_;
return true;
}
else if (additionalProperties_) {
context.valueSchema = typeless_;
return true;
}
if (context.patternPropertiesSchemaCount == 0) { // patternProperties are not additional properties
context.error_handler.DisallowedProperty(str, len);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetAdditionalPropertiesString());
}
return true;
}
bool EndObject(Context& context, SizeType memberCount) const {
if (hasRequired_) {
context.error_handler.StartMissingProperties();
for (SizeType index = 0; index < propertyCount_; index++)
if (properties_[index].required && !context.propertyExist[index])
if (properties_[index].schema->defaultValueLength_ == 0 )
context.error_handler.AddMissingProperty(properties_[index].name);
if (context.error_handler.EndMissingProperties())
RAPIDJSON_INVALID_KEYWORD_RETURN(GetRequiredString());
}
if (memberCount < minProperties_) {
context.error_handler.TooFewProperties(memberCount, minProperties_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinPropertiesString());
}
if (memberCount > maxProperties_) {
context.error_handler.TooManyProperties(memberCount, maxProperties_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxPropertiesString());
}
if (hasDependencies_) {
context.error_handler.StartDependencyErrors();
for (SizeType sourceIndex = 0; sourceIndex < propertyCount_; sourceIndex++) {
const Property& source = properties_[sourceIndex];
if (context.propertyExist[sourceIndex]) {
if (source.dependencies) {
context.error_handler.StartMissingDependentProperties();
for (SizeType targetIndex = 0; targetIndex < propertyCount_; targetIndex++)
if (source.dependencies[targetIndex] && !context.propertyExist[targetIndex])
context.error_handler.AddMissingDependentProperty(properties_[targetIndex].name);
context.error_handler.EndMissingDependentProperties(source.name);
}
else if (source.dependenciesSchema) {
ISchemaValidator* dependenciesValidator = context.validators[source.dependenciesValidatorIndex];
if (!dependenciesValidator->IsValid())
context.error_handler.AddDependencySchemaError(source.name, dependenciesValidator);
}
}
}
if (context.error_handler.EndDependencyErrors())
RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString());
}
return true;
}
bool StartArray(Context& context) const {
if (!(type_ & (1 << kArraySchemaType))) {
DisallowedType(context, GetArrayString());
RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
}
context.arrayElementIndex = 0;
context.inArray = true;
return CreateParallelValidator(context);
}
bool EndArray(Context& context, SizeType elementCount) const {
context.inArray = false;
if (elementCount < minItems_) {
context.error_handler.TooFewItems(elementCount, minItems_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinItemsString());
}
if (elementCount > maxItems_) {
context.error_handler.TooManyItems(elementCount, maxItems_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxItemsString());
}
return true;
}
// Generate functions for string literal according to Ch
#define RAPIDJSON_STRING_(name, ...) \
static const ValueType& Get##name##String() {\
static const Ch s[] = { __VA_ARGS__, '\0' };\
static const ValueType v(s, static_cast<SizeType>(sizeof(s) / sizeof(Ch) - 1));\
return v;\
}
RAPIDJSON_STRING_(Null, 'n', 'u', 'l', 'l')
RAPIDJSON_STRING_(Boolean, 'b', 'o', 'o', 'l', 'e', 'a', 'n')
RAPIDJSON_STRING_(Object, 'o', 'b', 'j', 'e', 'c', 't')
RAPIDJSON_STRING_(Array, 'a', 'r', 'r', 'a', 'y')
RAPIDJSON_STRING_(String, 's', 't', 'r', 'i', 'n', 'g')
RAPIDJSON_STRING_(Number, 'n', 'u', 'm', 'b', 'e', 'r')
RAPIDJSON_STRING_(Integer, 'i', 'n', 't', 'e', 'g', 'e', 'r')
RAPIDJSON_STRING_(Type, 't', 'y', 'p', 'e')
RAPIDJSON_STRING_(Enum, 'e', 'n', 'u', 'm')
RAPIDJSON_STRING_(AllOf, 'a', 'l', 'l', 'O', 'f')
RAPIDJSON_STRING_(AnyOf, 'a', 'n', 'y', 'O', 'f')
RAPIDJSON_STRING_(OneOf, 'o', 'n', 'e', 'O', 'f')
RAPIDJSON_STRING_(Not, 'n', 'o', 't')
RAPIDJSON_STRING_(Properties, 'p', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's')
RAPIDJSON_STRING_(Required, 'r', 'e', 'q', 'u', 'i', 'r', 'e', 'd')
RAPIDJSON_STRING_(Dependencies, 'd', 'e', 'p', 'e', 'n', 'd', 'e', 'n', 'c', 'i', 'e', 's')
RAPIDJSON_STRING_(PatternProperties, 'p', 'a', 't', 't', 'e', 'r', 'n', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's')
RAPIDJSON_STRING_(AdditionalProperties, 'a', 'd', 'd', 'i', 't', 'i', 'o', 'n', 'a', 'l', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's')
RAPIDJSON_STRING_(MinProperties, 'm', 'i', 'n', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's')
RAPIDJSON_STRING_(MaxProperties, 'm', 'a', 'x', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's')
RAPIDJSON_STRING_(Items, 'i', 't', 'e', 'm', 's')
RAPIDJSON_STRING_(MinItems, 'm', 'i', 'n', 'I', 't', 'e', 'm', 's')
RAPIDJSON_STRING_(MaxItems, 'm', 'a', 'x', 'I', 't', 'e', 'm', 's')
RAPIDJSON_STRING_(AdditionalItems, 'a', 'd', 'd', 'i', 't', 'i', 'o', 'n', 'a', 'l', 'I', 't', 'e', 'm', 's')
RAPIDJSON_STRING_(UniqueItems, 'u', 'n', 'i', 'q', 'u', 'e', 'I', 't', 'e', 'm', 's')
RAPIDJSON_STRING_(MinLength, 'm', 'i', 'n', 'L', 'e', 'n', 'g', 't', 'h')
RAPIDJSON_STRING_(MaxLength, 'm', 'a', 'x', 'L', 'e', 'n', 'g', 't', 'h')
RAPIDJSON_STRING_(Pattern, 'p', 'a', 't', 't', 'e', 'r', 'n')
RAPIDJSON_STRING_(Minimum, 'm', 'i', 'n', 'i', 'm', 'u', 'm')
RAPIDJSON_STRING_(Maximum, 'm', 'a', 'x', 'i', 'm', 'u', 'm')
RAPIDJSON_STRING_(ExclusiveMinimum, 'e', 'x', 'c', 'l', 'u', 's', 'i', 'v', 'e', 'M', 'i', 'n', 'i', 'm', 'u', 'm')
RAPIDJSON_STRING_(ExclusiveMaximum, 'e', 'x', 'c', 'l', 'u', 's', 'i', 'v', 'e', 'M', 'a', 'x', 'i', 'm', 'u', 'm')
RAPIDJSON_STRING_(MultipleOf, 'm', 'u', 'l', 't', 'i', 'p', 'l', 'e', 'O', 'f')
RAPIDJSON_STRING_(DefaultValue, 'd', 'e', 'f', 'a', 'u', 'l', 't')
#undef RAPIDJSON_STRING_
private:
enum SchemaValueType {
kNullSchemaType,
kBooleanSchemaType,
kObjectSchemaType,
kArraySchemaType,
kStringSchemaType,
kNumberSchemaType,
kIntegerSchemaType,
kTotalSchemaType
};
#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX
typedef internal::GenericRegex<EncodingType, AllocatorType> RegexType;
#elif RAPIDJSON_SCHEMA_USE_STDREGEX
typedef std::basic_regex<Ch> RegexType;
#else
typedef char RegexType;
#endif
struct SchemaArray {
SchemaArray() : schemas(), count() {}
~SchemaArray() { AllocatorType::Free(schemas); }
const SchemaType** schemas;
SizeType begin; // begin index of context.validators
SizeType count;
};
template <typename V1, typename V2>
void AddUniqueElement(V1& a, const V2& v) {
for (typename V1::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)
if (*itr == v)
return;
V1 c(v, *allocator_);
a.PushBack(c, *allocator_);
}
static const ValueType* GetMember(const ValueType& value, const ValueType& name) {
typename ValueType::ConstMemberIterator itr = value.FindMember(name);
return itr != value.MemberEnd() ? &(itr->value) : 0;
}
static void AssignIfExist(bool& out, const ValueType& value, const ValueType& name) {
if (const ValueType* v = GetMember(value, name))
if (v->IsBool())
out = v->GetBool();
}
static void AssignIfExist(SizeType& out, const ValueType& value, const ValueType& name) {
if (const ValueType* v = GetMember(value, name))
if (v->IsUint64() && v->GetUint64() <= SizeType(~0))
out = static_cast<SizeType>(v->GetUint64());
}
void AssignIfExist(SchemaArray& out, SchemaDocumentType& schemaDocument, const PointerType& p, const ValueType& value, const ValueType& name, const ValueType& document) {
if (const ValueType* v = GetMember(value, name)) {
if (v->IsArray() && v->Size() > 0) {
PointerType q = p.Append(name, allocator_);
out.count = v->Size();
out.schemas = static_cast<const Schema**>(allocator_->Malloc(out.count * sizeof(const Schema*)));
memset(out.schemas, 0, sizeof(Schema*)* out.count);
for (SizeType i = 0; i < out.count; i++)
schemaDocument.CreateSchema(&out.schemas[i], q.Append(i, allocator_), (*v)[i], document);
out.begin = validatorCount_;
validatorCount_ += out.count;
}
}
}
#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX
template <typename ValueType>
RegexType* CreatePattern(const ValueType& value) {
if (value.IsString()) {
RegexType* r = new (allocator_->Malloc(sizeof(RegexType))) RegexType(value.GetString(), allocator_);
if (!r->IsValid()) {
r->~RegexType();
AllocatorType::Free(r);
r = 0;
}
return r;
}
return 0;
}
static bool IsPatternMatch(const RegexType* pattern, const Ch *str, SizeType) {
GenericRegexSearch<RegexType> rs(*pattern);
return rs.Search(str);
}
#elif RAPIDJSON_SCHEMA_USE_STDREGEX
template <typename ValueType>
RegexType* CreatePattern(const ValueType& value) {
if (value.IsString()) {
RegexType *r = static_cast<RegexType*>(allocator_->Malloc(sizeof(RegexType)));
try {
return new (r) RegexType(value.GetString(), std::size_t(value.GetStringLength()), std::regex_constants::ECMAScript);
}
catch (const std::regex_error&) {
AllocatorType::Free(r);
}
}
return 0;
}
static bool IsPatternMatch(const RegexType* pattern, const Ch *str, SizeType length) {
std::match_results<const Ch*> r;
return std::regex_search(str, str + length, r, *pattern);
}
#else
template <typename ValueType>
RegexType* CreatePattern(const ValueType&) { return 0; }
static bool IsPatternMatch(const RegexType*, const Ch *, SizeType) { return true; }
#endif // RAPIDJSON_SCHEMA_USE_STDREGEX
void AddType(const ValueType& type) {
if (type == GetNullString() ) type_ |= 1 << kNullSchemaType;
else if (type == GetBooleanString()) type_ |= 1 << kBooleanSchemaType;
else if (type == GetObjectString() ) type_ |= 1 << kObjectSchemaType;
else if (type == GetArrayString() ) type_ |= 1 << kArraySchemaType;
else if (type == GetStringString() ) type_ |= 1 << kStringSchemaType;
else if (type == GetIntegerString()) type_ |= 1 << kIntegerSchemaType;
else if (type == GetNumberString() ) type_ |= (1 << kNumberSchemaType) | (1 << kIntegerSchemaType);
}
bool CreateParallelValidator(Context& context) const {
if (enum_ || context.arrayUniqueness)
context.hasher = context.factory.CreateHasher();
if (validatorCount_) {
RAPIDJSON_ASSERT(context.validators == 0);
context.validators = static_cast<ISchemaValidator**>(context.factory.MallocState(sizeof(ISchemaValidator*) * validatorCount_));
context.validatorCount = validatorCount_;
if (allOf_.schemas)
CreateSchemaValidators(context, allOf_);
if (anyOf_.schemas)
CreateSchemaValidators(context, anyOf_);
if (oneOf_.schemas)
CreateSchemaValidators(context, oneOf_);
if (not_)
context.validators[notValidatorIndex_] = context.factory.CreateSchemaValidator(*not_);
if (hasSchemaDependencies_) {
for (SizeType i = 0; i < propertyCount_; i++)
if (properties_[i].dependenciesSchema)
context.validators[properties_[i].dependenciesValidatorIndex] = context.factory.CreateSchemaValidator(*properties_[i].dependenciesSchema);
}
}
return true;
}
void CreateSchemaValidators(Context& context, const SchemaArray& schemas) const {
for (SizeType i = 0; i < schemas.count; i++)
context.validators[schemas.begin + i] = context.factory.CreateSchemaValidator(*schemas.schemas[i]);
}
// O(n)
bool FindPropertyIndex(const ValueType& name, SizeType* outIndex) const {
SizeType len = name.GetStringLength();
const Ch* str = name.GetString();
for (SizeType index = 0; index < propertyCount_; index++)
if (properties_[index].name.GetStringLength() == len &&
(std::memcmp(properties_[index].name.GetString(), str, sizeof(Ch) * len) == 0))
{
*outIndex = index;
return true;
}
return false;
}
bool CheckInt(Context& context, int64_t i) const {
if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) {
DisallowedType(context, GetIntegerString());
RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
}
if (!minimum_.IsNull()) {
if (minimum_.IsInt64()) {
if (exclusiveMinimum_ ? i <= minimum_.GetInt64() : i < minimum_.GetInt64()) {
context.error_handler.BelowMinimum(i, minimum_, exclusiveMinimum_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString());
}
}
else if (minimum_.IsUint64()) {
context.error_handler.BelowMinimum(i, minimum_, exclusiveMinimum_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); // i <= max(int64_t) < minimum.GetUint64()
}
else if (!CheckDoubleMinimum(context, static_cast<double>(i)))
return false;
}
if (!maximum_.IsNull()) {
if (maximum_.IsInt64()) {
if (exclusiveMaximum_ ? i >= maximum_.GetInt64() : i > maximum_.GetInt64()) {
context.error_handler.AboveMaximum(i, maximum_, exclusiveMaximum_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString());
}
}
else if (maximum_.IsUint64()) { }
/* do nothing */ // i <= max(int64_t) < maximum_.GetUint64()
else if (!CheckDoubleMaximum(context, static_cast<double>(i)))
return false;
}
if (!multipleOf_.IsNull()) {
if (multipleOf_.IsUint64()) {
if (static_cast<uint64_t>(i >= 0 ? i : -i) % multipleOf_.GetUint64() != 0) {
context.error_handler.NotMultipleOf(i, multipleOf_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString());
}
}
else if (!CheckDoubleMultipleOf(context, static_cast<double>(i)))
return false;
}
return true;
}
bool CheckUint(Context& context, uint64_t i) const {
if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) {
DisallowedType(context, GetIntegerString());
RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
}
if (!minimum_.IsNull()) {
if (minimum_.IsUint64()) {
if (exclusiveMinimum_ ? i <= minimum_.GetUint64() : i < minimum_.GetUint64()) {
context.error_handler.BelowMinimum(i, minimum_, exclusiveMinimum_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString());
}
}
else if (minimum_.IsInt64())
/* do nothing */; // i >= 0 > minimum.Getint64()
else if (!CheckDoubleMinimum(context, static_cast<double>(i)))
return false;
}
if (!maximum_.IsNull()) {
if (maximum_.IsUint64()) {
if (exclusiveMaximum_ ? i >= maximum_.GetUint64() : i > maximum_.GetUint64()) {
context.error_handler.AboveMaximum(i, maximum_, exclusiveMaximum_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString());
}
}
else if (maximum_.IsInt64()) {
context.error_handler.AboveMaximum(i, maximum_, exclusiveMaximum_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); // i >= 0 > maximum_
}
else if (!CheckDoubleMaximum(context, static_cast<double>(i)))
return false;
}
if (!multipleOf_.IsNull()) {
if (multipleOf_.IsUint64()) {
if (i % multipleOf_.GetUint64() != 0) {
context.error_handler.NotMultipleOf(i, multipleOf_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString());
}
}
else if (!CheckDoubleMultipleOf(context, static_cast<double>(i)))
return false;
}
return true;
}
bool CheckDoubleMinimum(Context& context, double d) const {
if (exclusiveMinimum_ ? d <= minimum_.GetDouble() : d < minimum_.GetDouble()) {
context.error_handler.BelowMinimum(d, minimum_, exclusiveMinimum_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString());
}
return true;
}
bool CheckDoubleMaximum(Context& context, double d) const {
if (exclusiveMaximum_ ? d >= maximum_.GetDouble() : d > maximum_.GetDouble()) {
context.error_handler.AboveMaximum(d, maximum_, exclusiveMaximum_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString());
}
return true;
}
bool CheckDoubleMultipleOf(Context& context, double d) const {
double a = std::abs(d), b = std::abs(multipleOf_.GetDouble());
double q = std::floor(a / b);
double r = a - q * b;
if (r > 0.0) {
context.error_handler.NotMultipleOf(d, multipleOf_);
RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString());
}
return true;
}
void DisallowedType(Context& context, const ValueType& actualType) const {
ErrorHandler& eh = context.error_handler;
eh.StartDisallowedType();
if (type_ & (1 << kNullSchemaType)) eh.AddExpectedType(GetNullString());
if (type_ & (1 << kBooleanSchemaType)) eh.AddExpectedType(GetBooleanString());
if (type_ & (1 << kObjectSchemaType)) eh.AddExpectedType(GetObjectString());
if (type_ & (1 << kArraySchemaType)) eh.AddExpectedType(GetArrayString());
if (type_ & (1 << kStringSchemaType)) eh.AddExpectedType(GetStringString());
if (type_ & (1 << kNumberSchemaType)) eh.AddExpectedType(GetNumberString());
else if (type_ & (1 << kIntegerSchemaType)) eh.AddExpectedType(GetIntegerString());
eh.EndDisallowedType(actualType);
}
struct Property {
Property() : schema(), dependenciesSchema(), dependenciesValidatorIndex(), dependencies(), required(false) {}
~Property() { AllocatorType::Free(dependencies); }
SValue name;
const SchemaType* schema;
const SchemaType* dependenciesSchema;
SizeType dependenciesValidatorIndex;
bool* dependencies;
bool required;
};
struct PatternProperty {
PatternProperty() : schema(), pattern() {}
~PatternProperty() {
if (pattern) {
pattern->~RegexType();
AllocatorType::Free(pattern);
}
}
const SchemaType* schema;
RegexType* pattern;
};
AllocatorType* allocator_;
SValue uri_;
PointerType pointer_;
const SchemaType* typeless_;
uint64_t* enum_;
SizeType enumCount_;
SchemaArray allOf_;
SchemaArray anyOf_;
SchemaArray oneOf_;
const SchemaType* not_;
unsigned type_; // bitmask of kSchemaType
SizeType validatorCount_;
SizeType notValidatorIndex_;
Property* properties_;
const SchemaType* additionalPropertiesSchema_;
PatternProperty* patternProperties_;
SizeType patternPropertyCount_;
SizeType propertyCount_;
SizeType minProperties_;
SizeType maxProperties_;
bool additionalProperties_;
bool hasDependencies_;
bool hasRequired_;
bool hasSchemaDependencies_;
const SchemaType* additionalItemsSchema_;
const SchemaType* itemsList_;
const SchemaType** itemsTuple_;
SizeType itemsTupleCount_;
SizeType minItems_;
SizeType maxItems_;
bool additionalItems_;
bool uniqueItems_;
RegexType* pattern_;
SizeType minLength_;
SizeType maxLength_;
SValue minimum_;
SValue maximum_;
SValue multipleOf_;
bool exclusiveMinimum_;
bool exclusiveMaximum_;
SizeType defaultValueLength_;
};
template<typename Stack, typename Ch>
struct TokenHelper {
RAPIDJSON_FORCEINLINE static void AppendIndexToken(Stack& documentStack, SizeType index) {
*documentStack.template Push<Ch>() = '/';
char buffer[21];
size_t length = static_cast<size_t>((sizeof(SizeType) == 4 ? u32toa(index, buffer) : u64toa(index, buffer)) - buffer);
for (size_t i = 0; i < length; i++)
*documentStack.template Push<Ch>() = static_cast<Ch>(buffer[i]);
}
};
// Partial specialized version for char to prevent buffer copying.
template <typename Stack>
struct TokenHelper<Stack, char> {
RAPIDJSON_FORCEINLINE static void AppendIndexToken(Stack& documentStack, SizeType index) {
if (sizeof(SizeType) == 4) {
char *buffer = documentStack.template Push<char>(1 + 10); // '/' + uint
*buffer++ = '/';
const char* end = internal::u32toa(index, buffer);
documentStack.template Pop<char>(static_cast<size_t>(10 - (end - buffer)));
}
else {
char *buffer = documentStack.template Push<char>(1 + 20); // '/' + uint64
*buffer++ = '/';
const char* end = internal::u64toa(index, buffer);
documentStack.template Pop<char>(static_cast<size_t>(20 - (end - buffer)));
}
}
};
} // namespace internal
///////////////////////////////////////////////////////////////////////////////
// IGenericRemoteSchemaDocumentProvider
template <typename SchemaDocumentType>
class IGenericRemoteSchemaDocumentProvider {
public:
typedef typename SchemaDocumentType::Ch Ch;
virtual ~IGenericRemoteSchemaDocumentProvider() {}
virtual const SchemaDocumentType* GetRemoteDocument(const Ch* uri, SizeType length) = 0;
};
///////////////////////////////////////////////////////////////////////////////
// GenericSchemaDocument
//! JSON schema document.
/*!
A JSON schema document is a compiled version of a JSON schema.
It is basically a tree of internal::Schema.
\note This is an immutable class (i.e. its instance cannot be modified after construction).
\tparam ValueT Type of JSON value (e.g. \c Value ), which also determine the encoding.
\tparam Allocator Allocator type for allocating memory of this document.
*/
template <typename ValueT, typename Allocator = CrtAllocator>
class GenericSchemaDocument {
public:
typedef ValueT ValueType;
typedef IGenericRemoteSchemaDocumentProvider<GenericSchemaDocument> IRemoteSchemaDocumentProviderType;
typedef Allocator AllocatorType;
typedef typename ValueType::EncodingType EncodingType;
typedef typename EncodingType::Ch Ch;
typedef internal::Schema<GenericSchemaDocument> SchemaType;
typedef GenericPointer<ValueType, Allocator> PointerType;
typedef GenericValue<EncodingType, Allocator> URIType;
friend class internal::Schema<GenericSchemaDocument>;
template <typename, typename, typename>
friend class GenericSchemaValidator;
//! Constructor.
/*!
Compile a JSON document into schema document.
\param document A JSON document as source.
\param uri The base URI of this schema document for purposes of violation reporting.
\param uriLength Length of \c name, in code points.
\param remoteProvider An optional remote schema document provider for resolving remote reference. Can be null.
\param allocator An optional allocator instance for allocating memory. Can be null.
*/
explicit GenericSchemaDocument(const ValueType& document, const Ch* uri = 0, SizeType uriLength = 0,
IRemoteSchemaDocumentProviderType* remoteProvider = 0, Allocator* allocator = 0) :
remoteProvider_(remoteProvider),
allocator_(allocator),
ownAllocator_(),
root_(),
typeless_(),
schemaMap_(allocator, kInitialSchemaMapSize),
schemaRef_(allocator, kInitialSchemaRefSize)
{
if (!allocator_)
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
Ch noUri[1] = {0};
uri_.SetString(uri ? uri : noUri, uriLength, *allocator_);
typeless_ = static_cast<SchemaType*>(allocator_->Malloc(sizeof(SchemaType)));
new (typeless_) SchemaType(this, PointerType(), ValueType(kObjectType).Move(), ValueType(kObjectType).Move(), allocator_);
// Generate root schema, it will call CreateSchema() to create sub-schemas,
// And call AddRefSchema() if there are $ref.
CreateSchemaRecursive(&root_, PointerType(), document, document);
// Resolve $ref
while (!schemaRef_.Empty()) {
SchemaRefEntry* refEntry = schemaRef_.template Pop<SchemaRefEntry>(1);
if (const SchemaType* s = GetSchema(refEntry->target)) {
if (refEntry->schema)
*refEntry->schema = s;
// Create entry in map if not exist
if (!GetSchema(refEntry->source)) {
new (schemaMap_.template Push<SchemaEntry>()) SchemaEntry(refEntry->source, const_cast<SchemaType*>(s), false, allocator_);
}
}
else if (refEntry->schema)
*refEntry->schema = typeless_;
refEntry->~SchemaRefEntry();
}
RAPIDJSON_ASSERT(root_ != 0);
schemaRef_.ShrinkToFit(); // Deallocate all memory for ref
}
#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
//! Move constructor in C++11
GenericSchemaDocument(GenericSchemaDocument&& rhs) RAPIDJSON_NOEXCEPT :
remoteProvider_(rhs.remoteProvider_),
allocator_(rhs.allocator_),
ownAllocator_(rhs.ownAllocator_),
root_(rhs.root_),
typeless_(rhs.typeless_),
schemaMap_(std::move(rhs.schemaMap_)),
schemaRef_(std::move(rhs.schemaRef_)),
uri_(std::move(rhs.uri_))
{
rhs.remoteProvider_ = 0;
rhs.allocator_ = 0;
rhs.ownAllocator_ = 0;
rhs.typeless_ = 0;
}
#endif
//! Destructor
~GenericSchemaDocument() {
while (!schemaMap_.Empty())
schemaMap_.template Pop<SchemaEntry>(1)->~SchemaEntry();
if (typeless_) {
typeless_->~SchemaType();
Allocator::Free(typeless_);
}
RAPIDJSON_DELETE(ownAllocator_);
}
const URIType& GetURI() const { return uri_; }
//! Get the root schema.
const SchemaType& GetRoot() const { return *root_; }
private:
//! Prohibit copying
GenericSchemaDocument(const GenericSchemaDocument&);
//! Prohibit assignment
GenericSchemaDocument& operator=(const GenericSchemaDocument&);
struct SchemaRefEntry {
SchemaRefEntry(const PointerType& s, const PointerType& t, const SchemaType** outSchema, Allocator *allocator) : source(s, allocator), target(t, allocator), schema(outSchema) {}
PointerType source;
PointerType target;
const SchemaType** schema;
};
struct SchemaEntry {
SchemaEntry(const PointerType& p, SchemaType* s, bool o, Allocator* allocator) : pointer(p, allocator), schema(s), owned(o) {}
~SchemaEntry() {
if (owned) {
schema->~SchemaType();
Allocator::Free(schema);
}
}
PointerType pointer;
SchemaType* schema;
bool owned;
};
void CreateSchemaRecursive(const SchemaType** schema, const PointerType& pointer, const ValueType& v, const ValueType& document) {
if (schema)
*schema = typeless_;
if (v.GetType() == kObjectType) {
const SchemaType* s = GetSchema(pointer);
if (!s)
CreateSchema(schema, pointer, v, document);
for (typename ValueType::ConstMemberIterator itr = v.MemberBegin(); itr != v.MemberEnd(); ++itr)
CreateSchemaRecursive(0, pointer.Append(itr->name, allocator_), itr->value, document);
}
else if (v.GetType() == kArrayType)
for (SizeType i = 0; i < v.Size(); i++)
CreateSchemaRecursive(0, pointer.Append(i, allocator_), v[i], document);
}
void CreateSchema(const SchemaType** schema, const PointerType& pointer, const ValueType& v, const ValueType& document) {
RAPIDJSON_ASSERT(pointer.IsValid());
if (v.IsObject()) {
if (!HandleRefSchema(pointer, schema, v, document)) {
SchemaType* s = new (allocator_->Malloc(sizeof(SchemaType))) SchemaType(this, pointer, v, document, allocator_);
new (schemaMap_.template Push<SchemaEntry>()) SchemaEntry(pointer, s, true, allocator_);
if (schema)
*schema = s;
}
}
}
bool HandleRefSchema(const PointerType& source, const SchemaType** schema, const ValueType& v, const ValueType& document) {
static const Ch kRefString[] = { '$', 'r', 'e', 'f', '\0' };
static const ValueType kRefValue(kRefString, 4);
typename ValueType::ConstMemberIterator itr = v.FindMember(kRefValue);
if (itr == v.MemberEnd())
return false;
if (itr->value.IsString()) {
SizeType len = itr->value.GetStringLength();
if (len > 0) {
const Ch* s = itr->value.GetString();
SizeType i = 0;
while (i < len && s[i] != '#') // Find the first #
i++;
if (i > 0) { // Remote reference, resolve immediately
if (remoteProvider_) {
if (const GenericSchemaDocument* remoteDocument = remoteProvider_->GetRemoteDocument(s, i)) {
PointerType pointer(&s[i], len - i, allocator_);
if (pointer.IsValid()) {
if (const SchemaType* sc = remoteDocument->GetSchema(pointer)) {
if (schema)
*schema = sc;
new (schemaMap_.template Push<SchemaEntry>()) SchemaEntry(source, const_cast<SchemaType*>(sc), false, allocator_);
return true;
}
}
}
}
}
else if (s[i] == '#') { // Local reference, defer resolution
PointerType pointer(&s[i], len - i, allocator_);
if (pointer.IsValid()) {
if (const ValueType* nv = pointer.Get(document))
if (HandleRefSchema(source, schema, *nv, document))
return true;
new (schemaRef_.template Push<SchemaRefEntry>()) SchemaRefEntry(source, pointer, schema, allocator_);
return true;
}
}
}
}
return false;
}
const SchemaType* GetSchema(const PointerType& pointer) const {
for (const SchemaEntry* target = schemaMap_.template Bottom<SchemaEntry>(); target != schemaMap_.template End<SchemaEntry>(); ++target)
if (pointer == target->pointer)
return target->schema;
return 0;
}
PointerType GetPointer(const SchemaType* schema) const {
for (const SchemaEntry* target = schemaMap_.template Bottom<SchemaEntry>(); target != schemaMap_.template End<SchemaEntry>(); ++target)
if (schema == target->schema)
return target->pointer;
return PointerType();
}
const SchemaType* GetTypeless() const { return typeless_; }
static const size_t kInitialSchemaMapSize = 64;
static const size_t kInitialSchemaRefSize = 64;
IRemoteSchemaDocumentProviderType* remoteProvider_;
Allocator *allocator_;
Allocator *ownAllocator_;
const SchemaType* root_; //!< Root schema.
SchemaType* typeless_;
internal::Stack<Allocator> schemaMap_; // Stores created Pointer -> Schemas
internal::Stack<Allocator> schemaRef_; // Stores Pointer from $ref and schema which holds the $ref
URIType uri_;
};
//! GenericSchemaDocument using Value type.
typedef GenericSchemaDocument<Value> SchemaDocument;
//! IGenericRemoteSchemaDocumentProvider using SchemaDocument.
typedef IGenericRemoteSchemaDocumentProvider<SchemaDocument> IRemoteSchemaDocumentProvider;
///////////////////////////////////////////////////////////////////////////////
// GenericSchemaValidator
//! JSON Schema Validator.
/*!
A SAX style JSON schema validator.
It uses a \c GenericSchemaDocument to validate SAX events.
It delegates the incoming SAX events to an output handler.
The default output handler does nothing.
It can be reused multiple times by calling \c Reset().
\tparam SchemaDocumentType Type of schema document.
\tparam OutputHandler Type of output handler. Default handler does nothing.
\tparam StateAllocator Allocator for storing the internal validation states.
*/
template <
typename SchemaDocumentType,
typename OutputHandler = BaseReaderHandler<typename SchemaDocumentType::SchemaType::EncodingType>,
typename StateAllocator = CrtAllocator>
class GenericSchemaValidator :
public internal::ISchemaStateFactory<typename SchemaDocumentType::SchemaType>,
public internal::ISchemaValidator,
public internal::IValidationErrorHandler<typename SchemaDocumentType::SchemaType>
{
public:
typedef typename SchemaDocumentType::SchemaType SchemaType;
typedef typename SchemaDocumentType::PointerType PointerType;
typedef typename SchemaType::EncodingType EncodingType;
typedef typename SchemaType::SValue SValue;
typedef typename EncodingType::Ch Ch;
typedef GenericStringRef<Ch> StringRefType;
typedef GenericValue<EncodingType, StateAllocator> ValueType;
//! Constructor without output handler.
/*!
\param schemaDocument The schema document to conform to.
\param allocator Optional allocator for storing internal validation states.
\param schemaStackCapacity Optional initial capacity of schema path stack.
\param documentStackCapacity Optional initial capacity of document path stack.
*/
GenericSchemaValidator(
const SchemaDocumentType& schemaDocument,
StateAllocator* allocator = 0,
size_t schemaStackCapacity = kDefaultSchemaStackCapacity,
size_t documentStackCapacity = kDefaultDocumentStackCapacity)
:
schemaDocument_(&schemaDocument),
root_(schemaDocument.GetRoot()),
stateAllocator_(allocator),
ownStateAllocator_(0),
schemaStack_(allocator, schemaStackCapacity),
documentStack_(allocator, documentStackCapacity),
outputHandler_(0),
error_(kObjectType),
currentError_(),
missingDependents_(),
valid_(true)
#if RAPIDJSON_SCHEMA_VERBOSE
, depth_(0)
#endif
{
}
//! Constructor with output handler.
/*!
\param schemaDocument The schema document to conform to.
\param allocator Optional allocator for storing internal validation states.
\param schemaStackCapacity Optional initial capacity of schema path stack.
\param documentStackCapacity Optional initial capacity of document path stack.
*/
GenericSchemaValidator(
const SchemaDocumentType& schemaDocument,
OutputHandler& outputHandler,
StateAllocator* allocator = 0,
size_t schemaStackCapacity = kDefaultSchemaStackCapacity,
size_t documentStackCapacity = kDefaultDocumentStackCapacity)
:
schemaDocument_(&schemaDocument),
root_(schemaDocument.GetRoot()),
stateAllocator_(allocator),
ownStateAllocator_(0),
schemaStack_(allocator, schemaStackCapacity),
documentStack_(allocator, documentStackCapacity),
outputHandler_(&outputHandler),
error_(kObjectType),
currentError_(),
missingDependents_(),
valid_(true)
#if RAPIDJSON_SCHEMA_VERBOSE
, depth_(0)
#endif
{
}
//! Destructor.
~GenericSchemaValidator() {
Reset();
RAPIDJSON_DELETE(ownStateAllocator_);
}
//! Reset the internal states.
void Reset() {
while (!schemaStack_.Empty())
PopSchema();
documentStack_.Clear();
error_.SetObject();
currentError_.SetNull();
missingDependents_.SetNull();
valid_ = true;
}
//! Checks whether the current state is valid.
// Implementation of ISchemaValidator
virtual bool IsValid() const { return valid_; }
//! Gets the error object.
ValueType& GetError() { return error_; }
const ValueType& GetError() const { return error_; }
//! Gets the JSON pointer pointed to the invalid schema.
PointerType GetInvalidSchemaPointer() const {
return schemaStack_.Empty() ? PointerType() : CurrentSchema().GetPointer();
}
//! Gets the keyword of invalid schema.
const Ch* GetInvalidSchemaKeyword() const {
return schemaStack_.Empty() ? 0 : CurrentContext().invalidKeyword;
}
//! Gets the JSON pointer pointed to the invalid value.
PointerType GetInvalidDocumentPointer() const {
if (documentStack_.Empty()) {
return PointerType();
}
else {
return PointerType(documentStack_.template Bottom<Ch>(), documentStack_.GetSize() / sizeof(Ch));
}
}
void NotMultipleOf(int64_t actual, const SValue& expected) {
AddNumberError(SchemaType::GetMultipleOfString(), ValueType(actual).Move(), expected);
}
void NotMultipleOf(uint64_t actual, const SValue& expected) {
AddNumberError(SchemaType::GetMultipleOfString(), ValueType(actual).Move(), expected);
}
void NotMultipleOf(double actual, const SValue& expected) {
AddNumberError(SchemaType::GetMultipleOfString(), ValueType(actual).Move(), expected);
}
void AboveMaximum(int64_t actual, const SValue& expected, bool exclusive) {
AddNumberError(SchemaType::GetMaximumString(), ValueType(actual).Move(), expected,
exclusive ? &SchemaType::GetExclusiveMaximumString : 0);
}
void AboveMaximum(uint64_t actual, const SValue& expected, bool exclusive) {
AddNumberError(SchemaType::GetMaximumString(), ValueType(actual).Move(), expected,
exclusive ? &SchemaType::GetExclusiveMaximumString : 0);
}
void AboveMaximum(double actual, const SValue& expected, bool exclusive) {
AddNumberError(SchemaType::GetMaximumString(), ValueType(actual).Move(), expected,
exclusive ? &SchemaType::GetExclusiveMaximumString : 0);
}
void BelowMinimum(int64_t actual, const SValue& expected, bool exclusive) {
AddNumberError(SchemaType::GetMinimumString(), ValueType(actual).Move(), expected,
exclusive ? &SchemaType::GetExclusiveMinimumString : 0);
}
void BelowMinimum(uint64_t actual, const SValue& expected, bool exclusive) {
AddNumberError(SchemaType::GetMinimumString(), ValueType(actual).Move(), expected,
exclusive ? &SchemaType::GetExclusiveMinimumString : 0);
}
void BelowMinimum(double actual, const SValue& expected, bool exclusive) {
AddNumberError(SchemaType::GetMinimumString(), ValueType(actual).Move(), expected,
exclusive ? &SchemaType::GetExclusiveMinimumString : 0);
}
void TooLong(const Ch* str, SizeType length, SizeType expected) {
AddNumberError(SchemaType::GetMaxLengthString(),
ValueType(str, length, GetStateAllocator()).Move(), SValue(expected).Move());
}
void TooShort(const Ch* str, SizeType length, SizeType expected) {
AddNumberError(SchemaType::GetMinLengthString(),
ValueType(str, length, GetStateAllocator()).Move(), SValue(expected).Move());
}
void DoesNotMatch(const Ch* str, SizeType length) {
currentError_.SetObject();
currentError_.AddMember(GetActualString(), ValueType(str, length, GetStateAllocator()).Move(), GetStateAllocator());
AddCurrentError(SchemaType::GetPatternString());
}
void DisallowedItem(SizeType index) {
currentError_.SetObject();
currentError_.AddMember(GetDisallowedString(), ValueType(index).Move(), GetStateAllocator());
AddCurrentError(SchemaType::GetAdditionalItemsString(), true);
}
void TooFewItems(SizeType actualCount, SizeType expectedCount) {
AddNumberError(SchemaType::GetMinItemsString(),
ValueType(actualCount).Move(), SValue(expectedCount).Move());
}
void TooManyItems(SizeType actualCount, SizeType expectedCount) {
AddNumberError(SchemaType::GetMaxItemsString(),
ValueType(actualCount).Move(), SValue(expectedCount).Move());
}
void DuplicateItems(SizeType index1, SizeType index2) {
ValueType duplicates(kArrayType);
duplicates.PushBack(index1, GetStateAllocator());
duplicates.PushBack(index2, GetStateAllocator());
currentError_.SetObject();
currentError_.AddMember(GetDuplicatesString(), duplicates, GetStateAllocator());
AddCurrentError(SchemaType::GetUniqueItemsString(), true);
}
void TooManyProperties(SizeType actualCount, SizeType expectedCount) {
AddNumberError(SchemaType::GetMaxPropertiesString(),
ValueType(actualCount).Move(), SValue(expectedCount).Move());
}
void TooFewProperties(SizeType actualCount, SizeType expectedCount) {
AddNumberError(SchemaType::GetMinPropertiesString(),
ValueType(actualCount).Move(), SValue(expectedCount).Move());
}
void StartMissingProperties() {
currentError_.SetArray();
}
void AddMissingProperty(const SValue& name) {
currentError_.PushBack(ValueType(name, GetStateAllocator()).Move(), GetStateAllocator());
}
bool EndMissingProperties() {
if (currentError_.Empty())
return false;
ValueType error(kObjectType);
error.AddMember(GetMissingString(), currentError_, GetStateAllocator());
currentError_ = error;
AddCurrentError(SchemaType::GetRequiredString());
return true;
}
void PropertyViolations(ISchemaValidator** subvalidators, SizeType count) {
for (SizeType i = 0; i < count; ++i)
MergeError(static_cast<GenericSchemaValidator*>(subvalidators[i])->GetError());
}
void DisallowedProperty(const Ch* name, SizeType length) {
currentError_.SetObject();
currentError_.AddMember(GetDisallowedString(), ValueType(name, length, GetStateAllocator()).Move(), GetStateAllocator());
AddCurrentError(SchemaType::GetAdditionalPropertiesString(), true);
}
void StartDependencyErrors() {
currentError_.SetObject();
}
void StartMissingDependentProperties() {
missingDependents_.SetArray();
}
void AddMissingDependentProperty(const SValue& targetName) {
missingDependents_.PushBack(ValueType(targetName, GetStateAllocator()).Move(), GetStateAllocator());
}
void EndMissingDependentProperties(const SValue& sourceName) {
if (!missingDependents_.Empty())
currentError_.AddMember(ValueType(sourceName, GetStateAllocator()).Move(),
missingDependents_, GetStateAllocator());
}
void AddDependencySchemaError(const SValue& sourceName, ISchemaValidator* subvalidator) {
currentError_.AddMember(ValueType(sourceName, GetStateAllocator()).Move(),
static_cast<GenericSchemaValidator*>(subvalidator)->GetError(), GetStateAllocator());
}
bool EndDependencyErrors() {
if (currentError_.ObjectEmpty())
return false;
ValueType error(kObjectType);
error.AddMember(GetErrorsString(), currentError_, GetStateAllocator());
currentError_ = error;
AddCurrentError(SchemaType::GetDependenciesString());
return true;
}
void DisallowedValue() {
currentError_.SetObject();
AddCurrentError(SchemaType::GetEnumString());
}
void StartDisallowedType() {
currentError_.SetArray();
}
void AddExpectedType(const typename SchemaType::ValueType& expectedType) {
currentError_.PushBack(ValueType(expectedType, GetStateAllocator()).Move(), GetStateAllocator());
}
void EndDisallowedType(const typename SchemaType::ValueType& actualType) {
ValueType error(kObjectType);
error.AddMember(GetExpectedString(), currentError_, GetStateAllocator());
error.AddMember(GetActualString(), ValueType(actualType, GetStateAllocator()).Move(), GetStateAllocator());
currentError_ = error;
AddCurrentError(SchemaType::GetTypeString());
}
void NotAllOf(ISchemaValidator** subvalidators, SizeType count) {
for (SizeType i = 0; i < count; ++i) {
MergeError(static_cast<GenericSchemaValidator*>(subvalidators[i])->GetError());
}
}
void NoneOf(ISchemaValidator** subvalidators, SizeType count) {
AddErrorArray(SchemaType::GetAnyOfString(), subvalidators, count);
}
void NotOneOf(ISchemaValidator** subvalidators, SizeType count) {
AddErrorArray(SchemaType::GetOneOfString(), subvalidators, count);
}
void Disallowed() {
currentError_.SetObject();
AddCurrentError(SchemaType::GetNotString());
}
#define RAPIDJSON_STRING_(name, ...) \
static const StringRefType& Get##name##String() {\
static const Ch s[] = { __VA_ARGS__, '\0' };\
static const StringRefType v(s, static_cast<SizeType>(sizeof(s) / sizeof(Ch) - 1)); \
return v;\
}
RAPIDJSON_STRING_(InstanceRef, 'i', 'n', 's', 't', 'a', 'n', 'c', 'e', 'R', 'e', 'f')
RAPIDJSON_STRING_(SchemaRef, 's', 'c', 'h', 'e', 'm', 'a', 'R', 'e', 'f')
RAPIDJSON_STRING_(Expected, 'e', 'x', 'p', 'e', 'c', 't', 'e', 'd')
RAPIDJSON_STRING_(Actual, 'a', 'c', 't', 'u', 'a', 'l')
RAPIDJSON_STRING_(Disallowed, 'd', 'i', 's', 'a', 'l', 'l', 'o', 'w', 'e', 'd')
RAPIDJSON_STRING_(Missing, 'm', 'i', 's', 's', 'i', 'n', 'g')
RAPIDJSON_STRING_(Errors, 'e', 'r', 'r', 'o', 'r', 's')
RAPIDJSON_STRING_(Duplicates, 'd', 'u', 'p', 'l', 'i', 'c', 'a', 't', 'e', 's')
#undef RAPIDJSON_STRING_
#if RAPIDJSON_SCHEMA_VERBOSE
#define RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_() \
RAPIDJSON_MULTILINEMACRO_BEGIN\
*documentStack_.template Push<Ch>() = '\0';\
documentStack_.template Pop<Ch>(1);\
internal::PrintInvalidDocument(documentStack_.template Bottom<Ch>());\
RAPIDJSON_MULTILINEMACRO_END
#else
#define RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_()
#endif
#define RAPIDJSON_SCHEMA_HANDLE_BEGIN_(method, arg1)\
if (!valid_) return false; \
if (!BeginValue() || !CurrentSchema().method arg1) {\
RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_();\
return valid_ = false;\
}
#define RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2)\
for (Context* context = schemaStack_.template Bottom<Context>(); context != schemaStack_.template End<Context>(); context++) {\
if (context->hasher)\
static_cast<HasherType*>(context->hasher)->method arg2;\
if (context->validators)\
for (SizeType i_ = 0; i_ < context->validatorCount; i_++)\
static_cast<GenericSchemaValidator*>(context->validators[i_])->method arg2;\
if (context->patternPropertiesValidators)\
for (SizeType i_ = 0; i_ < context->patternPropertiesValidatorCount; i_++)\
static_cast<GenericSchemaValidator*>(context->patternPropertiesValidators[i_])->method arg2;\
}
#define RAPIDJSON_SCHEMA_HANDLE_END_(method, arg2)\
return valid_ = EndValue() && (!outputHandler_ || outputHandler_->method arg2)
#define RAPIDJSON_SCHEMA_HANDLE_VALUE_(method, arg1, arg2) \
RAPIDJSON_SCHEMA_HANDLE_BEGIN_ (method, arg1);\
RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2);\
RAPIDJSON_SCHEMA_HANDLE_END_ (method, arg2)
bool Null() { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Null, (CurrentContext()), ( )); }
bool Bool(bool b) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Bool, (CurrentContext(), b), (b)); }
bool Int(int i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int, (CurrentContext(), i), (i)); }
bool Uint(unsigned u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint, (CurrentContext(), u), (u)); }
bool Int64(int64_t i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int64, (CurrentContext(), i), (i)); }
bool Uint64(uint64_t u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint64, (CurrentContext(), u), (u)); }
bool Double(double d) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Double, (CurrentContext(), d), (d)); }
bool RawNumber(const Ch* str, SizeType length, bool copy)
{ RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), str, length, copy), (str, length, copy)); }
bool String(const Ch* str, SizeType length, bool copy)
{ RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), str, length, copy), (str, length, copy)); }
bool StartObject() {
RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartObject, (CurrentContext()));
RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartObject, ());
return valid_ = !outputHandler_ || outputHandler_->StartObject();
}
bool Key(const Ch* str, SizeType len, bool copy) {
if (!valid_) return false;
AppendToken(str, len);
if (!CurrentSchema().Key(CurrentContext(), str, len, copy)) return valid_ = false;
RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(Key, (str, len, copy));
return valid_ = !outputHandler_ || outputHandler_->Key(str, len, copy);
}
bool EndObject(SizeType memberCount) {
if (!valid_) return false;
RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndObject, (memberCount));
if (!CurrentSchema().EndObject(CurrentContext(), memberCount)) return valid_ = false;
RAPIDJSON_SCHEMA_HANDLE_END_(EndObject, (memberCount));
}
bool StartArray() {
RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartArray, (CurrentContext()));
RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartArray, ());
return valid_ = !outputHandler_ || outputHandler_->StartArray();
}
bool EndArray(SizeType elementCount) {
if (!valid_) return false;
RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndArray, (elementCount));
if (!CurrentSchema().EndArray(CurrentContext(), elementCount)) return valid_ = false;
RAPIDJSON_SCHEMA_HANDLE_END_(EndArray, (elementCount));
}
#undef RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_
#undef RAPIDJSON_SCHEMA_HANDLE_BEGIN_
#undef RAPIDJSON_SCHEMA_HANDLE_PARALLEL_
#undef RAPIDJSON_SCHEMA_HANDLE_VALUE_
// Implementation of ISchemaStateFactory<SchemaType>
virtual ISchemaValidator* CreateSchemaValidator(const SchemaType& root) {
return new (GetStateAllocator().Malloc(sizeof(GenericSchemaValidator))) GenericSchemaValidator(*schemaDocument_, root, documentStack_.template Bottom<char>(), documentStack_.GetSize(),
#if RAPIDJSON_SCHEMA_VERBOSE
depth_ + 1,
#endif
&GetStateAllocator());
}
virtual void DestroySchemaValidator(ISchemaValidator* validator) {
GenericSchemaValidator* v = static_cast<GenericSchemaValidator*>(validator);
v->~GenericSchemaValidator();
StateAllocator::Free(v);
}
virtual void* CreateHasher() {
return new (GetStateAllocator().Malloc(sizeof(HasherType))) HasherType(&GetStateAllocator());
}
virtual uint64_t GetHashCode(void* hasher) {
return static_cast<HasherType*>(hasher)->GetHashCode();
}
virtual void DestroryHasher(void* hasher) {
HasherType* h = static_cast<HasherType*>(hasher);
h->~HasherType();
StateAllocator::Free(h);
}
virtual void* MallocState(size_t size) {
return GetStateAllocator().Malloc(size);
}
virtual void FreeState(void* p) {
StateAllocator::Free(p);
}
private:
typedef typename SchemaType::Context Context;
typedef GenericValue<UTF8<>, StateAllocator> HashCodeArray;
typedef internal::Hasher<EncodingType, StateAllocator> HasherType;
GenericSchemaValidator(
const SchemaDocumentType& schemaDocument,
const SchemaType& root,
const char* basePath, size_t basePathSize,
#if RAPIDJSON_SCHEMA_VERBOSE
unsigned depth,
#endif
StateAllocator* allocator = 0,
size_t schemaStackCapacity = kDefaultSchemaStackCapacity,
size_t documentStackCapacity = kDefaultDocumentStackCapacity)
:
schemaDocument_(&schemaDocument),
root_(root),
stateAllocator_(allocator),
ownStateAllocator_(0),
schemaStack_(allocator, schemaStackCapacity),
documentStack_(allocator, documentStackCapacity),
outputHandler_(0),
error_(kObjectType),
currentError_(),
missingDependents_(),
valid_(true)
#if RAPIDJSON_SCHEMA_VERBOSE
, depth_(depth)
#endif
{
if (basePath && basePathSize)
memcpy(documentStack_.template Push<char>(basePathSize), basePath, basePathSize);
}
StateAllocator& GetStateAllocator() {
if (!stateAllocator_)
stateAllocator_ = ownStateAllocator_ = RAPIDJSON_NEW(StateAllocator)();
return *stateAllocator_;
}
bool BeginValue() {
if (schemaStack_.Empty())
PushSchema(root_);
else {
if (CurrentContext().inArray)
internal::TokenHelper<internal::Stack<StateAllocator>, Ch>::AppendIndexToken(documentStack_, CurrentContext().arrayElementIndex);
if (!CurrentSchema().BeginValue(CurrentContext()))
return false;
SizeType count = CurrentContext().patternPropertiesSchemaCount;
const SchemaType** sa = CurrentContext().patternPropertiesSchemas;
typename Context::PatternValidatorType patternValidatorType = CurrentContext().valuePatternValidatorType;
bool valueUniqueness = CurrentContext().valueUniqueness;
RAPIDJSON_ASSERT(CurrentContext().valueSchema);
PushSchema(*CurrentContext().valueSchema);
if (count > 0) {
CurrentContext().objectPatternValidatorType = patternValidatorType;
ISchemaValidator**& va = CurrentContext().patternPropertiesValidators;
SizeType& validatorCount = CurrentContext().patternPropertiesValidatorCount;
va = static_cast<ISchemaValidator**>(MallocState(sizeof(ISchemaValidator*) * count));
for (SizeType i = 0; i < count; i++)
va[validatorCount++] = CreateSchemaValidator(*sa[i]);
}
CurrentContext().arrayUniqueness = valueUniqueness;
}
return true;
}
bool EndValue() {
if (!CurrentSchema().EndValue(CurrentContext()))
return false;
#if RAPIDJSON_SCHEMA_VERBOSE
GenericStringBuffer<EncodingType> sb;
schemaDocument_->GetPointer(&CurrentSchema()).Stringify(sb);
*documentStack_.template Push<Ch>() = '\0';
documentStack_.template Pop<Ch>(1);
internal::PrintValidatorPointers(depth_, sb.GetString(), documentStack_.template Bottom<Ch>());
#endif
uint64_t h = CurrentContext().arrayUniqueness ? static_cast<HasherType*>(CurrentContext().hasher)->GetHashCode() : 0;
PopSchema();
if (!schemaStack_.Empty()) {
Context& context = CurrentContext();
if (context.valueUniqueness) {
HashCodeArray* a = static_cast<HashCodeArray*>(context.arrayElementHashCodes);
if (!a)
CurrentContext().arrayElementHashCodes = a = new (GetStateAllocator().Malloc(sizeof(HashCodeArray))) HashCodeArray(kArrayType);
for (typename HashCodeArray::ConstValueIterator itr = a->Begin(); itr != a->End(); ++itr)
if (itr->GetUint64() == h) {
DuplicateItems(static_cast<SizeType>(itr - a->Begin()), a->Size());
RAPIDJSON_INVALID_KEYWORD_RETURN(SchemaType::GetUniqueItemsString());
}
a->PushBack(h, GetStateAllocator());
}
}
// Remove the last token of document pointer
while (!documentStack_.Empty() && *documentStack_.template Pop<Ch>(1) != '/')
;
return true;
}
void AppendToken(const Ch* str, SizeType len) {
documentStack_.template Reserve<Ch>(1 + len * 2); // worst case all characters are escaped as two characters
*documentStack_.template PushUnsafe<Ch>() = '/';
for (SizeType i = 0; i < len; i++) {
if (str[i] == '~') {
*documentStack_.template PushUnsafe<Ch>() = '~';
*documentStack_.template PushUnsafe<Ch>() = '0';
}
else if (str[i] == '/') {
*documentStack_.template PushUnsafe<Ch>() = '~';
*documentStack_.template PushUnsafe<Ch>() = '1';
}
else
*documentStack_.template PushUnsafe<Ch>() = str[i];
}
}
RAPIDJSON_FORCEINLINE void PushSchema(const SchemaType& schema) { new (schemaStack_.template Push<Context>()) Context(*this, *this, &schema); }
RAPIDJSON_FORCEINLINE void PopSchema() {
Context* c = schemaStack_.template Pop<Context>(1);
if (HashCodeArray* a = static_cast<HashCodeArray*>(c->arrayElementHashCodes)) {
a->~HashCodeArray();
StateAllocator::Free(a);
}
c->~Context();
}
void AddErrorLocation(ValueType& result, bool parent) {
GenericStringBuffer<EncodingType> sb;
PointerType instancePointer = GetInvalidDocumentPointer();
((parent && instancePointer.GetTokenCount() > 0)
? PointerType(instancePointer.GetTokens(), instancePointer.GetTokenCount() - 1)
: instancePointer).StringifyUriFragment(sb);
ValueType instanceRef(sb.GetString(), static_cast<SizeType>(sb.GetSize() / sizeof(Ch)),
GetStateAllocator());
result.AddMember(GetInstanceRefString(), instanceRef, GetStateAllocator());
sb.Clear();
memcpy(sb.Push(CurrentSchema().GetURI().GetStringLength()),
CurrentSchema().GetURI().GetString(),
CurrentSchema().GetURI().GetStringLength() * sizeof(Ch));
GetInvalidSchemaPointer().StringifyUriFragment(sb);
ValueType schemaRef(sb.GetString(), static_cast<SizeType>(sb.GetSize() / sizeof(Ch)),
GetStateAllocator());
result.AddMember(GetSchemaRefString(), schemaRef, GetStateAllocator());
}
void AddError(ValueType& keyword, ValueType& error) {
typename ValueType::MemberIterator member = error_.FindMember(keyword);
if (member == error_.MemberEnd())
error_.AddMember(keyword, error, GetStateAllocator());
else {
if (member->value.IsObject()) {
ValueType errors(kArrayType);
errors.PushBack(member->value, GetStateAllocator());
member->value = errors;
}
member->value.PushBack(error, GetStateAllocator());
}
}
void AddCurrentError(const typename SchemaType::ValueType& keyword, bool parent = false) {
AddErrorLocation(currentError_, parent);
AddError(ValueType(keyword, GetStateAllocator(), false).Move(), currentError_);
}
void MergeError(ValueType& other) {
for (typename ValueType::MemberIterator it = other.MemberBegin(), end = other.MemberEnd(); it != end; ++it) {
AddError(it->name, it->value);
}
}
void AddNumberError(const typename SchemaType::ValueType& keyword, ValueType& actual, const SValue& expected,
const typename SchemaType::ValueType& (*exclusive)() = 0) {
currentError_.SetObject();
currentError_.AddMember(GetActualString(), actual, GetStateAllocator());
currentError_.AddMember(GetExpectedString(), ValueType(expected, GetStateAllocator()).Move(), GetStateAllocator());
if (exclusive)
currentError_.AddMember(ValueType(exclusive(), GetStateAllocator()).Move(), true, GetStateAllocator());
AddCurrentError(keyword);
}
void AddErrorArray(const typename SchemaType::ValueType& keyword,
ISchemaValidator** subvalidators, SizeType count) {
ValueType errors(kArrayType);
for (SizeType i = 0; i < count; ++i)
errors.PushBack(static_cast<GenericSchemaValidator*>(subvalidators[i])->GetError(), GetStateAllocator());
currentError_.SetObject();
currentError_.AddMember(GetErrorsString(), errors, GetStateAllocator());
AddCurrentError(keyword);
}
const SchemaType& CurrentSchema() const { return *schemaStack_.template Top<Context>()->schema; }
Context& CurrentContext() { return *schemaStack_.template Top<Context>(); }
const Context& CurrentContext() const { return *schemaStack_.template Top<Context>(); }
static const size_t kDefaultSchemaStackCapacity = 1024;
static const size_t kDefaultDocumentStackCapacity = 256;
const SchemaDocumentType* schemaDocument_;
const SchemaType& root_;
StateAllocator* stateAllocator_;
StateAllocator* ownStateAllocator_;
internal::Stack<StateAllocator> schemaStack_; //!< stack to store the current path of schema (BaseSchemaType *)
internal::Stack<StateAllocator> documentStack_; //!< stack to store the current path of validating document (Ch)
OutputHandler* outputHandler_;
ValueType error_;
ValueType currentError_;
ValueType missingDependents_;
bool valid_;
#if RAPIDJSON_SCHEMA_VERBOSE
unsigned depth_;
#endif
};
typedef GenericSchemaValidator<SchemaDocument> SchemaValidator;
///////////////////////////////////////////////////////////////////////////////
// SchemaValidatingReader
//! A helper class for parsing with validation.
/*!
This helper class is a functor, designed as a parameter of \ref GenericDocument::Populate().
\tparam parseFlags Combination of \ref ParseFlag.
\tparam InputStream Type of input stream, implementing Stream concept.
\tparam SourceEncoding Encoding of the input stream.
\tparam SchemaDocumentType Type of schema document.
\tparam StackAllocator Allocator type for stack.
*/
template <
unsigned parseFlags,
typename InputStream,
typename SourceEncoding,
typename SchemaDocumentType = SchemaDocument,
typename StackAllocator = CrtAllocator>
class SchemaValidatingReader {
public:
typedef typename SchemaDocumentType::PointerType PointerType;
typedef typename InputStream::Ch Ch;
typedef GenericValue<SourceEncoding, StackAllocator> ValueType;
//! Constructor
/*!
\param is Input stream.
\param sd Schema document.
*/
SchemaValidatingReader(InputStream& is, const SchemaDocumentType& sd) : is_(is), sd_(sd), invalidSchemaKeyword_(), error_(kObjectType), isValid_(true) {}
template <typename Handler>
bool operator()(Handler& handler) {
GenericReader<SourceEncoding, typename SchemaDocumentType::EncodingType, StackAllocator> reader;
GenericSchemaValidator<SchemaDocumentType, Handler> validator(sd_, handler);
parseResult_ = reader.template Parse<parseFlags>(is_, validator);
isValid_ = validator.IsValid();
if (isValid_) {
invalidSchemaPointer_ = PointerType();
invalidSchemaKeyword_ = 0;
invalidDocumentPointer_ = PointerType();
error_.SetObject();
}
else {
invalidSchemaPointer_ = validator.GetInvalidSchemaPointer();
invalidSchemaKeyword_ = validator.GetInvalidSchemaKeyword();
invalidDocumentPointer_ = validator.GetInvalidDocumentPointer();
error_.CopyFrom(validator.GetError(), allocator_);
}
return parseResult_;
}
const ParseResult& GetParseResult() const { return parseResult_; }
bool IsValid() const { return isValid_; }
const PointerType& GetInvalidSchemaPointer() const { return invalidSchemaPointer_; }
const Ch* GetInvalidSchemaKeyword() const { return invalidSchemaKeyword_; }
const PointerType& GetInvalidDocumentPointer() const { return invalidDocumentPointer_; }
const ValueType& GetError() const { return error_; }
private:
InputStream& is_;
const SchemaDocumentType& sd_;
ParseResult parseResult_;
PointerType invalidSchemaPointer_;
const Ch* invalidSchemaKeyword_;
PointerType invalidDocumentPointer_;
StackAllocator allocator_;
ValueType error_;
bool isValid_;
};
RAPIDJSON_NAMESPACE_END
RAPIDJSON_DIAG_POP
#endif // RAPIDJSON_SCHEMA_H_
| 103,633 | schema | h | en | c | code | {"qsc_code_num_words": 8987, "qsc_code_num_chars": 103633.0, "qsc_code_mean_word_length": 7.06898854, "qsc_code_frac_words_unique": 0.09213308, "qsc_code_frac_chars_top_2grams": 0.01605566, "qsc_code_frac_chars_top_3grams": 0.01629177, "qsc_code_frac_chars_top_4grams": 0.01917235, "qsc_code_frac_chars_dupe_5grams": 0.36377088, "qsc_code_frac_chars_dupe_6grams": 0.30046121, "qsc_code_frac_chars_dupe_7grams": 0.2357506, "qsc_code_frac_chars_dupe_8grams": 0.18238915, "qsc_code_frac_chars_dupe_9grams": 0.17262982, "qsc_code_frac_chars_dupe_10grams": 0.14920745, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00687361, "qsc_code_frac_chars_whitespace": 0.25175378, "qsc_code_size_file_byte": 103633.0, "qsc_code_num_lines": 2496.0, "qsc_code_num_chars_line_max": 193.0, "qsc_code_num_chars_line_mean": 41.51963141, "qsc_code_frac_chars_alphabet": 0.81240086, "qsc_code_frac_chars_comments": 0.06916716, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.2141083, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00605401, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00041466, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.00248385, "qsc_codec_frac_lines_func_ratio": 0.12518629, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.00099354, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.16939891, "qsc_codec_frac_lines_print": 0.00298063, "qsc_codec_frac_lines_preprocessor_directives": null} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/rapidjson/prettywriter.h | // Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// 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 RAPIDJSON_PRETTYWRITER_H_
#define RAPIDJSON_PRETTYWRITER_H_
#include "writer.h"
#ifdef __GNUC__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(effc++)
#endif
#if defined(__clang__)
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(c++98-compat)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Combination of PrettyWriter format flags.
/*! \see PrettyWriter::SetFormatOptions
*/
enum PrettyFormatOptions {
kFormatDefault = 0, //!< Default pretty formatting.
kFormatSingleLineArray = 1 //!< Format arrays on a single line.
};
//! Writer with indentation and spacing.
/*!
\tparam OutputStream Type of output os.
\tparam SourceEncoding Encoding of source string.
\tparam TargetEncoding Encoding of output stream.
\tparam StackAllocator Type of allocator for allocating memory of stack.
*/
template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags>
class PrettyWriter : public Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator, writeFlags> {
public:
typedef Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator, writeFlags> Base;
typedef typename Base::Ch Ch;
//! Constructor
/*! \param os Output stream.
\param allocator User supplied allocator. If it is null, it will create a private one.
\param levelDepth Initial capacity of stack.
*/
explicit PrettyWriter(OutputStream& os, StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) :
Base(os, allocator, levelDepth), indentChar_(' '), indentCharCount_(4), formatOptions_(kFormatDefault) {}
explicit PrettyWriter(StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) :
Base(allocator, levelDepth), indentChar_(' '), indentCharCount_(4), formatOptions_(kFormatDefault) {}
#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
PrettyWriter(PrettyWriter&& rhs) :
Base(std::forward<PrettyWriter>(rhs)), indentChar_(rhs.indentChar_), indentCharCount_(rhs.indentCharCount_), formatOptions_(rhs.formatOptions_) {}
#endif
//! Set custom indentation.
/*! \param indentChar Character for indentation. Must be whitespace character (' ', '\\t', '\\n', '\\r').
\param indentCharCount Number of indent characters for each indentation level.
\note The default indentation is 4 spaces.
*/
PrettyWriter& SetIndent(Ch indentChar, unsigned indentCharCount) {
RAPIDJSON_ASSERT(indentChar == ' ' || indentChar == '\t' || indentChar == '\n' || indentChar == '\r');
indentChar_ = indentChar;
indentCharCount_ = indentCharCount;
return *this;
}
//! Set pretty writer formatting options.
/*! \param options Formatting options.
*/
PrettyWriter& SetFormatOptions(PrettyFormatOptions options) {
formatOptions_ = options;
return *this;
}
/*! @name Implementation of Handler
\see Handler
*/
//@{
bool Null() { PrettyPrefix(kNullType); return Base::EndValue(Base::WriteNull()); }
bool Bool(bool b) { PrettyPrefix(b ? kTrueType : kFalseType); return Base::EndValue(Base::WriteBool(b)); }
bool Int(int i) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteInt(i)); }
bool Uint(unsigned u) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteUint(u)); }
bool Int64(int64_t i64) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteInt64(i64)); }
bool Uint64(uint64_t u64) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteUint64(u64)); }
bool Double(double d) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteDouble(d)); }
bool RawNumber(const Ch* str, SizeType length, bool copy = false) {
RAPIDJSON_ASSERT(str != 0);
(void)copy;
PrettyPrefix(kNumberType);
return Base::EndValue(Base::WriteString(str, length));
}
bool String(const Ch* str, SizeType length, bool copy = false) {
RAPIDJSON_ASSERT(str != 0);
(void)copy;
PrettyPrefix(kStringType);
return Base::EndValue(Base::WriteString(str, length));
}
#if RAPIDJSON_HAS_STDSTRING
bool String(const std::basic_string<Ch>& str) {
return String(str.data(), SizeType(str.size()));
}
#endif
bool StartObject() {
PrettyPrefix(kObjectType);
new (Base::level_stack_.template Push<typename Base::Level>()) typename Base::Level(false);
return Base::WriteStartObject();
}
bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); }
#if RAPIDJSON_HAS_STDSTRING
bool Key(const std::basic_string<Ch>& str) {
return Key(str.data(), SizeType(str.size()));
}
#endif
bool EndObject(SizeType memberCount = 0) {
(void)memberCount;
RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); // not inside an Object
RAPIDJSON_ASSERT(!Base::level_stack_.template Top<typename Base::Level>()->inArray); // currently inside an Array, not Object
RAPIDJSON_ASSERT(0 == Base::level_stack_.template Top<typename Base::Level>()->valueCount % 2); // Object has a Key without a Value
bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
if (!empty) {
Base::os_->Put('\n');
WriteIndent();
}
bool ret = Base::EndValue(Base::WriteEndObject());
(void)ret;
RAPIDJSON_ASSERT(ret == true);
if (Base::level_stack_.Empty()) // end of json text
Base::Flush();
return true;
}
bool StartArray() {
PrettyPrefix(kArrayType);
new (Base::level_stack_.template Push<typename Base::Level>()) typename Base::Level(true);
return Base::WriteStartArray();
}
bool EndArray(SizeType memberCount = 0) {
(void)memberCount;
RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level));
RAPIDJSON_ASSERT(Base::level_stack_.template Top<typename Base::Level>()->inArray);
bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
if (!empty && !(formatOptions_ & kFormatSingleLineArray)) {
Base::os_->Put('\n');
WriteIndent();
}
bool ret = Base::EndValue(Base::WriteEndArray());
(void)ret;
RAPIDJSON_ASSERT(ret == true);
if (Base::level_stack_.Empty()) // end of json text
Base::Flush();
return true;
}
//@}
/*! @name Convenience extensions */
//@{
//! Simpler but slower overload.
bool String(const Ch* str) { return String(str, internal::StrLen(str)); }
bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); }
//@}
//! Write a raw JSON value.
/*!
For user to write a stringified JSON as a value.
\param json A well-formed JSON value. It should not contain null character within [0, length - 1] range.
\param length Length of the json.
\param type Type of the root of json.
\note When using PrettyWriter::RawValue(), the result json may not be indented correctly.
*/
bool RawValue(const Ch* json, size_t length, Type type) {
RAPIDJSON_ASSERT(json != 0);
PrettyPrefix(type);
return Base::EndValue(Base::WriteRawValue(json, length));
}
protected:
void PrettyPrefix(Type type) {
(void)type;
if (Base::level_stack_.GetSize() != 0) { // this value is not at root
typename Base::Level* level = Base::level_stack_.template Top<typename Base::Level>();
if (level->inArray) {
if (level->valueCount > 0) {
Base::os_->Put(','); // add comma if it is not the first element in array
if (formatOptions_ & kFormatSingleLineArray)
Base::os_->Put(' ');
}
if (!(formatOptions_ & kFormatSingleLineArray)) {
Base::os_->Put('\n');
WriteIndent();
}
}
else { // in object
if (level->valueCount > 0) {
if (level->valueCount % 2 == 0) {
Base::os_->Put(',');
Base::os_->Put('\n');
}
else {
Base::os_->Put(':');
Base::os_->Put(' ');
}
}
else
Base::os_->Put('\n');
if (level->valueCount % 2 == 0)
WriteIndent();
}
if (!level->inArray && level->valueCount % 2 == 0)
RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name
level->valueCount++;
}
else {
RAPIDJSON_ASSERT(!Base::hasRoot_); // Should only has one and only one root.
Base::hasRoot_ = true;
}
}
void WriteIndent() {
size_t count = (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) * indentCharCount_;
PutN(*Base::os_, static_cast<typename OutputStream::Ch>(indentChar_), count);
}
Ch indentChar_;
unsigned indentCharCount_;
PrettyFormatOptions formatOptions_;
private:
// Prohibit copy constructor & assignment operator.
PrettyWriter(const PrettyWriter&);
PrettyWriter& operator=(const PrettyWriter&);
};
RAPIDJSON_NAMESPACE_END
#if defined(__clang__)
RAPIDJSON_DIAG_POP
#endif
#ifdef __GNUC__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_RAPIDJSON_H_
| 10,539 | prettywriter | h | en | c | code | {"qsc_code_num_words": 1131, "qsc_code_num_chars": 10539.0, "qsc_code_mean_word_length": 5.76746242, "qsc_code_frac_words_unique": 0.27055703, "qsc_code_frac_chars_top_2grams": 0.03863253, "qsc_code_frac_chars_top_3grams": 0.03004752, "qsc_code_frac_chars_top_4grams": 0.03372681, "qsc_code_frac_chars_dupe_5grams": 0.37881343, "qsc_code_frac_chars_dupe_6grams": 0.34462671, "qsc_code_frac_chars_dupe_7grams": 0.26398896, "qsc_code_frac_chars_dupe_8grams": 0.19638203, "qsc_code_frac_chars_dupe_9grams": 0.17108692, "qsc_code_frac_chars_dupe_10grams": 0.15115744, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00770786, "qsc_code_frac_chars_whitespace": 0.24907486, "qsc_code_size_file_byte": 10539.0, "qsc_code_num_lines": 277.0, "qsc_code_num_chars_line_max": 182.0, "qsc_code_num_chars_line_mean": 38.04693141, "qsc_code_frac_chars_alphabet": 0.81652767, "qsc_code_frac_chars_comments": 0.25400892, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.30357143, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00407021, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.06547619, "qsc_codec_frac_lines_func_ratio": 0.19642857, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.2202381, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/rapidjson/encodedstream.h | // Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// 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 RAPIDJSON_ENCODEDSTREAM_H_
#define RAPIDJSON_ENCODEDSTREAM_H_
#include "stream.h"
#include "memorystream.h"
#ifdef __GNUC__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(effc++)
#endif
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(padded)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Input byte stream wrapper with a statically bound encoding.
/*!
\tparam Encoding The interpretation of encoding of the stream. Either UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE.
\tparam InputByteStream Type of input byte stream. For example, FileReadStream.
*/
template <typename Encoding, typename InputByteStream>
class EncodedInputStream {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
public:
typedef typename Encoding::Ch Ch;
EncodedInputStream(InputByteStream& is) : is_(is) {
current_ = Encoding::TakeBOM(is_);
}
Ch Peek() const { return current_; }
Ch Take() { Ch c = current_; current_ = Encoding::Take(is_); return c; }
size_t Tell() const { return is_.Tell(); }
// Not implemented
void Put(Ch) { RAPIDJSON_ASSERT(false); }
void Flush() { RAPIDJSON_ASSERT(false); }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
private:
EncodedInputStream(const EncodedInputStream&);
EncodedInputStream& operator=(const EncodedInputStream&);
InputByteStream& is_;
Ch current_;
};
//! Specialized for UTF8 MemoryStream.
template <>
class EncodedInputStream<UTF8<>, MemoryStream> {
public:
typedef UTF8<>::Ch Ch;
EncodedInputStream(MemoryStream& is) : is_(is) {
if (static_cast<unsigned char>(is_.Peek()) == 0xEFu) is_.Take();
if (static_cast<unsigned char>(is_.Peek()) == 0xBBu) is_.Take();
if (static_cast<unsigned char>(is_.Peek()) == 0xBFu) is_.Take();
}
Ch Peek() const { return is_.Peek(); }
Ch Take() { return is_.Take(); }
size_t Tell() const { return is_.Tell(); }
// Not implemented
void Put(Ch) {}
void Flush() {}
Ch* PutBegin() { return 0; }
size_t PutEnd(Ch*) { return 0; }
MemoryStream& is_;
private:
EncodedInputStream(const EncodedInputStream&);
EncodedInputStream& operator=(const EncodedInputStream&);
};
//! Output byte stream wrapper with statically bound encoding.
/*!
\tparam Encoding The interpretation of encoding of the stream. Either UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE.
\tparam OutputByteStream Type of input byte stream. For example, FileWriteStream.
*/
template <typename Encoding, typename OutputByteStream>
class EncodedOutputStream {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
public:
typedef typename Encoding::Ch Ch;
EncodedOutputStream(OutputByteStream& os, bool putBOM = true) : os_(os) {
if (putBOM)
Encoding::PutBOM(os_);
}
void Put(Ch c) { Encoding::Put(os_, c); }
void Flush() { os_.Flush(); }
// Not implemented
Ch Peek() const { RAPIDJSON_ASSERT(false); return 0;}
Ch Take() { RAPIDJSON_ASSERT(false); return 0;}
size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
private:
EncodedOutputStream(const EncodedOutputStream&);
EncodedOutputStream& operator=(const EncodedOutputStream&);
OutputByteStream& os_;
};
#define RAPIDJSON_ENCODINGS_FUNC(x) UTF8<Ch>::x, UTF16LE<Ch>::x, UTF16BE<Ch>::x, UTF32LE<Ch>::x, UTF32BE<Ch>::x
//! Input stream wrapper with dynamically bound encoding and automatic encoding detection.
/*!
\tparam CharType Type of character for reading.
\tparam InputByteStream type of input byte stream to be wrapped.
*/
template <typename CharType, typename InputByteStream>
class AutoUTFInputStream {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
public:
typedef CharType Ch;
//! Constructor.
/*!
\param is input stream to be wrapped.
\param type UTF encoding type if it is not detected from the stream.
*/
AutoUTFInputStream(InputByteStream& is, UTFType type = kUTF8) : is_(&is), type_(type), hasBOM_(false) {
RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE);
DetectType();
static const TakeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Take) };
takeFunc_ = f[type_];
current_ = takeFunc_(*is_);
}
UTFType GetType() const { return type_; }
bool HasBOM() const { return hasBOM_; }
Ch Peek() const { return current_; }
Ch Take() { Ch c = current_; current_ = takeFunc_(*is_); return c; }
size_t Tell() const { return is_->Tell(); }
// Not implemented
void Put(Ch) { RAPIDJSON_ASSERT(false); }
void Flush() { RAPIDJSON_ASSERT(false); }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
private:
AutoUTFInputStream(const AutoUTFInputStream&);
AutoUTFInputStream& operator=(const AutoUTFInputStream&);
// Detect encoding type with BOM or RFC 4627
void DetectType() {
// BOM (Byte Order Mark):
// 00 00 FE FF UTF-32BE
// FF FE 00 00 UTF-32LE
// FE FF UTF-16BE
// FF FE UTF-16LE
// EF BB BF UTF-8
const unsigned char* c = reinterpret_cast<const unsigned char *>(is_->Peek4());
if (!c)
return;
unsigned bom = static_cast<unsigned>(c[0] | (c[1] << 8) | (c[2] << 16) | (c[3] << 24));
hasBOM_ = false;
if (bom == 0xFFFE0000) { type_ = kUTF32BE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); }
else if (bom == 0x0000FEFF) { type_ = kUTF32LE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); }
else if ((bom & 0xFFFF) == 0xFFFE) { type_ = kUTF16BE; hasBOM_ = true; is_->Take(); is_->Take(); }
else if ((bom & 0xFFFF) == 0xFEFF) { type_ = kUTF16LE; hasBOM_ = true; is_->Take(); is_->Take(); }
else if ((bom & 0xFFFFFF) == 0xBFBBEF) { type_ = kUTF8; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); }
// RFC 4627: Section 3
// "Since the first two characters of a JSON text will always be ASCII
// characters [RFC0020], it is possible to determine whether an octet
// stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking
// at the pattern of nulls in the first four octets."
// 00 00 00 xx UTF-32BE
// 00 xx 00 xx UTF-16BE
// xx 00 00 00 UTF-32LE
// xx 00 xx 00 UTF-16LE
// xx xx xx xx UTF-8
if (!hasBOM_) {
int pattern = (c[0] ? 1 : 0) | (c[1] ? 2 : 0) | (c[2] ? 4 : 0) | (c[3] ? 8 : 0);
switch (pattern) {
case 0x08: type_ = kUTF32BE; break;
case 0x0A: type_ = kUTF16BE; break;
case 0x01: type_ = kUTF32LE; break;
case 0x05: type_ = kUTF16LE; break;
case 0x0F: type_ = kUTF8; break;
default: break; // Use type defined by user.
}
}
// Runtime check whether the size of character type is sufficient. It only perform checks with assertion.
if (type_ == kUTF16LE || type_ == kUTF16BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 2);
if (type_ == kUTF32LE || type_ == kUTF32BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 4);
}
typedef Ch (*TakeFunc)(InputByteStream& is);
InputByteStream* is_;
UTFType type_;
Ch current_;
TakeFunc takeFunc_;
bool hasBOM_;
};
//! Output stream wrapper with dynamically bound encoding and automatic encoding detection.
/*!
\tparam CharType Type of character for writing.
\tparam OutputByteStream type of output byte stream to be wrapped.
*/
template <typename CharType, typename OutputByteStream>
class AutoUTFOutputStream {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
public:
typedef CharType Ch;
//! Constructor.
/*!
\param os output stream to be wrapped.
\param type UTF encoding type.
\param putBOM Whether to write BOM at the beginning of the stream.
*/
AutoUTFOutputStream(OutputByteStream& os, UTFType type, bool putBOM) : os_(&os), type_(type) {
RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE);
// Runtime check whether the size of character type is sufficient. It only perform checks with assertion.
if (type_ == kUTF16LE || type_ == kUTF16BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 2);
if (type_ == kUTF32LE || type_ == kUTF32BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 4);
static const PutFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Put) };
putFunc_ = f[type_];
if (putBOM)
PutBOM();
}
UTFType GetType() const { return type_; }
void Put(Ch c) { putFunc_(*os_, c); }
void Flush() { os_->Flush(); }
// Not implemented
Ch Peek() const { RAPIDJSON_ASSERT(false); return 0;}
Ch Take() { RAPIDJSON_ASSERT(false); return 0;}
size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
private:
AutoUTFOutputStream(const AutoUTFOutputStream&);
AutoUTFOutputStream& operator=(const AutoUTFOutputStream&);
void PutBOM() {
typedef void (*PutBOMFunc)(OutputByteStream&);
static const PutBOMFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(PutBOM) };
f[type_](*os_);
}
typedef void (*PutFunc)(OutputByteStream&, Ch);
OutputByteStream* os_;
UTFType type_;
PutFunc putFunc_;
};
#undef RAPIDJSON_ENCODINGS_FUNC
RAPIDJSON_NAMESPACE_END
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#ifdef __GNUC__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_FILESTREAM_H_
| 10,681 | encodedstream | h | en | c | code | {"qsc_code_num_words": 1276, "qsc_code_num_chars": 10681.0, "qsc_code_mean_word_length": 5.26959248, "qsc_code_frac_words_unique": 0.21159875, "qsc_code_frac_chars_top_2grams": 0.05353956, "qsc_code_frac_chars_top_3grams": 0.05353956, "qsc_code_frac_chars_top_4grams": 0.05413444, "qsc_code_frac_chars_dupe_5grams": 0.4674301, "qsc_code_frac_chars_dupe_6grams": 0.45880428, "qsc_code_frac_chars_dupe_7grams": 0.43530637, "qsc_code_frac_chars_dupe_8grams": 0.41463415, "qsc_code_frac_chars_dupe_9grams": 0.36719215, "qsc_code_frac_chars_dupe_10grams": 0.31930399, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02676607, "qsc_code_frac_chars_whitespace": 0.23396686, "qsc_code_size_file_byte": 10681.0, "qsc_code_num_lines": 299.0, "qsc_code_num_chars_line_max": 138.0, "qsc_code_num_chars_line_mean": 35.72240803, "qsc_code_frac_chars_alphabet": 0.79503789, "qsc_code_frac_chars_comments": 0.2844303, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.43181818, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00287845, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.01046709, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.15909091, "qsc_codec_frac_lines_func_ratio": 0.24431818, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.28977273, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/rapidjson/rapidjson.h | // Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// 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 RAPIDJSON_RAPIDJSON_H_
#define RAPIDJSON_RAPIDJSON_H_
/*!\file rapidjson.h
\brief common definitions and configuration
\see RAPIDJSON_CONFIG
*/
/*! \defgroup RAPIDJSON_CONFIG RapidJSON configuration
\brief Configuration macros for library features
Some RapidJSON features are configurable to adapt the library to a wide
variety of platforms, environments and usage scenarios. Most of the
features can be configured in terms of overridden or predefined
preprocessor macros at compile-time.
Some additional customization is available in the \ref RAPIDJSON_ERRORS APIs.
\note These macros should be given on the compiler command-line
(where applicable) to avoid inconsistent values when compiling
different translation units of a single application.
*/
#include <cstdlib> // malloc(), realloc(), free(), size_t
#include <cstring> // memset(), memcpy(), memmove(), memcmp()
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_VERSION_STRING
//
// ALWAYS synchronize the following 3 macros with corresponding variables in /CMakeLists.txt.
//
//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
// token stringification
#define RAPIDJSON_STRINGIFY(x) RAPIDJSON_DO_STRINGIFY(x)
#define RAPIDJSON_DO_STRINGIFY(x) #x
// token concatenation
#define RAPIDJSON_JOIN(X, Y) RAPIDJSON_DO_JOIN(X, Y)
#define RAPIDJSON_DO_JOIN(X, Y) RAPIDJSON_DO_JOIN2(X, Y)
#define RAPIDJSON_DO_JOIN2(X, Y) X##Y
//!@endcond
/*! \def RAPIDJSON_MAJOR_VERSION
\ingroup RAPIDJSON_CONFIG
\brief Major version of RapidJSON in integer.
*/
/*! \def RAPIDJSON_MINOR_VERSION
\ingroup RAPIDJSON_CONFIG
\brief Minor version of RapidJSON in integer.
*/
/*! \def RAPIDJSON_PATCH_VERSION
\ingroup RAPIDJSON_CONFIG
\brief Patch version of RapidJSON in integer.
*/
/*! \def RAPIDJSON_VERSION_STRING
\ingroup RAPIDJSON_CONFIG
\brief Version of RapidJSON in "<major>.<minor>.<patch>" string format.
*/
#define RAPIDJSON_MAJOR_VERSION 1
#define RAPIDJSON_MINOR_VERSION 1
#define RAPIDJSON_PATCH_VERSION 0
#define RAPIDJSON_VERSION_STRING \
RAPIDJSON_STRINGIFY(RAPIDJSON_MAJOR_VERSION.RAPIDJSON_MINOR_VERSION.RAPIDJSON_PATCH_VERSION)
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_NAMESPACE_(BEGIN|END)
/*! \def RAPIDJSON_NAMESPACE
\ingroup RAPIDJSON_CONFIG
\brief provide custom rapidjson namespace
In order to avoid symbol clashes and/or "One Definition Rule" errors
between multiple inclusions of (different versions of) RapidJSON in
a single binary, users can customize the name of the main RapidJSON
namespace.
In case of a single nesting level, defining \c RAPIDJSON_NAMESPACE
to a custom name (e.g. \c MyRapidJSON) is sufficient. If multiple
levels are needed, both \ref RAPIDJSON_NAMESPACE_BEGIN and \ref
RAPIDJSON_NAMESPACE_END need to be defined as well:
\code
// in some .cpp file
#define RAPIDJSON_NAMESPACE my::rapidjson
#define RAPIDJSON_NAMESPACE_BEGIN namespace my { namespace rapidjson {
#define RAPIDJSON_NAMESPACE_END } }
#include "rapidjson/..."
\endcode
\see rapidjson
*/
/*! \def RAPIDJSON_NAMESPACE_BEGIN
\ingroup RAPIDJSON_CONFIG
\brief provide custom rapidjson namespace (opening expression)
\see RAPIDJSON_NAMESPACE
*/
/*! \def RAPIDJSON_NAMESPACE_END
\ingroup RAPIDJSON_CONFIG
\brief provide custom rapidjson namespace (closing expression)
\see RAPIDJSON_NAMESPACE
*/
#ifndef RAPIDJSON_NAMESPACE
#define RAPIDJSON_NAMESPACE rapidjson
#endif
#ifndef RAPIDJSON_NAMESPACE_BEGIN
#define RAPIDJSON_NAMESPACE_BEGIN namespace RAPIDJSON_NAMESPACE {
#endif
#ifndef RAPIDJSON_NAMESPACE_END
#define RAPIDJSON_NAMESPACE_END }
#endif
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_HAS_STDSTRING
#ifndef RAPIDJSON_HAS_STDSTRING
#ifdef RAPIDJSON_DOXYGEN_RUNNING
#define RAPIDJSON_HAS_STDSTRING 1 // force generation of documentation
#else
#define RAPIDJSON_HAS_STDSTRING 0 // no std::string support by default
#endif
/*! \def RAPIDJSON_HAS_STDSTRING
\ingroup RAPIDJSON_CONFIG
\brief Enable RapidJSON support for \c std::string
By defining this preprocessor symbol to \c 1, several convenience functions for using
\ref rapidjson::GenericValue with \c std::string are enabled, especially
for construction and comparison.
\hideinitializer
*/
#endif // !defined(RAPIDJSON_HAS_STDSTRING)
#if RAPIDJSON_HAS_STDSTRING
#include <string>
#endif // RAPIDJSON_HAS_STDSTRING
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_NO_INT64DEFINE
/*! \def RAPIDJSON_NO_INT64DEFINE
\ingroup RAPIDJSON_CONFIG
\brief Use external 64-bit integer types.
RapidJSON requires the 64-bit integer types \c int64_t and \c uint64_t types
to be available at global scope.
If users have their own definition, define RAPIDJSON_NO_INT64DEFINE to
prevent RapidJSON from defining its own types.
*/
#ifndef RAPIDJSON_NO_INT64DEFINE
//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
#if defined(_MSC_VER) && (_MSC_VER < 1800) // Visual Studio 2013
#include "msinttypes/stdint.h"
#include "msinttypes/inttypes.h"
#else
// Other compilers should have this.
#include <stdint.h>
#include <inttypes.h>
#endif
//!@endcond
#ifdef RAPIDJSON_DOXYGEN_RUNNING
#define RAPIDJSON_NO_INT64DEFINE
#endif
#endif // RAPIDJSON_NO_INT64TYPEDEF
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_FORCEINLINE
#ifndef RAPIDJSON_FORCEINLINE
//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
#if defined(_MSC_VER) && defined(NDEBUG)
#define RAPIDJSON_FORCEINLINE __forceinline
#elif defined(__GNUC__) && __GNUC__ >= 4 && defined(NDEBUG)
#define RAPIDJSON_FORCEINLINE __attribute__((always_inline))
#else
#define RAPIDJSON_FORCEINLINE
#endif
//!@endcond
#endif // RAPIDJSON_FORCEINLINE
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_ENDIAN
#define RAPIDJSON_LITTLEENDIAN 0 //!< Little endian machine
#define RAPIDJSON_BIGENDIAN 1 //!< Big endian machine
//! Endianness of the machine.
/*!
\def RAPIDJSON_ENDIAN
\ingroup RAPIDJSON_CONFIG
GCC 4.6 provided macro for detecting endianness of the target machine. But other
compilers may not have this. User can define RAPIDJSON_ENDIAN to either
\ref RAPIDJSON_LITTLEENDIAN or \ref RAPIDJSON_BIGENDIAN.
Default detection implemented with reference to
\li https://gcc.gnu.org/onlinedocs/gcc-4.6.0/cpp/Common-Predefined-Macros.html
\li http://www.boost.org/doc/libs/1_42_0/boost/detail/endian.hpp
*/
#ifndef RAPIDJSON_ENDIAN
// Detect with GCC 4.6's macro
# ifdef __BYTE_ORDER__
# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
# elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
# else
# error Unknown machine endianness detected. User needs to define RAPIDJSON_ENDIAN.
# endif // __BYTE_ORDER__
// Detect with GLIBC's endian.h
# elif defined(__GLIBC__)
# include <endian.h>
# if (__BYTE_ORDER == __LITTLE_ENDIAN)
# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
# elif (__BYTE_ORDER == __BIG_ENDIAN)
# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
# else
# error Unknown machine endianness detected. User needs to define RAPIDJSON_ENDIAN.
# endif // __GLIBC__
// Detect with _LITTLE_ENDIAN and _BIG_ENDIAN macro
# elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)
# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
# elif defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN)
# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
// Detect with architecture macros
# elif defined(__sparc) || defined(__sparc__) || defined(_POWER) || defined(__powerpc__) || defined(__ppc__) || defined(__hpux) || defined(__hppa) || defined(_MIPSEB) || defined(_POWER) || defined(__s390__)
# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
# elif defined(__i386__) || defined(__alpha__) || defined(__ia64) || defined(__ia64__) || defined(_M_IX86) || defined(_M_IA64) || defined(_M_ALPHA) || defined(__amd64) || defined(__amd64__) || defined(_M_AMD64) || defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || defined(__bfin__)
# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
# elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64))
# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
# elif defined(RAPIDJSON_DOXYGEN_RUNNING)
# define RAPIDJSON_ENDIAN
# else
# error Unknown machine endianness detected. User needs to define RAPIDJSON_ENDIAN.
# endif
#endif // RAPIDJSON_ENDIAN
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_64BIT
//! Whether using 64-bit architecture
#ifndef RAPIDJSON_64BIT
#if defined(__LP64__) || (defined(__x86_64__) && defined(__ILP32__)) || defined(_WIN64) || defined(__EMSCRIPTEN__)
#define RAPIDJSON_64BIT 1
#else
#define RAPIDJSON_64BIT 0
#endif
#endif // RAPIDJSON_64BIT
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_ALIGN
//! Data alignment of the machine.
/*! \ingroup RAPIDJSON_CONFIG
\param x pointer to align
Some machines require strict data alignment. The default is 8 bytes.
User can customize by defining the RAPIDJSON_ALIGN function macro.
*/
#ifndef RAPIDJSON_ALIGN
#define RAPIDJSON_ALIGN(x) (((x) + static_cast<size_t>(7u)) & ~static_cast<size_t>(7u))
#endif
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_UINT64_C2
//! Construct a 64-bit literal by a pair of 32-bit integer.
/*!
64-bit literal with or without ULL suffix is prone to compiler warnings.
UINT64_C() is C macro which cause compilation problems.
Use this macro to define 64-bit constants by a pair of 32-bit integer.
*/
#ifndef RAPIDJSON_UINT64_C2
#define RAPIDJSON_UINT64_C2(high32, low32) ((static_cast<uint64_t>(high32) << 32) | static_cast<uint64_t>(low32))
#endif
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_48BITPOINTER_OPTIMIZATION
//! Use only lower 48-bit address for some pointers.
/*!
\ingroup RAPIDJSON_CONFIG
This optimization uses the fact that current X86-64 architecture only implement lower 48-bit virtual address.
The higher 16-bit can be used for storing other data.
\c GenericValue uses this optimization to reduce its size form 24 bytes to 16 bytes in 64-bit architecture.
*/
#ifndef RAPIDJSON_48BITPOINTER_OPTIMIZATION
#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64)
#define RAPIDJSON_48BITPOINTER_OPTIMIZATION 1
#else
#define RAPIDJSON_48BITPOINTER_OPTIMIZATION 0
#endif
#endif // RAPIDJSON_48BITPOINTER_OPTIMIZATION
#if RAPIDJSON_48BITPOINTER_OPTIMIZATION == 1
#if RAPIDJSON_64BIT != 1
#error RAPIDJSON_48BITPOINTER_OPTIMIZATION can only be set to 1 when RAPIDJSON_64BIT=1
#endif
#define RAPIDJSON_SETPOINTER(type, p, x) (p = reinterpret_cast<type *>((reinterpret_cast<uintptr_t>(p) & static_cast<uintptr_t>(RAPIDJSON_UINT64_C2(0xFFFF0000, 0x00000000))) | reinterpret_cast<uintptr_t>(reinterpret_cast<const void*>(x))))
#define RAPIDJSON_GETPOINTER(type, p) (reinterpret_cast<type *>(reinterpret_cast<uintptr_t>(p) & static_cast<uintptr_t>(RAPIDJSON_UINT64_C2(0x0000FFFF, 0xFFFFFFFF))))
#else
#define RAPIDJSON_SETPOINTER(type, p, x) (p = (x))
#define RAPIDJSON_GETPOINTER(type, p) (p)
#endif
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_SSE2/RAPIDJSON_SSE42/RAPIDJSON_NEON/RAPIDJSON_SIMD
/*! \def RAPIDJSON_SIMD
\ingroup RAPIDJSON_CONFIG
\brief Enable SSE2/SSE4.2/Neon optimization.
RapidJSON supports optimized implementations for some parsing operations
based on the SSE2, SSE4.2 or NEon SIMD extensions on modern Intel
or ARM compatible processors.
To enable these optimizations, three different symbols can be defined;
\code
// Enable SSE2 optimization.
#define RAPIDJSON_SSE2
// Enable SSE4.2 optimization.
#define RAPIDJSON_SSE42
\endcode
// Enable ARM Neon optimization.
#define RAPIDJSON_NEON
\endcode
\c RAPIDJSON_SSE42 takes precedence over SSE2, if both are defined.
If any of these symbols is defined, RapidJSON defines the macro
\c RAPIDJSON_SIMD to indicate the availability of the optimized code.
*/
#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) \
|| defined(RAPIDJSON_NEON) || defined(RAPIDJSON_DOXYGEN_RUNNING)
#define RAPIDJSON_SIMD
#endif
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_NO_SIZETYPEDEFINE
#ifndef RAPIDJSON_NO_SIZETYPEDEFINE
/*! \def RAPIDJSON_NO_SIZETYPEDEFINE
\ingroup RAPIDJSON_CONFIG
\brief User-provided \c SizeType definition.
In order to avoid using 32-bit size types for indexing strings and arrays,
define this preprocessor symbol and provide the type rapidjson::SizeType
before including RapidJSON:
\code
#define RAPIDJSON_NO_SIZETYPEDEFINE
namespace rapidjson { typedef ::std::size_t SizeType; }
#include "rapidjson/..."
\endcode
\see rapidjson::SizeType
*/
#ifdef RAPIDJSON_DOXYGEN_RUNNING
#define RAPIDJSON_NO_SIZETYPEDEFINE
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Size type (for string lengths, array sizes, etc.)
/*! RapidJSON uses 32-bit array/string indices even on 64-bit platforms,
instead of using \c size_t. Users may override the SizeType by defining
\ref RAPIDJSON_NO_SIZETYPEDEFINE.
*/
typedef unsigned SizeType;
RAPIDJSON_NAMESPACE_END
#endif
// always import std::size_t to rapidjson namespace
RAPIDJSON_NAMESPACE_BEGIN
using std::size_t;
RAPIDJSON_NAMESPACE_END
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_ASSERT
//! Assertion.
/*! \ingroup RAPIDJSON_CONFIG
By default, rapidjson uses C \c assert() for internal assertions.
User can override it by defining RAPIDJSON_ASSERT(x) macro.
\note Parsing errors are handled and can be customized by the
\ref RAPIDJSON_ERRORS APIs.
*/
#ifndef RAPIDJSON_ASSERT
#include <cassert>
#define RAPIDJSON_ASSERT(x) assert(x)
#endif // RAPIDJSON_ASSERT
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_STATIC_ASSERT
// Prefer C++11 static_assert, if available
#ifndef RAPIDJSON_STATIC_ASSERT
#if __cplusplus >= 201103L || ( defined(_MSC_VER) && _MSC_VER >= 1800 )
#define RAPIDJSON_STATIC_ASSERT(x) \
static_assert(x, RAPIDJSON_STRINGIFY(x))
#endif // C++11
#endif // RAPIDJSON_STATIC_ASSERT
// Adopt C++03 implementation from boost
#ifndef RAPIDJSON_STATIC_ASSERT
#ifndef __clang__
//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
#endif
RAPIDJSON_NAMESPACE_BEGIN
template <bool x> struct STATIC_ASSERTION_FAILURE;
template <> struct STATIC_ASSERTION_FAILURE<true> { enum { value = 1 }; };
template <size_t x> struct StaticAssertTest {};
RAPIDJSON_NAMESPACE_END
#if defined(__GNUC__) || defined(__clang__)
#define RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused))
#else
#define RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE
#endif
#ifndef __clang__
//!@endcond
#endif
/*! \def RAPIDJSON_STATIC_ASSERT
\brief (Internal) macro to check for conditions at compile-time
\param x compile-time condition
\hideinitializer
*/
#define RAPIDJSON_STATIC_ASSERT(x) \
typedef ::RAPIDJSON_NAMESPACE::StaticAssertTest< \
sizeof(::RAPIDJSON_NAMESPACE::STATIC_ASSERTION_FAILURE<bool(x) >)> \
RAPIDJSON_JOIN(StaticAssertTypedef, __LINE__) RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE
#endif // RAPIDJSON_STATIC_ASSERT
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_LIKELY, RAPIDJSON_UNLIKELY
//! Compiler branching hint for expression with high probability to be true.
/*!
\ingroup RAPIDJSON_CONFIG
\param x Boolean expression likely to be true.
*/
#ifndef RAPIDJSON_LIKELY
#if defined(__GNUC__) || defined(__clang__)
#define RAPIDJSON_LIKELY(x) __builtin_expect(!!(x), 1)
#else
#define RAPIDJSON_LIKELY(x) (x)
#endif
#endif
//! Compiler branching hint for expression with low probability to be true.
/*!
\ingroup RAPIDJSON_CONFIG
\param x Boolean expression unlikely to be true.
*/
#ifndef RAPIDJSON_UNLIKELY
#if defined(__GNUC__) || defined(__clang__)
#define RAPIDJSON_UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define RAPIDJSON_UNLIKELY(x) (x)
#endif
#endif
///////////////////////////////////////////////////////////////////////////////
// Helpers
//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
#define RAPIDJSON_MULTILINEMACRO_BEGIN do {
#define RAPIDJSON_MULTILINEMACRO_END \
} while((void)0, 0)
// adopted from Boost
#define RAPIDJSON_VERSION_CODE(x,y,z) \
(((x)*100000) + ((y)*100) + (z))
#if defined(__has_builtin)
#define RAPIDJSON_HAS_BUILTIN(x) __has_builtin(x)
#else
#define RAPIDJSON_HAS_BUILTIN(x) 0
#endif
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_DIAG_PUSH/POP, RAPIDJSON_DIAG_OFF
#if defined(__GNUC__)
#define RAPIDJSON_GNUC \
RAPIDJSON_VERSION_CODE(__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__)
#endif
#if defined(__clang__) || (defined(RAPIDJSON_GNUC) && RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,2,0))
#define RAPIDJSON_PRAGMA(x) _Pragma(RAPIDJSON_STRINGIFY(x))
#define RAPIDJSON_DIAG_PRAGMA(x) RAPIDJSON_PRAGMA(GCC diagnostic x)
#define RAPIDJSON_DIAG_OFF(x) \
RAPIDJSON_DIAG_PRAGMA(ignored RAPIDJSON_STRINGIFY(RAPIDJSON_JOIN(-W,x)))
// push/pop support in Clang and GCC>=4.6
#if defined(__clang__) || (defined(RAPIDJSON_GNUC) && RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,6,0))
#define RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_PRAGMA(push)
#define RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_PRAGMA(pop)
#else // GCC >= 4.2, < 4.6
#define RAPIDJSON_DIAG_PUSH /* ignored */
#define RAPIDJSON_DIAG_POP /* ignored */
#endif
#elif defined(_MSC_VER)
// pragma (MSVC specific)
#define RAPIDJSON_PRAGMA(x) __pragma(x)
#define RAPIDJSON_DIAG_PRAGMA(x) RAPIDJSON_PRAGMA(warning(x))
#define RAPIDJSON_DIAG_OFF(x) RAPIDJSON_DIAG_PRAGMA(disable: x)
#define RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_PRAGMA(push)
#define RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_PRAGMA(pop)
#else
#define RAPIDJSON_DIAG_OFF(x) /* ignored */
#define RAPIDJSON_DIAG_PUSH /* ignored */
#define RAPIDJSON_DIAG_POP /* ignored */
#endif // RAPIDJSON_DIAG_*
///////////////////////////////////////////////////////////////////////////////
// C++11 features
#ifndef RAPIDJSON_HAS_CXX11_RVALUE_REFS
#if defined(__clang__)
#if __has_feature(cxx_rvalue_references) && \
(defined(_MSC_VER) || defined(_LIBCPP_VERSION) || defined(__GLIBCXX__) && __GLIBCXX__ >= 20080306)
#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 1
#else
#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 0
#endif
#elif (defined(RAPIDJSON_GNUC) && (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,3,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \
(defined(_MSC_VER) && _MSC_VER >= 1600) || \
(defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && defined(__GXX_EXPERIMENTAL_CXX0X__))
#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 1
#else
#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 0
#endif
#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS
#ifndef RAPIDJSON_HAS_CXX11_NOEXCEPT
#if defined(__clang__)
#define RAPIDJSON_HAS_CXX11_NOEXCEPT __has_feature(cxx_noexcept)
#elif (defined(RAPIDJSON_GNUC) && (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,6,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \
(defined(_MSC_VER) && _MSC_VER >= 1900) || \
(defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && defined(__GXX_EXPERIMENTAL_CXX0X__))
#define RAPIDJSON_HAS_CXX11_NOEXCEPT 1
#else
#define RAPIDJSON_HAS_CXX11_NOEXCEPT 0
#endif
#endif
#if RAPIDJSON_HAS_CXX11_NOEXCEPT
#define RAPIDJSON_NOEXCEPT noexcept
#else
#define RAPIDJSON_NOEXCEPT /* noexcept */
#endif // RAPIDJSON_HAS_CXX11_NOEXCEPT
// no automatic detection, yet
#ifndef RAPIDJSON_HAS_CXX11_TYPETRAITS
#if (defined(_MSC_VER) && _MSC_VER >= 1700)
#define RAPIDJSON_HAS_CXX11_TYPETRAITS 1
#else
#define RAPIDJSON_HAS_CXX11_TYPETRAITS 0
#endif
#endif
#ifndef RAPIDJSON_HAS_CXX11_RANGE_FOR
#if defined(__clang__)
#define RAPIDJSON_HAS_CXX11_RANGE_FOR __has_feature(cxx_range_for)
#elif (defined(RAPIDJSON_GNUC) && (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,6,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \
(defined(_MSC_VER) && _MSC_VER >= 1700) || \
(defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && defined(__GXX_EXPERIMENTAL_CXX0X__))
#define RAPIDJSON_HAS_CXX11_RANGE_FOR 1
#else
#define RAPIDJSON_HAS_CXX11_RANGE_FOR 0
#endif
#endif // RAPIDJSON_HAS_CXX11_RANGE_FOR
///////////////////////////////////////////////////////////////////////////////
// C++17 features
#if defined(__has_cpp_attribute)
# if __has_cpp_attribute(fallthrough)
# define RAPIDJSON_DELIBERATE_FALLTHROUGH [[fallthrough]]
# else
# define RAPIDJSON_DELIBERATE_FALLTHROUGH
# endif
#else
# define RAPIDJSON_DELIBERATE_FALLTHROUGH
#endif
//!@endcond
//! Assertion (in non-throwing contexts).
/*! \ingroup RAPIDJSON_CONFIG
Some functions provide a \c noexcept guarantee, if the compiler supports it.
In these cases, the \ref RAPIDJSON_ASSERT macro cannot be overridden to
throw an exception. This macro adds a separate customization point for
such cases.
Defaults to C \c assert() (as \ref RAPIDJSON_ASSERT), if \c noexcept is
supported, and to \ref RAPIDJSON_ASSERT otherwise.
*/
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_NOEXCEPT_ASSERT
#ifndef RAPIDJSON_NOEXCEPT_ASSERT
#ifdef RAPIDJSON_ASSERT_THROWS
#if RAPIDJSON_HAS_CXX11_NOEXCEPT
#define RAPIDJSON_NOEXCEPT_ASSERT(x)
#else
#include <cassert>
#define RAPIDJSON_NOEXCEPT_ASSERT(x) assert(x)
#endif // RAPIDJSON_HAS_CXX11_NOEXCEPT
#else
#define RAPIDJSON_NOEXCEPT_ASSERT(x) RAPIDJSON_ASSERT(x)
#endif // RAPIDJSON_ASSERT_THROWS
#endif // RAPIDJSON_NOEXCEPT_ASSERT
///////////////////////////////////////////////////////////////////////////////
// malloc/realloc/free
#ifndef RAPIDJSON_MALLOC
///! customization point for global \c malloc
#define RAPIDJSON_MALLOC(size) std::malloc(size)
#endif
#ifndef RAPIDJSON_REALLOC
///! customization point for global \c realloc
#define RAPIDJSON_REALLOC(ptr, new_size) std::realloc(ptr, new_size)
#endif
#ifndef RAPIDJSON_FREE
///! customization point for global \c free
#define RAPIDJSON_FREE(ptr) std::free(ptr)
#endif
///////////////////////////////////////////////////////////////////////////////
// new/delete
#ifndef RAPIDJSON_NEW
///! customization point for global \c new
#define RAPIDJSON_NEW(TypeName) new TypeName
#endif
#ifndef RAPIDJSON_DELETE
///! customization point for global \c delete
#define RAPIDJSON_DELETE(x) delete x
#endif
///////////////////////////////////////////////////////////////////////////////
// Type
/*! \namespace rapidjson
\brief main RapidJSON namespace
\see RAPIDJSON_NAMESPACE
*/
RAPIDJSON_NAMESPACE_BEGIN
//! Type of JSON value
enum Type {
kNullType = 0, //!< null
kFalseType = 1, //!< false
kTrueType = 2, //!< true
kObjectType = 3, //!< object
kArrayType = 4, //!< array
kStringType = 5, //!< string
kNumberType = 6 //!< number
};
RAPIDJSON_NAMESPACE_END
#endif // RAPIDJSON_RAPIDJSON_H_
| 24,161 | rapidjson | h | en | c | code | {"qsc_code_num_words": 2899, "qsc_code_num_chars": 24161.0, "qsc_code_mean_word_length": 5.58054502, "qsc_code_frac_words_unique": 0.19454984, "qsc_code_frac_chars_top_2grams": 0.10199036, "qsc_code_frac_chars_top_3grams": 0.02311781, "qsc_code_frac_chars_top_4grams": 0.01706021, "qsc_code_frac_chars_dupe_5grams": 0.35288664, "qsc_code_frac_chars_dupe_6grams": 0.24731116, "qsc_code_frac_chars_dupe_7grams": 0.19798492, "qsc_code_frac_chars_dupe_8grams": 0.15650884, "qsc_code_frac_chars_dupe_9grams": 0.13438002, "qsc_code_frac_chars_dupe_10grams": 0.12350105, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02013551, "qsc_code_frac_chars_whitespace": 0.13256902, "qsc_code_size_file_byte": 24161.0, "qsc_code_num_lines": 692.0, "qsc_code_num_chars_line_max": 296.0, "qsc_code_num_chars_line_mean": 34.91473988, "qsc_code_frac_chars_alphabet": 0.75178929, "qsc_code_frac_chars_comments": 0.52501966, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.45117845, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00348554, "qsc_code_frac_chars_long_word_length": 0.00182991, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00505403, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.07407407, "qsc_codec_frac_lines_func_ratio": 0.24242424, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.27272727, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/rapidjson/ostreamwrapper.h | // Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// 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 RAPIDJSON_OSTREAMWRAPPER_H_
#define RAPIDJSON_OSTREAMWRAPPER_H_
#include "stream.h"
#include <iosfwd>
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(padded)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Wrapper of \c std::basic_ostream into RapidJSON's Stream concept.
/*!
The classes can be wrapped including but not limited to:
- \c std::ostringstream
- \c std::stringstream
- \c std::wpstringstream
- \c std::wstringstream
- \c std::ifstream
- \c std::fstream
- \c std::wofstream
- \c std::wfstream
\tparam StreamType Class derived from \c std::basic_ostream.
*/
template <typename StreamType>
class BasicOStreamWrapper {
public:
typedef typename StreamType::char_type Ch;
BasicOStreamWrapper(StreamType& stream) : stream_(stream) {}
void Put(Ch c) {
stream_.put(c);
}
void Flush() {
stream_.flush();
}
// Not implemented
char Peek() const { RAPIDJSON_ASSERT(false); return 0; }
char Take() { RAPIDJSON_ASSERT(false); return 0; }
size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; }
private:
BasicOStreamWrapper(const BasicOStreamWrapper&);
BasicOStreamWrapper& operator=(const BasicOStreamWrapper&);
StreamType& stream_;
};
typedef BasicOStreamWrapper<std::ostream> OStreamWrapper;
typedef BasicOStreamWrapper<std::wostream> WOStreamWrapper;
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
RAPIDJSON_NAMESPACE_END
#endif // RAPIDJSON_OSTREAMWRAPPER_H_
| 2,331 | ostreamwrapper | h | en | c | code | {"qsc_code_num_words": 291, "qsc_code_num_chars": 2331.0, "qsc_code_mean_word_length": 5.69072165, "qsc_code_frac_words_unique": 0.51202749, "qsc_code_frac_chars_top_2grams": 0.02415459, "qsc_code_frac_chars_top_3grams": 0.06038647, "qsc_code_frac_chars_top_4grams": 0.07850242, "qsc_code_frac_chars_dupe_5grams": 0.09842995, "qsc_code_frac_chars_dupe_6grams": 0.0821256, "qsc_code_frac_chars_dupe_7grams": 0.0821256, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00573514, "qsc_code_frac_chars_whitespace": 0.17717718, "qsc_code_size_file_byte": 2331.0, "qsc_code_num_lines": 81.0, "qsc_code_num_chars_line_max": 93.0, "qsc_code_num_chars_line_mean": 28.77777778, "qsc_code_frac_chars_alphabet": 0.85766423, "qsc_code_frac_chars_comments": 0.5027885, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.13513514, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0069025, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.13513514, "qsc_codec_frac_lines_func_ratio": 0.21621622, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.2972973, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/rapidjson/fwd.h | // Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// 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 RAPIDJSON_FWD_H_
#define RAPIDJSON_FWD_H_
#include "rapidjson.h"
RAPIDJSON_NAMESPACE_BEGIN
// encodings.h
template<typename CharType> struct UTF8;
template<typename CharType> struct UTF16;
template<typename CharType> struct UTF16BE;
template<typename CharType> struct UTF16LE;
template<typename CharType> struct UTF32;
template<typename CharType> struct UTF32BE;
template<typename CharType> struct UTF32LE;
template<typename CharType> struct ASCII;
template<typename CharType> struct AutoUTF;
template<typename SourceEncoding, typename TargetEncoding>
struct Transcoder;
// allocators.h
class CrtAllocator;
template <typename BaseAllocator>
class MemoryPoolAllocator;
// stream.h
template <typename Encoding>
struct GenericStringStream;
typedef GenericStringStream<UTF8<char> > StringStream;
template <typename Encoding>
struct GenericInsituStringStream;
typedef GenericInsituStringStream<UTF8<char> > InsituStringStream;
// stringbuffer.h
template <typename Encoding, typename Allocator>
class GenericStringBuffer;
typedef GenericStringBuffer<UTF8<char>, CrtAllocator> StringBuffer;
// filereadstream.h
class FileReadStream;
// filewritestream.h
class FileWriteStream;
// memorybuffer.h
template <typename Allocator>
struct GenericMemoryBuffer;
typedef GenericMemoryBuffer<CrtAllocator> MemoryBuffer;
// memorystream.h
struct MemoryStream;
// reader.h
template<typename Encoding, typename Derived>
struct BaseReaderHandler;
template <typename SourceEncoding, typename TargetEncoding, typename StackAllocator>
class GenericReader;
typedef GenericReader<UTF8<char>, UTF8<char>, CrtAllocator> Reader;
// writer.h
template<typename OutputStream, typename SourceEncoding, typename TargetEncoding, typename StackAllocator, unsigned writeFlags>
class Writer;
// prettywriter.h
template<typename OutputStream, typename SourceEncoding, typename TargetEncoding, typename StackAllocator, unsigned writeFlags>
class PrettyWriter;
// document.h
template <typename Encoding, typename Allocator>
class GenericMember;
template <bool Const, typename Encoding, typename Allocator>
class GenericMemberIterator;
template<typename CharType>
struct GenericStringRef;
template <typename Encoding, typename Allocator>
class GenericValue;
typedef GenericValue<UTF8<char>, MemoryPoolAllocator<CrtAllocator> > Value;
template <typename Encoding, typename Allocator, typename StackAllocator>
class GenericDocument;
typedef GenericDocument<UTF8<char>, MemoryPoolAllocator<CrtAllocator>, CrtAllocator> Document;
// pointer.h
template <typename ValueType, typename Allocator>
class GenericPointer;
typedef GenericPointer<Value, CrtAllocator> Pointer;
// schema.h
template <typename SchemaDocumentType>
class IGenericRemoteSchemaDocumentProvider;
template <typename ValueT, typename Allocator>
class GenericSchemaDocument;
typedef GenericSchemaDocument<Value, CrtAllocator> SchemaDocument;
typedef IGenericRemoteSchemaDocumentProvider<SchemaDocument> IRemoteSchemaDocumentProvider;
template <
typename SchemaDocumentType,
typename OutputHandler,
typename StateAllocator>
class GenericSchemaValidator;
typedef GenericSchemaValidator<SchemaDocument, BaseReaderHandler<UTF8<char>, void>, CrtAllocator> SchemaValidator;
RAPIDJSON_NAMESPACE_END
#endif // RAPIDJSON_RAPIDJSONFWD_H_
| 4,034 | fwd | h | en | c | code | {"qsc_code_num_words": 417, "qsc_code_num_chars": 4034.0, "qsc_code_mean_word_length": 7.88009592, "qsc_code_frac_words_unique": 0.38129496, "qsc_code_frac_chars_top_2grams": 0.13146683, "qsc_code_frac_chars_top_3grams": 0.05173463, "qsc_code_frac_chars_top_4grams": 0.09129641, "qsc_code_frac_chars_dupe_5grams": 0.18685332, "qsc_code_frac_chars_dupe_6grams": 0.13451004, "qsc_code_frac_chars_dupe_7grams": 0.10042605, "qsc_code_frac_chars_dupe_8grams": 0.07181984, "qsc_code_frac_chars_dupe_9grams": 0.07181984, "qsc_code_frac_chars_dupe_10grams": 0.07181984, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00754401, "qsc_code_frac_chars_whitespace": 0.11279127, "qsc_code_size_file_byte": 4034.0, "qsc_code_num_lines": 151.0, "qsc_code_num_chars_line_max": 128.0, "qsc_code_num_chars_line_mean": 26.71523179, "qsc_code_frac_chars_alphabet": 0.91058955, "qsc_code_frac_chars_comments": 0.23847298, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.09859155, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00358073, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.0, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.01408451, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/rapidjson/filewritestream.h | // Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// 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 RAPIDJSON_FILEWRITESTREAM_H_
#define RAPIDJSON_FILEWRITESTREAM_H_
#include "stream.h"
#include <cstdio>
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(unreachable-code)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Wrapper of C file stream for output using fwrite().
/*!
\note implements Stream concept
*/
class FileWriteStream {
public:
typedef char Ch; //!< Character type. Only support char.
FileWriteStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) {
RAPIDJSON_ASSERT(fp_ != 0);
}
void Put(char c) {
if (current_ >= bufferEnd_)
Flush();
*current_++ = c;
}
void PutN(char c, size_t n) {
size_t avail = static_cast<size_t>(bufferEnd_ - current_);
while (n > avail) {
std::memset(current_, c, avail);
current_ += avail;
Flush();
n -= avail;
avail = static_cast<size_t>(bufferEnd_ - current_);
}
if (n > 0) {
std::memset(current_, c, n);
current_ += n;
}
}
void Flush() {
if (current_ != buffer_) {
size_t result = std::fwrite(buffer_, 1, static_cast<size_t>(current_ - buffer_), fp_);
if (result < static_cast<size_t>(current_ - buffer_)) {
// failure deliberately ignored at this time
// added to avoid warn_unused_result build errors
}
current_ = buffer_;
}
}
// Not implemented
char Peek() const { RAPIDJSON_ASSERT(false); return 0; }
char Take() { RAPIDJSON_ASSERT(false); return 0; }
size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; }
private:
// Prohibit copy constructor & assignment operator.
FileWriteStream(const FileWriteStream&);
FileWriteStream& operator=(const FileWriteStream&);
std::FILE* fp_;
char *buffer_;
char *bufferEnd_;
char *current_;
};
//! Implement specialized version of PutN() with memset() for better performance.
template<>
inline void PutN(FileWriteStream& stream, char c, size_t n) {
stream.PutN(c, n);
}
RAPIDJSON_NAMESPACE_END
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_FILESTREAM_H_
| 3,146 | filewritestream | h | en | c | code | {"qsc_code_num_words": 382, "qsc_code_num_chars": 3146.0, "qsc_code_mean_word_length": 5.20157068, "qsc_code_frac_words_unique": 0.43455497, "qsc_code_frac_chars_top_2grams": 0.02767992, "qsc_code_frac_chars_top_3grams": 0.05032713, "qsc_code_frac_chars_top_4grams": 0.06542526, "qsc_code_frac_chars_dupe_5grams": 0.19174635, "qsc_code_frac_chars_dupe_6grams": 0.16708606, "qsc_code_frac_chars_dupe_7grams": 0.10468042, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00585284, "qsc_code_frac_chars_whitespace": 0.23966942, "qsc_code_size_file_byte": 3146.0, "qsc_code_num_lines": 104.0, "qsc_code_num_chars_line_max": 150.0, "qsc_code_num_chars_line_mean": 30.25, "qsc_code_frac_chars_alphabet": 0.82483278, "qsc_code_frac_chars_comments": 0.35823268, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.109375, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00396236, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.09375, "qsc_codec_frac_lines_func_ratio": 0.15625, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.203125, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/rapidjson/memorystream.h | // Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// 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 RAPIDJSON_MEMORYSTREAM_H_
#define RAPIDJSON_MEMORYSTREAM_H_
#include "stream.h"
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(unreachable-code)
RAPIDJSON_DIAG_OFF(missing-noreturn)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Represents an in-memory input byte stream.
/*!
This class is mainly for being wrapped by EncodedInputStream or AutoUTFInputStream.
It is similar to FileReadBuffer but the source is an in-memory buffer instead of a file.
Differences between MemoryStream and StringStream:
1. StringStream has encoding but MemoryStream is a byte stream.
2. MemoryStream needs size of the source buffer and the buffer don't need to be null terminated. StringStream assume null-terminated string as source.
3. MemoryStream supports Peek4() for encoding detection. StringStream is specified with an encoding so it should not have Peek4().
\note implements Stream concept
*/
struct MemoryStream {
typedef char Ch; // byte
MemoryStream(const Ch *src, size_t size) : src_(src), begin_(src), end_(src + size), size_(size) {}
Ch Peek() const { return RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_; }
Ch Take() { return RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_++; }
size_t Tell() const { return static_cast<size_t>(src_ - begin_); }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
void Put(Ch) { RAPIDJSON_ASSERT(false); }
void Flush() { RAPIDJSON_ASSERT(false); }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
// For encoding detection only.
const Ch* Peek4() const {
return Tell() + 4 <= size_ ? src_ : 0;
}
const Ch* src_; //!< Current read position.
const Ch* begin_; //!< Original head of the string.
const Ch* end_; //!< End of stream.
size_t size_; //!< Size of the stream.
};
RAPIDJSON_NAMESPACE_END
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_MEMORYBUFFER_H_
| 2,667 | memorystream | h | en | c | code | {"qsc_code_num_words": 369, "qsc_code_num_chars": 2667.0, "qsc_code_mean_word_length": 5.05420054, "qsc_code_frac_words_unique": 0.46070461, "qsc_code_frac_chars_top_2grams": 0.03217158, "qsc_code_frac_chars_top_3grams": 0.04289544, "qsc_code_frac_chars_top_4grams": 0.01715818, "qsc_code_frac_chars_dupe_5grams": 0.06434316, "qsc_code_frac_chars_dupe_6grams": 0.03538874, "qsc_code_frac_chars_dupe_7grams": 0.03538874, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00831025, "qsc_code_frac_chars_whitespace": 0.18785152, "qsc_code_size_file_byte": 2667.0, "qsc_code_num_lines": 71.0, "qsc_code_num_chars_line_max": 155.0, "qsc_code_num_chars_line_mean": 37.56338028, "qsc_code_frac_chars_alphabet": 0.85272392, "qsc_code_frac_chars_comments": 0.59055118, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.17857143, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01098901, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.14285714, "qsc_codec_frac_lines_func_ratio": 0.42857143, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.46428571, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/T-Glass-Applications | image_capture_app/t_glass_ble_app/macos/Runner/Info.plist | <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSBluetoothAlwaysUsageDescription</key>
<string>This app needs Bluetooth to function</string>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIconFile</key>
<string>AppIcon</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHumanReadableCopyright</key>
<string>$(PRODUCT_COPYRIGHT)</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>
| 1,168 | Info | plist | en | openstep property list | data | {"qsc_code_num_words": 134, "qsc_code_num_chars": 1168.0, "qsc_code_mean_word_length": 6.44776119, "qsc_code_frac_words_unique": 0.44776119, "qsc_code_frac_chars_top_2grams": 0.14583333, "qsc_code_frac_chars_top_3grams": 0.04513889, "qsc_code_frac_chars_top_4grams": 0.04861111, "qsc_code_frac_chars_dupe_5grams": 0.0, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01007326, "qsc_code_frac_chars_whitespace": 0.06506849, "qsc_code_size_file_byte": 1168.0, "qsc_code_num_lines": 34.0, "qsc_code_num_chars_line_max": 103.0, "qsc_code_num_chars_line_mean": 34.35294118, "qsc_code_frac_chars_alphabet": 0.78113553, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 1.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.07191781, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_words_unique": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 1, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0} |
0015/esp_rlottie | rlottie/src/vector/vdebug.cpp | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
* 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.
*/
#include "vdebug.h"
#ifdef LOTTIE_LOGGING_SUPPORT
#include <atomic>
#include <chrono>
#include <cstring>
#include <ctime>
#include <fstream>
#include <memory>
#include <queue>
#include <sstream>
#include <thread>
#include <tuple>
namespace {
/* Returns microseconds since epoch */
uint64_t timestamp_now()
{
return std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch())
.count();
}
/* I want [2016-10-13 00:01:23.528514] */
void format_timestamp(std::ostream& os, uint64_t timestamp)
{
// The next 3 lines do not work on MSVC!
// auto duration = std::chrono::microseconds(timestamp);
// std::chrono::high_resolution_clock::time_point time_point(duration);
// std::time_t time_t =
// std::chrono::high_resolution_clock::to_time_t(time_point);
std::time_t time_t = timestamp / 1000000;
auto gmtime = std::gmtime(&time_t);
char buffer[32];
strftime(buffer, 32, "%Y-%m-%d %T.", gmtime);
char microseconds[7];
snprintf(microseconds, 7, "%06llu",
(long long unsigned int)timestamp % 1000000);
os << '[' << buffer << microseconds << ']';
}
std::thread::id this_thread_id()
{
static thread_local const std::thread::id id = std::this_thread::get_id();
return id;
}
template <typename T, typename Tuple>
struct TupleIndex;
template <typename T, typename... Types>
struct TupleIndex<T, std::tuple<T, Types...> > {
static constexpr const std::size_t value = 0;
};
template <typename T, typename U, typename... Types>
struct TupleIndex<T, std::tuple<U, Types...> > {
static constexpr const std::size_t value =
1 + TupleIndex<T, std::tuple<Types...> >::value;
};
} // anonymous namespace
typedef std::tuple<char, uint32_t, uint64_t, int32_t, int64_t, double,
VDebug::string_literal_t, char*>
SupportedTypes;
char const* to_string(LogLevel loglevel)
{
switch (loglevel) {
case LogLevel::OFF:
return "OFF";
case LogLevel::INFO:
return "INFO";
case LogLevel::WARN:
return "WARN";
case LogLevel::CRIT:
return "CRIT";
}
return "XXXX";
}
template <typename Arg>
void VDebug::encode(Arg arg)
{
*reinterpret_cast<Arg*>(buffer()) = arg;
m_bytes_used += sizeof(Arg);
}
template <typename Arg>
void VDebug::encode(Arg arg, uint8_t type_id)
{
resize_buffer_if_needed(sizeof(Arg) + sizeof(uint8_t));
encode<uint8_t>(type_id);
encode<Arg>(arg);
}
VDebug::VDebug(LogLevel level, char const* file, char const* function,
uint32_t line)
: m_bytes_used(0), m_buffer_size(sizeof(m_stack_buffer))
{
encode<uint64_t>(timestamp_now());
encode<std::thread::id>(this_thread_id());
encode<string_literal_t>(string_literal_t(file));
encode<string_literal_t>(string_literal_t(function));
encode<uint32_t>(line);
encode<LogLevel>(level);
if (level == LogLevel::INFO) {
m_logAll = false;
} else {
m_logAll = true;
}
}
VDebug::~VDebug() = default;
void VDebug::stringify(std::ostream& os)
{
char* b = !m_heap_buffer ? m_stack_buffer : m_heap_buffer.get();
char const* const end = b + m_bytes_used;
uint64_t timestamp = *reinterpret_cast<uint64_t*>(b);
b += sizeof(uint64_t);
std::thread::id threadid = *reinterpret_cast<std::thread::id*>(b);
b += sizeof(std::thread::id);
string_literal_t file = *reinterpret_cast<string_literal_t*>(b);
b += sizeof(string_literal_t);
string_literal_t function = *reinterpret_cast<string_literal_t*>(b);
b += sizeof(string_literal_t);
uint32_t line = *reinterpret_cast<uint32_t*>(b);
b += sizeof(uint32_t);
LogLevel loglevel = *reinterpret_cast<LogLevel*>(b);
b += sizeof(LogLevel);
if (m_logAll) {
format_timestamp(os, timestamp);
os << '[' << to_string(loglevel) << ']' << '[' << threadid << ']' << '['
<< file.m_s << ':' << function.m_s << ':' << line << "] ";
}
stringify(os, b, end);
os << std::endl;
if (loglevel >= LogLevel::CRIT) os.flush();
}
template <typename Arg>
char* decode(std::ostream& os, char* b, Arg* /*dummy*/)
{
Arg arg = *reinterpret_cast<Arg*>(b);
os << arg;
return b + sizeof(Arg);
}
template <>
char* decode(std::ostream& os, char* b, VDebug::string_literal_t* /*dummy*/)
{
VDebug::string_literal_t s =
*reinterpret_cast<VDebug::string_literal_t*>(b);
os << s.m_s;
return b + sizeof(VDebug::string_literal_t);
}
template <>
char* decode(std::ostream& os, char* b, char** /*dummy*/)
{
while (*b != '\0') {
os << *b;
++b;
}
return ++b;
}
void VDebug::stringify(std::ostream& os, char* start, char const* const end)
{
if (start == end) return;
int type_id = static_cast<int>(*start);
start++;
switch (type_id) {
case 0:
stringify(
os,
decode(os, start,
static_cast<std::tuple_element<0, SupportedTypes>::type*>(
nullptr)),
end);
return;
case 1:
stringify(
os,
decode(os, start,
static_cast<std::tuple_element<1, SupportedTypes>::type*>(
nullptr)),
end);
return;
case 2:
stringify(
os,
decode(os, start,
static_cast<std::tuple_element<2, SupportedTypes>::type*>(
nullptr)),
end);
return;
case 3:
stringify(
os,
decode(os, start,
static_cast<std::tuple_element<3, SupportedTypes>::type*>(
nullptr)),
end);
return;
case 4:
stringify(
os,
decode(os, start,
static_cast<std::tuple_element<4, SupportedTypes>::type*>(
nullptr)),
end);
return;
case 5:
stringify(
os,
decode(os, start,
static_cast<std::tuple_element<5, SupportedTypes>::type*>(
nullptr)),
end);
return;
case 6:
stringify(
os,
decode(os, start,
static_cast<std::tuple_element<6, SupportedTypes>::type*>(
nullptr)),
end);
return;
case 7:
stringify(
os,
decode(os, start,
static_cast<std::tuple_element<7, SupportedTypes>::type*>(
nullptr)),
end);
return;
}
}
char* VDebug::buffer()
{
return !m_heap_buffer ? &m_stack_buffer[m_bytes_used]
: &(m_heap_buffer.get())[m_bytes_used];
}
void VDebug::resize_buffer_if_needed(size_t additional_bytes)
{
size_t const required_size = m_bytes_used + additional_bytes;
if (required_size <= m_buffer_size) return;
if (!m_heap_buffer) {
m_buffer_size = std::max(static_cast<size_t>(512), required_size);
m_heap_buffer = std::make_unique<char[]>(m_buffer_size);
memcpy(m_heap_buffer.get(), m_stack_buffer, m_bytes_used);
return;
} else {
m_buffer_size =
std::max(static_cast<size_t>(2 * m_buffer_size), required_size);
std::unique_ptr<char[]> new_heap_buffer(new char[m_buffer_size]);
memcpy(new_heap_buffer.get(), m_heap_buffer.get(), m_bytes_used);
m_heap_buffer.swap(new_heap_buffer);
}
}
void VDebug::encode(char const* arg)
{
if (arg != nullptr) encode_c_string(arg, strlen(arg));
}
void VDebug::encode(char* arg)
{
if (arg != nullptr) encode_c_string(arg, strlen(arg));
}
void VDebug::encode_c_string(char const* arg, size_t length)
{
if (length == 0) return;
resize_buffer_if_needed(1 + length + 1);
char* b = buffer();
auto type_id = TupleIndex<char*, SupportedTypes>::value;
*reinterpret_cast<uint8_t*>(b++) = static_cast<uint8_t>(type_id);
memcpy(b, arg, length + 1);
m_bytes_used += 1 + length + 1;
}
void VDebug::encode(string_literal_t arg)
{
encode<string_literal_t>(
arg, TupleIndex<string_literal_t, SupportedTypes>::value);
}
VDebug& VDebug::operator<<(std::string const& arg)
{
encode_c_string(arg.c_str(), arg.length());
return *this;
}
VDebug& VDebug::operator<<(int32_t arg)
{
encode<int32_t>(arg, TupleIndex<int32_t, SupportedTypes>::value);
return *this;
}
VDebug& VDebug::operator<<(uint32_t arg)
{
encode<uint32_t>(arg, TupleIndex<uint32_t, SupportedTypes>::value);
return *this;
}
// VDebug& VDebug::operator<<(int64_t arg)
// {
// encode < int64_t >(arg, TupleIndex < int64_t, SupportedTypes >::value);
// return *this;
// }
// VDebug& VDebug::operator<<(uint64_t arg)
// {
// encode < uint64_t >(arg, TupleIndex < uint64_t, SupportedTypes >::value);
// return *this;
// }
VDebug& VDebug::operator<<(unsigned long arg)
{
encode<uint64_t>(arg, TupleIndex<uint64_t, SupportedTypes>::value);
return *this;
}
VDebug& VDebug::operator<<(long arg)
{
encode<int64_t>(arg, TupleIndex<int64_t, SupportedTypes>::value);
return *this;
}
VDebug& VDebug::operator<<(double arg)
{
encode<double>(arg, TupleIndex<double, SupportedTypes>::value);
return *this;
}
VDebug& VDebug::operator<<(char arg)
{
encode<char>(arg, TupleIndex<char, SupportedTypes>::value);
return *this;
}
struct BufferBase {
virtual ~BufferBase() = default;
virtual void push(VDebug&& logline) = 0;
virtual bool try_pop(VDebug& logline) = 0;
};
struct SpinLock {
SpinLock(std::atomic_flag& flag) : m_flag(flag)
{
while (m_flag.test_and_set(std::memory_order_acquire))
;
}
~SpinLock() { m_flag.clear(std::memory_order_release); }
private:
std::atomic_flag& m_flag;
};
/* Multi Producer Single Consumer Ring Buffer */
class RingBuffer : public BufferBase {
public:
struct alignas(64) Item {
Item()
: flag(), written(0), logline(LogLevel::INFO, nullptr, nullptr, 0)
{
}
std::atomic_flag flag;
char written;
char padding[256 - sizeof(std::atomic_flag) - sizeof(char) -
sizeof(VDebug)];
VDebug logline;
};
RingBuffer(size_t const size)
: m_size(size),
m_ring(static_cast<Item*>(std::malloc(size * sizeof(Item)))),
m_write_index(0),
m_read_index(0)
{
for (size_t i = 0; i < m_size; ++i) {
new (&m_ring[i]) Item();
}
static_assert(sizeof(Item) == 256, "Unexpected size != 256");
}
~RingBuffer() override
{
for (size_t i = 0; i < m_size; ++i) {
m_ring[i].~Item();
}
std::free(m_ring);
}
void push(VDebug&& logline) override
{
unsigned int write_index =
m_write_index.fetch_add(1, std::memory_order_relaxed) % m_size;
Item& item = m_ring[write_index];
SpinLock spinlock(item.flag);
item.logline = std::move(logline);
item.written = 1;
}
bool try_pop(VDebug& logline) override
{
Item& item = m_ring[m_read_index % m_size];
SpinLock spinlock(item.flag);
if (item.written == 1) {
logline = std::move(item.logline);
item.written = 0;
++m_read_index;
return true;
}
return false;
}
RingBuffer(RingBuffer const&) = delete;
RingBuffer& operator=(RingBuffer const&) = delete;
private:
size_t const m_size;
Item* m_ring;
std::atomic<unsigned int> m_write_index;
public:
char pad[64];
private:
unsigned int m_read_index;
};
class Buffer {
public:
struct Item {
Item(VDebug&& logline) : logline(std::move(logline)) {}
char padding[256 - sizeof(VDebug)];
VDebug logline;
};
static constexpr const size_t size =
32768; // 8MB. Helps reduce memory fragmentation
Buffer() : m_buffer(static_cast<Item*>(std::malloc(size * sizeof(Item))))
{
for (size_t i = 0; i <= size; ++i) {
m_write_state[i].store(0, std::memory_order_relaxed);
}
static_assert(sizeof(Item) == 256, "Unexpected size != 256");
}
~Buffer()
{
unsigned int write_count = m_write_state[size].load();
for (size_t i = 0; i < write_count; ++i) {
m_buffer[i].~Item();
}
std::free(m_buffer);
}
// Returns true if we need to switch to next buffer
bool push(VDebug&& logline, unsigned int const write_index)
{
new (&m_buffer[write_index]) Item(std::move(logline));
m_write_state[write_index].store(1, std::memory_order_release);
return m_write_state[size].fetch_add(1, std::memory_order_acquire) +
1 ==
size;
}
bool try_pop(VDebug& logline, unsigned int const read_index)
{
if (m_write_state[read_index].load(std::memory_order_acquire)) {
Item& item = m_buffer[read_index];
logline = std::move(item.logline);
return true;
}
return false;
}
Buffer(Buffer const&) = delete;
Buffer& operator=(Buffer const&) = delete;
private:
Item* m_buffer;
std::atomic<unsigned int> m_write_state[size + 1];
};
class QueueBuffer : public BufferBase {
public:
QueueBuffer(QueueBuffer const&) = delete;
QueueBuffer& operator=(QueueBuffer const&) = delete;
QueueBuffer()
: m_current_read_buffer{nullptr},
m_write_index(0),
m_flag(),
m_read_index(0)
{
setup_next_write_buffer();
}
void push(VDebug&& logline) override
{
unsigned int write_index =
m_write_index.fetch_add(1, std::memory_order_relaxed);
if (write_index < Buffer::size) {
if (m_current_write_buffer.load(std::memory_order_acquire)
->push(std::move(logline), write_index)) {
setup_next_write_buffer();
}
} else {
while (m_write_index.load(std::memory_order_acquire) >=
Buffer::size)
;
push(std::move(logline));
}
}
bool try_pop(VDebug& logline) override
{
if (m_current_read_buffer == nullptr)
m_current_read_buffer = get_next_read_buffer();
Buffer* read_buffer = m_current_read_buffer;
if (read_buffer == nullptr) return false;
if (read_buffer->try_pop(logline, m_read_index)) {
m_read_index++;
if (m_read_index == Buffer::size) {
m_read_index = 0;
m_current_read_buffer = nullptr;
SpinLock spinlock(m_flag);
m_buffers.pop();
}
return true;
}
return false;
}
private:
void setup_next_write_buffer()
{
std::unique_ptr<Buffer> next_write_buffer(new Buffer());
m_current_write_buffer.store(next_write_buffer.get(),
std::memory_order_release);
SpinLock spinlock(m_flag);
m_buffers.push(std::move(next_write_buffer));
m_write_index.store(0, std::memory_order_relaxed);
}
Buffer* get_next_read_buffer()
{
SpinLock spinlock(m_flag);
return m_buffers.empty() ? nullptr : m_buffers.front().get();
}
private:
std::queue<std::unique_ptr<Buffer> > m_buffers;
std::atomic<Buffer*> m_current_write_buffer;
Buffer* m_current_read_buffer;
std::atomic<unsigned int> m_write_index;
std::atomic_flag m_flag;
unsigned int m_read_index;
};
class FileWriter {
public:
FileWriter(std::string const& log_directory,
std::string const& log_file_name, uint32_t log_file_roll_size_mb)
: m_log_file_roll_size_bytes(log_file_roll_size_mb * 1024 * 1024),
m_name(log_directory + log_file_name)
{
roll_file();
}
void write(VDebug& logline)
{
auto pos = m_os->tellp();
logline.stringify(*m_os);
m_bytes_written += m_os->tellp() - pos;
if (m_bytes_written > m_log_file_roll_size_bytes) {
roll_file();
}
}
private:
void roll_file()
{
if (m_os) {
m_os->flush();
m_os->close();
}
m_bytes_written = 0;
m_os = std::make_unique<std::ofstream>();
// TODO Optimize this part. Does it even matter ?
std::string log_file_name = m_name;
log_file_name.append(".");
log_file_name.append(std::to_string(++m_file_number));
log_file_name.append(".txt");
m_os->open(log_file_name, std::ofstream::out | std::ofstream::trunc);
}
private:
uint32_t m_file_number = 0;
std::streamoff m_bytes_written = 0;
uint32_t const m_log_file_roll_size_bytes;
std::string const m_name;
std::unique_ptr<std::ofstream> m_os;
};
class NanoLogger {
public:
NanoLogger(NonGuaranteedLogger ngl, std::string const& log_directory,
std::string const& log_file_name, uint32_t log_file_roll_size_mb)
: m_state(State::INIT),
m_buffer_base(
new RingBuffer(std::max(1u, ngl.ring_buffer_size_mb) * 1024 * 4)),
m_file_writer(log_directory, log_file_name,
std::max(1u, log_file_roll_size_mb)),
m_thread(&NanoLogger::pop, this)
{
m_state.store(State::READY, std::memory_order_release);
}
NanoLogger(GuaranteedLogger /*gl*/, std::string const& log_directory,
std::string const& log_file_name, uint32_t log_file_roll_size_mb)
: m_state(State::INIT),
m_buffer_base(new QueueBuffer()),
m_file_writer(log_directory, log_file_name,
std::max(1u, log_file_roll_size_mb)),
m_thread(&NanoLogger::pop, this)
{
m_state.store(State::READY, std::memory_order_release);
}
~NanoLogger()
{
m_state.store(State::SHUTDOWN);
m_thread.join();
}
void add(VDebug&& logline) { m_buffer_base->push(std::move(logline)); }
void pop()
{
// Wait for constructor to complete and pull all stores done there to
// this thread / core.
while (m_state.load(std::memory_order_acquire) == State::INIT)
std::this_thread::sleep_for(std::chrono::microseconds(50));
VDebug logline(LogLevel::INFO, nullptr, nullptr, 0);
while (m_state.load() == State::READY) {
if (m_buffer_base->try_pop(logline))
m_file_writer.write(logline);
else
std::this_thread::sleep_for(std::chrono::microseconds(50));
}
// Pop and log all remaining entries
while (m_buffer_base->try_pop(logline)) {
m_file_writer.write(logline);
}
}
private:
enum class State { INIT, READY, SHUTDOWN };
std::atomic<State> m_state;
std::unique_ptr<BufferBase> m_buffer_base;
FileWriter m_file_writer;
std::thread m_thread;
};
std::unique_ptr<NanoLogger> nanologger;
std::atomic<NanoLogger*> atomic_nanologger;
bool VDebugServer::operator==(VDebug& logline)
{
atomic_nanologger.load(std::memory_order_acquire)->add(std::move(logline));
return true;
}
void initialize(NonGuaranteedLogger ngl, std::string const& log_directory,
std::string const& log_file_name,
uint32_t log_file_roll_size_mb)
{
nanologger = std::make_unique<NanoLogger>(ngl, log_directory, log_file_name,
log_file_roll_size_mb);
atomic_nanologger.store(nanologger.get(), std::memory_order_seq_cst);
}
void initialize(GuaranteedLogger gl, std::string const& log_directory,
std::string const& log_file_name,
uint32_t log_file_roll_size_mb)
{
nanologger = std::make_unique<NanoLogger>(gl, log_directory, log_file_name,
log_file_roll_size_mb);
atomic_nanologger.store(nanologger.get(), std::memory_order_seq_cst);
}
std::atomic<unsigned int> loglevel = {0};
void set_log_level(LogLevel level)
{
loglevel.store(static_cast<unsigned int>(level), std::memory_order_release);
}
bool is_logged(LogLevel level)
{
return static_cast<unsigned int>(level) >=
loglevel.load(std::memory_order_relaxed);
}
#endif // LOTTIE_LOGGING_SUPPORT
| 22,094 | vdebug | cpp | en | cpp | code | {"qsc_code_num_words": 2704, "qsc_code_num_chars": 22094.0, "qsc_code_mean_word_length": 4.65051775, "qsc_code_frac_words_unique": 0.1364645, "qsc_code_frac_chars_top_2grams": 0.01558648, "qsc_code_frac_chars_top_3grams": 0.0222664, "qsc_code_frac_chars_top_4grams": 0.01550696, "qsc_code_frac_chars_dupe_5grams": 0.41256461, "qsc_code_frac_chars_dupe_6grams": 0.34282306, "qsc_code_frac_chars_dupe_7grams": 0.27387674, "qsc_code_frac_chars_dupe_8grams": 0.23284294, "qsc_code_frac_chars_dupe_9grams": 0.19419483, "qsc_code_frac_chars_dupe_10grams": 0.17940358, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01467833, "qsc_code_frac_chars_whitespace": 0.27536888, "qsc_code_size_file_byte": 22094.0, "qsc_code_num_lines": 758.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 29.14775726, "qsc_code_frac_chars_alphabet": 0.77076827, "qsc_code_frac_chars_comments": 0.10002716, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.25570033, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00538121, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.00131926, "qsc_code_frac_lines_assert": 0.00325733, "qsc_codecpp_frac_lines_preprocessor_directives": 0.03257329, "qsc_codecpp_frac_lines_func_ratio": 0.06026059, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.12703583, "qsc_codecpp_frac_lines_print": 0.00162866} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/vector/vpainter.cpp | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
* 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.
*/
#include "vpainter.h"
#include <algorithm>
V_BEGIN_NAMESPACE
void VPainter::drawRle(const VPoint &, const VRle &rle)
{
if (rle.empty()) return;
// mSpanData.updateSpanFunc();
if (!mSpanData.mUnclippedBlendFunc) return;
// do draw after applying clip.
rle.intersect(mSpanData.clipRect(), mSpanData.mUnclippedBlendFunc,
&mSpanData);
}
void VPainter::drawRle(const VRle &rle, const VRle &clip)
{
if (rle.empty() || clip.empty()) return;
if (!mSpanData.mUnclippedBlendFunc) return;
rle.intersect(clip, mSpanData.mUnclippedBlendFunc, &mSpanData);
}
static void fillRect(const VRect &r, VSpanData *data)
{
auto x1 = std::max(r.x(), 0);
auto x2 = std::min(r.x() + r.width(), data->mDrawableSize.width());
auto y1 = std::max(r.y(), 0);
auto y2 = std::min(r.y() + r.height(), data->mDrawableSize.height());
if (x2 <= x1 || y2 <= y1) return;
const int nspans = 256;
VRle::Span spans[nspans];
int y = y1;
while (y < y2) {
int n = std::min(nspans, y2 - y);
int i = 0;
while (i < n) {
spans[i].x = short(x1);
spans[i].len = uint16_t(x2 - x1);
spans[i].y = short(y + i);
spans[i].coverage = 255;
++i;
}
data->mUnclippedBlendFunc(n, spans, data);
y += n;
}
}
void VPainter::drawBitmapUntransform(const VRect & target,
const VBitmap &bitmap,
const VRect & source,
uint8_t const_alpha)
{
mSpanData.initTexture(&bitmap, const_alpha, source);
if (!mSpanData.mUnclippedBlendFunc) return;
// update translation matrix for source texture.
mSpanData.dx = float(target.x() - source.x());
mSpanData.dy = float(target.y() - source.y());
fillRect(target, &mSpanData);
}
VPainter::VPainter(VBitmap *buffer)
{
begin(buffer);
}
bool VPainter::begin(VBitmap *buffer)
{
mBuffer.prepare(buffer);
mSpanData.init(&mBuffer);
// TODO find a better api to clear the surface
mBuffer.clear();
return true;
}
void VPainter::end() {}
void VPainter::setDrawRegion(const VRect ®ion)
{
mSpanData.setDrawRegion(region);
}
void VPainter::setBrush(const VBrush &brush)
{
mSpanData.setup(brush);
}
void VPainter::setBlendMode(BlendMode mode)
{
mSpanData.mBlendMode = mode;
}
VRect VPainter::clipBoundingRect() const
{
return mSpanData.clipRect();
}
void VPainter::drawBitmap(const VPoint &point, const VBitmap &bitmap,
const VRect &source, uint8_t const_alpha)
{
if (!bitmap.valid()) return;
drawBitmap(VRect(point, bitmap.size()),
bitmap, source, const_alpha);
}
void VPainter::drawBitmap(const VRect &target, const VBitmap &bitmap,
const VRect &source, uint8_t const_alpha)
{
if (!bitmap.valid()) return;
// clear any existing brush data.
setBrush(VBrush());
if (target.size() == source.size()) {
drawBitmapUntransform(target, bitmap, source, const_alpha);
} else {
// @TODO scaling
}
}
void VPainter::drawBitmap(const VPoint &point, const VBitmap &bitmap,
uint8_t const_alpha)
{
if (!bitmap.valid()) return;
drawBitmap(VRect(point, bitmap.size()),
bitmap, bitmap.rect(),
const_alpha);
}
void VPainter::drawBitmap(const VRect &rect, const VBitmap &bitmap,
uint8_t const_alpha)
{
if (!bitmap.valid()) return;
drawBitmap(rect, bitmap, bitmap.rect(),
const_alpha);
}
V_END_NAMESPACE
| 4,841 | vpainter | cpp | en | cpp | code | {"qsc_code_num_words": 582, "qsc_code_num_chars": 4841.0, "qsc_code_mean_word_length": 5.23883162, "qsc_code_frac_words_unique": 0.35051546, "qsc_code_frac_chars_top_2grams": 0.04329288, "qsc_code_frac_chars_top_3grams": 0.02951787, "qsc_code_frac_chars_top_4grams": 0.02623811, "qsc_code_frac_chars_dupe_5grams": 0.19481797, "qsc_code_frac_chars_dupe_6grams": 0.18301082, "qsc_code_frac_chars_dupe_7grams": 0.18301082, "qsc_code_frac_chars_dupe_8grams": 0.15874057, "qsc_code_frac_chars_dupe_9grams": 0.15874057, "qsc_code_frac_chars_dupe_10grams": 0.13381437, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00937414, "qsc_code_frac_chars_whitespace": 0.25077463, "qsc_code_size_file_byte": 4841.0, "qsc_code_num_lines": 172.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 28.14534884, "qsc_code_frac_chars_alphabet": 0.83126551, "qsc_code_frac_chars_comments": 0.28052055, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.16071429, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00287109, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.01162791, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.01785714, "qsc_codecpp_frac_lines_func_ratio": 0.00892857, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.03571429, "qsc_codecpp_frac_lines_print": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 1, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/vector/vraster.cpp | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
* 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.
*/
#include "vraster.h"
#include <climits>
#include <cstring>
#include <memory>
#include "config.h"
#include "v_ft_raster.h"
#include "v_ft_stroker.h"
#include "vdebug.h"
#include "vmatrix.h"
#include "vpath.h"
#include "vrle.h"
V_BEGIN_NAMESPACE
template <typename T>
class dyn_array {
public:
explicit dyn_array(size_t size)
: mCapacity(size), mData(std::make_unique<T[]>(mCapacity))
{
}
void reserve(size_t size)
{
if (mCapacity > size) return;
mCapacity = size;
mData = std::make_unique<T[]>(mCapacity);
}
T * data() const { return mData.get(); }
dyn_array &operator=(dyn_array &&) noexcept = delete;
private:
size_t mCapacity{0};
std::unique_ptr<T[]> mData{nullptr};
};
struct FTOutline {
public:
void reset();
void grow(size_t, size_t);
void convert(const VPath &path);
void convert(CapStyle, JoinStyle, float, float);
void moveTo(const VPointF &pt);
void lineTo(const VPointF &pt);
void cubicTo(const VPointF &ctr1, const VPointF &ctr2, const VPointF end);
void close();
void end();
void transform(const VMatrix &m);
SW_FT_Pos TO_FT_COORD(float x)
{
return SW_FT_Pos(x * 64);
} // to freetype 26.6 coordinate.
SW_FT_Outline ft;
bool closed{false};
SW_FT_Stroker_LineCap ftCap;
SW_FT_Stroker_LineJoin ftJoin;
SW_FT_Fixed ftWidth;
SW_FT_Fixed ftMiterLimit;
dyn_array<SW_FT_Vector> mPointMemory{100};
dyn_array<char> mTagMemory{100};
dyn_array<short> mContourMemory{10};
dyn_array<char> mContourFlagMemory{10};
};
void FTOutline::reset()
{
ft.n_points = ft.n_contours = 0;
ft.flags = 0x0;
}
void FTOutline::grow(size_t points, size_t segments)
{
reset();
mPointMemory.reserve(points + segments);
mTagMemory.reserve(points + segments);
mContourMemory.reserve(segments);
mContourFlagMemory.reserve(segments);
ft.points = mPointMemory.data();
ft.tags = mTagMemory.data();
ft.contours = mContourMemory.data();
ft.contours_flag = mContourFlagMemory.data();
}
void FTOutline::convert(const VPath &path)
{
const std::vector<VPath::Element> &elements = path.elements();
const std::vector<VPointF> & points = path.points();
grow(points.size(), path.segments());
size_t index = 0;
for (auto element : elements) {
switch (element) {
case VPath::Element::MoveTo:
moveTo(points[index]);
index++;
break;
case VPath::Element::LineTo:
lineTo(points[index]);
index++;
break;
case VPath::Element::CubicTo:
cubicTo(points[index], points[index + 1], points[index + 2]);
index = index + 3;
break;
case VPath::Element::Close:
close();
break;
}
}
end();
}
void FTOutline::convert(CapStyle cap, JoinStyle join, float width,
float miterLimit)
{
// map strokeWidth to freetype. It uses as the radius of the pen not the
// diameter
width = width / 2.0f;
// convert to freetype co-ordinate
// IMP: stroker takes radius in 26.6 co-ordinate
ftWidth = SW_FT_Fixed(width * (1 << 6));
// IMP: stroker takes meterlimit in 16.16 co-ordinate
ftMiterLimit = SW_FT_Fixed(miterLimit * (1 << 16));
// map to freetype capstyle
switch (cap) {
case CapStyle::Square:
ftCap = SW_FT_STROKER_LINECAP_SQUARE;
break;
case CapStyle::Round:
ftCap = SW_FT_STROKER_LINECAP_ROUND;
break;
default:
ftCap = SW_FT_STROKER_LINECAP_BUTT;
break;
}
switch (join) {
case JoinStyle::Bevel:
ftJoin = SW_FT_STROKER_LINEJOIN_BEVEL;
break;
case JoinStyle::Round:
ftJoin = SW_FT_STROKER_LINEJOIN_ROUND;
break;
default:
ftJoin = SW_FT_STROKER_LINEJOIN_MITER_FIXED;
break;
}
}
void FTOutline::moveTo(const VPointF &pt)
{
assert(ft.n_points <= SHRT_MAX - 1);
ft.points[ft.n_points].x = TO_FT_COORD(pt.x());
ft.points[ft.n_points].y = TO_FT_COORD(pt.y());
ft.tags[ft.n_points] = SW_FT_CURVE_TAG_ON;
if (ft.n_points) {
ft.contours[ft.n_contours] = ft.n_points - 1;
ft.n_contours++;
}
// mark the current contour as open
// will be updated if ther is a close tag at the end.
ft.contours_flag[ft.n_contours] = 1;
ft.n_points++;
}
void FTOutline::lineTo(const VPointF &pt)
{
assert(ft.n_points <= SHRT_MAX - 1);
ft.points[ft.n_points].x = TO_FT_COORD(pt.x());
ft.points[ft.n_points].y = TO_FT_COORD(pt.y());
ft.tags[ft.n_points] = SW_FT_CURVE_TAG_ON;
ft.n_points++;
}
void FTOutline::cubicTo(const VPointF &cp1, const VPointF &cp2,
const VPointF ep)
{
assert(ft.n_points <= SHRT_MAX - 3);
ft.points[ft.n_points].x = TO_FT_COORD(cp1.x());
ft.points[ft.n_points].y = TO_FT_COORD(cp1.y());
ft.tags[ft.n_points] = SW_FT_CURVE_TAG_CUBIC;
ft.n_points++;
ft.points[ft.n_points].x = TO_FT_COORD(cp2.x());
ft.points[ft.n_points].y = TO_FT_COORD(cp2.y());
ft.tags[ft.n_points] = SW_FT_CURVE_TAG_CUBIC;
ft.n_points++;
ft.points[ft.n_points].x = TO_FT_COORD(ep.x());
ft.points[ft.n_points].y = TO_FT_COORD(ep.y());
ft.tags[ft.n_points] = SW_FT_CURVE_TAG_ON;
ft.n_points++;
}
void FTOutline::close()
{
assert(ft.n_points <= SHRT_MAX - 1);
// mark the contour as a close path.
ft.contours_flag[ft.n_contours] = 0;
int index;
if (ft.n_contours) {
index = ft.contours[ft.n_contours - 1] + 1;
} else {
index = 0;
}
// make sure atleast 1 point exists in the segment.
if (ft.n_points == index) {
closed = false;
return;
}
ft.points[ft.n_points].x = ft.points[index].x;
ft.points[ft.n_points].y = ft.points[index].y;
ft.tags[ft.n_points] = SW_FT_CURVE_TAG_ON;
ft.n_points++;
}
void FTOutline::end()
{
assert(ft.n_contours <= SHRT_MAX - 1);
if (ft.n_points) {
ft.contours[ft.n_contours] = ft.n_points - 1;
ft.n_contours++;
}
}
static void rleGenerationCb(int count, const SW_FT_Span *spans, void *user)
{
VRle *rle = static_cast<VRle *>(user);
auto *rleSpan = reinterpret_cast<const VRle::Span *>(spans);
rle->addSpan(rleSpan, count);
}
static void bboxCb(int x, int y, int w, int h, void *user)
{
VRle *rle = static_cast<VRle *>(user);
rle->setBoundingRect({x, y, w, h});
}
class SharedRle {
public:
SharedRle() = default;
VRle &unsafe() { return _rle; }
void notify()
{
{
std::lock_guard<std::mutex> lock(_mutex);
_ready = true;
}
_cv.notify_one();
}
void wait()
{
if (!_pending) return;
{
std::unique_lock<std::mutex> lock(_mutex);
while (!_ready) _cv.wait(lock);
}
_pending = false;
}
VRle &get()
{
wait();
return _rle;
}
void reset()
{
wait();
_ready = false;
_pending = true;
}
private:
VRle _rle;
std::mutex _mutex;
std::condition_variable _cv;
bool _ready{true};
bool _pending{false};
};
struct VRleTask {
SharedRle mRle;
VPath mPath;
float mStrokeWidth;
float mMiterLimit;
VRect mClip;
FillRule mFillRule;
CapStyle mCap;
JoinStyle mJoin;
bool mGenerateStroke;
VRle &rle() { return mRle.get(); }
void update(VPath path, FillRule fillRule, const VRect &clip)
{
mRle.reset();
mPath = std::move(path);
mFillRule = fillRule;
mClip = clip;
mGenerateStroke = false;
}
void update(VPath path, CapStyle cap, JoinStyle join, float width,
float miterLimit, const VRect &clip)
{
mRle.reset();
mPath = std::move(path);
mCap = cap;
mJoin = join;
mStrokeWidth = width;
mMiterLimit = miterLimit;
mClip = clip;
mGenerateStroke = true;
}
void render(FTOutline &outRef)
{
SW_FT_Raster_Params params;
mRle.unsafe().reset();
params.flags = SW_FT_RASTER_FLAG_DIRECT | SW_FT_RASTER_FLAG_AA;
params.gray_spans = &rleGenerationCb;
params.bbox_cb = &bboxCb;
params.user = &mRle.unsafe();
params.source = &outRef.ft;
if (!mClip.empty()) {
params.flags |= SW_FT_RASTER_FLAG_CLIP;
params.clip_box.xMin = mClip.left();
params.clip_box.yMin = mClip.top();
params.clip_box.xMax = mClip.right();
params.clip_box.yMax = mClip.bottom();
}
// compute rle
sw_ft_grays_raster.raster_render(nullptr, ¶ms);
}
void operator()(FTOutline &outRef, SW_FT_Stroker &stroker)
{
if (mPath.points().size() > SHRT_MAX ||
mPath.points().size() + mPath.segments() > SHRT_MAX) {
return;
}
if (mGenerateStroke) { // Stroke Task
outRef.convert(mPath);
outRef.convert(mCap, mJoin, mStrokeWidth, mMiterLimit);
uint32_t points, contors;
SW_FT_Stroker_Set(stroker, outRef.ftWidth, outRef.ftCap,
outRef.ftJoin, outRef.ftMiterLimit);
SW_FT_Stroker_ParseOutline(stroker, &outRef.ft);
SW_FT_Stroker_GetCounts(stroker, (SW_FT_UInt *)&points,
(SW_FT_UInt *)&contors);
outRef.grow(points, contors);
SW_FT_Stroker_Export(stroker, &outRef.ft);
} else { // Fill Task
outRef.convert(mPath);
int fillRuleFlag = SW_FT_OUTLINE_NONE;
switch (mFillRule) {
case FillRule::EvenOdd:
fillRuleFlag = SW_FT_OUTLINE_EVEN_ODD_FILL;
break;
default:
fillRuleFlag = SW_FT_OUTLINE_NONE;
break;
}
outRef.ft.flags = fillRuleFlag;
}
render(outRef);
mPath = VPath();
mRle.notify();
}
};
using VTask = std::shared_ptr<VRleTask>;
#ifdef LOTTIE_THREAD_SUPPORT
#include <thread>
#include "vtaskqueue.h"
class RleTaskScheduler {
const unsigned _count{std::thread::hardware_concurrency()};
std::vector<std::thread> _threads;
std::vector<TaskQueue<VTask>> _q{_count};
std::atomic<unsigned> _index{0};
void run(unsigned i)
{
/*
* initalize per thread objects.
*/
FTOutline outlineRef;
SW_FT_Stroker stroker;
SW_FT_Stroker_New(&stroker);
// Task Loop
VTask task;
while (true) {
bool success = false;
for (unsigned n = 0; n != _count * 2; ++n) {
if (_q[(i + n) % _count].try_pop(task)) {
success = true;
break;
}
}
if (!success && !_q[i].pop(task)) break;
(*task)(outlineRef, stroker);
}
// cleanup
SW_FT_Stroker_Done(stroker);
}
RleTaskScheduler()
{
for (unsigned n = 0; n != _count; ++n) {
_threads.emplace_back([&, n] { run(n); });
}
IsRunning = true;
}
public:
static bool IsRunning;
static RleTaskScheduler &instance()
{
static RleTaskScheduler singleton;
return singleton;
}
~RleTaskScheduler() { stop(); }
void stop()
{
if (IsRunning) {
IsRunning = false;
for (auto &e : _q) e.done();
for (auto &e : _threads) e.join();
}
}
void process(VTask task)
{
auto i = _index++;
for (unsigned n = 0; n != _count; ++n) {
if (_q[(i + n) % _count].try_push(std::move(task))) return;
}
if (_count > 0) {
_q[i % _count].push(std::move(task));
}
}
};
#else
class RleTaskScheduler {
public:
FTOutline outlineRef{};
SW_FT_Stroker stroker;
public:
static bool IsRunning;
static RleTaskScheduler &instance()
{
static RleTaskScheduler singleton;
return singleton;
}
void stop() {}
RleTaskScheduler() { SW_FT_Stroker_New(&stroker); }
~RleTaskScheduler() { SW_FT_Stroker_Done(stroker); }
void process(VTask task) { (*task)(outlineRef, stroker); }
};
#endif
bool RleTaskScheduler::IsRunning{false};
struct VRasterizer::VRasterizerImpl {
VRleTask mTask;
VRle & rle() { return mTask.rle(); }
VRleTask &task() { return mTask; }
};
VRle VRasterizer::rle()
{
if (!d) return VRle();
return d->rle();
}
void VRasterizer::init()
{
if (!d) d = std::make_shared<VRasterizerImpl>();
}
void VRasterizer::updateRequest()
{
VTask taskObj = VTask(d, &d->task());
RleTaskScheduler::instance().process(std::move(taskObj));
}
void VRasterizer::rasterize(VPath path, FillRule fillRule, const VRect &clip)
{
init();
if (path.empty()) {
d->rle().reset();
return;
}
d->task().update(std::move(path), fillRule, clip);
updateRequest();
}
void VRasterizer::rasterize(VPath path, CapStyle cap, JoinStyle join,
float width, float miterLimit, const VRect &clip)
{
init();
if (path.empty() || vIsZero(width)) {
d->rle().reset();
return;
}
d->task().update(std::move(path), cap, join, width, miterLimit, clip);
updateRequest();
}
void lottieShutdownRasterTaskScheduler()
{
if (RleTaskScheduler::IsRunning) {
RleTaskScheduler::instance().stop();
}
}
V_END_NAMESPACE
| 15,087 | vraster | cpp | en | cpp | code | {"qsc_code_num_words": 1804, "qsc_code_num_chars": 15087.0, "qsc_code_mean_word_length": 4.74833703, "qsc_code_frac_words_unique": 0.21507761, "qsc_code_frac_chars_top_2grams": 0.02054635, "qsc_code_frac_chars_top_3grams": 0.03572262, "qsc_code_frac_chars_top_4grams": 0.01540976, "qsc_code_frac_chars_dupe_5grams": 0.27399019, "qsc_code_frac_chars_dupe_6grams": 0.22460892, "qsc_code_frac_chars_dupe_7grams": 0.19740836, "qsc_code_frac_chars_dupe_8grams": 0.16507121, "qsc_code_frac_chars_dupe_9grams": 0.14207331, "qsc_code_frac_chars_dupe_10grams": 0.13144992, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00653717, "qsc_code_frac_chars_whitespace": 0.29024988, "qsc_code_size_file_byte": 15087.0, "qsc_code_num_lines": 586.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 25.74573379, "qsc_code_frac_chars_alphabet": 0.79342548, "qsc_code_frac_chars_comments": 0.1148671, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.2021978, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00644002, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00022465, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.01098901, "qsc_codecpp_frac_lines_preprocessor_directives": 0.04395604, "qsc_codecpp_frac_lines_func_ratio": 0.06813187, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.12967033, "qsc_codecpp_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0} |
0015/T-Glass-Applications | image_capture_app/t_glass_ble_app/macos/Runner.xcodeproj/project.pbxproj | // !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objects = {
/* Begin PBXAggregateTarget section */
33CC111A2044C6BA0003C045 /* Flutter Assemble */ = {
isa = PBXAggregateTarget;
buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */;
buildPhases = (
33CC111E2044C6BF0003C045 /* ShellScript */,
);
dependencies = (
);
name = "Flutter Assemble";
productName = FLX;
};
/* End PBXAggregateTarget section */
/* Begin PBXBuildFile section */
331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; };
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; };
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; };
33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; };
33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; };
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; };
559B7804BDC2FA87E657BCF6 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DAF662976A781D0E526E20B /* Pods_Runner.framework */; };
AA053885EB0BEE54C0CE271F /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3D9D1B35953F64F75511ADF8 /* Pods_RunnerTests.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 33CC10E52044A3C60003C045 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 33CC10EC2044A3C60003C045;
remoteInfo = Runner;
};
33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 33CC10E52044A3C60003C045 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 33CC111A2044C6BA0003C045;
remoteInfo = FLX;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
33CC110E2044A8840003C045 /* Bundle Framework */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
);
name = "Bundle Framework";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
24514A463BF6B3C5AA55D33E /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = "<group>"; };
331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };
333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = "<group>"; };
335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = "<group>"; };
33CC10ED2044A3C60003C045 /* t_glass_ble_app.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = t_glass_ble_app.app; sourceTree = BUILT_PRODUCTS_DIR; };
33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = "<group>"; };
33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = "<group>"; };
33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = "<group>"; };
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = "<group>"; };
33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = "<group>"; };
33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = "<group>"; };
33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = "<group>"; };
33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = "<group>"; };
33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = "<group>"; };
33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = "<group>"; };
3D9D1B35953F64F75511ADF8 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
5DAF662976A781D0E526E20B /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
6362AA39570EE4254AEB0A6A /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = "<group>"; };
79146CABF326332EAD41AE4E /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = "<group>"; };
897C61EF367C3C0B7B4586B6 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = "<group>"; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = "<group>"; };
A886A26D2E65235E67BE6EC7 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
E20E1E8077857A6D93C188A1 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
331C80D2294CF70F00263BE5 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
AA053885EB0BEE54C0CE271F /* Pods_RunnerTests.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
33CC10EA2044A3C60003C045 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
559B7804BDC2FA87E657BCF6 /* Pods_Runner.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
331C80D6294CF71000263BE5 /* RunnerTests */ = {
isa = PBXGroup;
children = (
331C80D7294CF71000263BE5 /* RunnerTests.swift */,
);
path = RunnerTests;
sourceTree = "<group>";
};
33BA886A226E78AF003329D5 /* Configs */ = {
isa = PBXGroup;
children = (
33E5194F232828860026EE4D /* AppInfo.xcconfig */,
9740EEB21CF90195004384FC /* Debug.xcconfig */,
7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
333000ED22D3DE5D00554162 /* Warnings.xcconfig */,
);
path = Configs;
sourceTree = "<group>";
};
33CC10E42044A3C60003C045 = {
isa = PBXGroup;
children = (
33FAB671232836740065AC1E /* Runner */,
33CEB47122A05771004F2AC0 /* Flutter */,
331C80D6294CF71000263BE5 /* RunnerTests */,
33CC10EE2044A3C60003C045 /* Products */,
D73912EC22F37F3D000D13A0 /* Frameworks */,
8B64B0F62B76E1395F15DBA7 /* Pods */,
);
sourceTree = "<group>";
};
33CC10EE2044A3C60003C045 /* Products */ = {
isa = PBXGroup;
children = (
33CC10ED2044A3C60003C045 /* t_glass_ble_app.app */,
331C80D5294CF71000263BE5 /* RunnerTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
33CC11242044D66E0003C045 /* Resources */ = {
isa = PBXGroup;
children = (
33CC10F22044A3C60003C045 /* Assets.xcassets */,
33CC10F42044A3C60003C045 /* MainMenu.xib */,
33CC10F72044A3C60003C045 /* Info.plist */,
);
name = Resources;
path = ..;
sourceTree = "<group>";
};
33CEB47122A05771004F2AC0 /* Flutter */ = {
isa = PBXGroup;
children = (
335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */,
33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */,
33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */,
33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */,
);
path = Flutter;
sourceTree = "<group>";
};
33FAB671232836740065AC1E /* Runner */ = {
isa = PBXGroup;
children = (
33CC10F02044A3C60003C045 /* AppDelegate.swift */,
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,
33E51913231747F40026EE4D /* DebugProfile.entitlements */,
33E51914231749380026EE4D /* Release.entitlements */,
33CC11242044D66E0003C045 /* Resources */,
33BA886A226E78AF003329D5 /* Configs */,
);
path = Runner;
sourceTree = "<group>";
};
8B64B0F62B76E1395F15DBA7 /* Pods */ = {
isa = PBXGroup;
children = (
E20E1E8077857A6D93C188A1 /* Pods-Runner.debug.xcconfig */,
79146CABF326332EAD41AE4E /* Pods-Runner.release.xcconfig */,
A886A26D2E65235E67BE6EC7 /* Pods-Runner.profile.xcconfig */,
897C61EF367C3C0B7B4586B6 /* Pods-RunnerTests.debug.xcconfig */,
24514A463BF6B3C5AA55D33E /* Pods-RunnerTests.release.xcconfig */,
6362AA39570EE4254AEB0A6A /* Pods-RunnerTests.profile.xcconfig */,
);
name = Pods;
path = Pods;
sourceTree = "<group>";
};
D73912EC22F37F3D000D13A0 /* Frameworks */ = {
isa = PBXGroup;
children = (
5DAF662976A781D0E526E20B /* Pods_Runner.framework */,
3D9D1B35953F64F75511ADF8 /* Pods_RunnerTests.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
331C80D4294CF70F00263BE5 /* RunnerTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */;
buildPhases = (
E63F93F0E5F7499928EBA683 /* [CP] Check Pods Manifest.lock */,
331C80D1294CF70F00263BE5 /* Sources */,
331C80D2294CF70F00263BE5 /* Frameworks */,
331C80D3294CF70F00263BE5 /* Resources */,
);
buildRules = (
);
dependencies = (
331C80DA294CF71000263BE5 /* PBXTargetDependency */,
);
name = RunnerTests;
productName = RunnerTests;
productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
33CC10EC2044A3C60003C045 /* Runner */ = {
isa = PBXNativeTarget;
buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */;
buildPhases = (
C9C04D6DEEA4F9D74D0B6AFC /* [CP] Check Pods Manifest.lock */,
33CC10E92044A3C60003C045 /* Sources */,
33CC10EA2044A3C60003C045 /* Frameworks */,
33CC10EB2044A3C60003C045 /* Resources */,
33CC110E2044A8840003C045 /* Bundle Framework */,
3399D490228B24CF009A79C7 /* ShellScript */,
82EE4522C320B3CCC43F3C01 /* [CP] Embed Pods Frameworks */,
);
buildRules = (
);
dependencies = (
33CC11202044C79F0003C045 /* PBXTargetDependency */,
);
name = Runner;
productName = Runner;
productReference = 33CC10ED2044A3C60003C045 /* t_glass_ble_app.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
33CC10E52044A3C60003C045 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0920;
LastUpgradeCheck = 1510;
ORGANIZATIONNAME = "";
TargetAttributes = {
331C80D4294CF70F00263BE5 = {
CreatedOnToolsVersion = 14.0;
TestTargetID = 33CC10EC2044A3C60003C045;
};
33CC10EC2044A3C60003C045 = {
CreatedOnToolsVersion = 9.2;
LastSwiftMigration = 1100;
ProvisioningStyle = Automatic;
SystemCapabilities = {
com.apple.Sandbox = {
enabled = 1;
};
};
};
33CC111A2044C6BA0003C045 = {
CreatedOnToolsVersion = 9.2;
ProvisioningStyle = Manual;
};
};
};
buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 33CC10E42044A3C60003C045;
productRefGroup = 33CC10EE2044A3C60003C045 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
33CC10EC2044A3C60003C045 /* Runner */,
331C80D4294CF70F00263BE5 /* RunnerTests */,
33CC111A2044C6BA0003C045 /* Flutter Assemble */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
331C80D3294CF70F00263BE5 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
33CC10EB2044A3C60003C045 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */,
33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
3399D490228B24CF009A79C7 /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n";
};
33CC111E2044C6BF0003C045 /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
Flutter/ephemeral/FlutterInputs.xcfilelist,
);
inputPaths = (
Flutter/ephemeral/tripwire,
);
outputFileListPaths = (
Flutter/ephemeral/FlutterOutputs.xcfilelist,
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire";
};
82EE4522C320B3CCC43F3C01 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
C9C04D6DEEA4F9D74D0B6AFC /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
E63F93F0E5F7499928EBA683 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
331C80D1294CF70F00263BE5 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
33CC10E92044A3C60003C045 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */,
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */,
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
331C80DA294CF71000263BE5 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 33CC10EC2044A3C60003C045 /* Runner */;
targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */;
};
33CC11202044C79F0003C045 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */;
targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
33CC10F42044A3C60003C045 /* MainMenu.xib */ = {
isa = PBXVariantGroup;
children = (
33CC10F52044A3C60003C045 /* Base */,
);
name = MainMenu.xib;
path = Runner;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
331C80DB294CF71000263BE5 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 897C61EF367C3C0B7B4586B6 /* Pods-RunnerTests.debug.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.thatproject.tGlassBleApp.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/t_glass_ble_app.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/t_glass_ble_app";
};
name = Debug;
};
331C80DC294CF71000263BE5 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 24514A463BF6B3C5AA55D33E /* Pods-RunnerTests.release.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.thatproject.tGlassBleApp.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/t_glass_ble_app.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/t_glass_ble_app";
};
name = Release;
};
331C80DD294CF71000263BE5 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 6362AA39570EE4254AEB0A6A /* Pods-RunnerTests.profile.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.thatproject.tGlassBleApp.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/t_glass_ble_app.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/t_glass_ble_app";
};
name = Profile;
};
338D0CE9231458BD00FA5F75 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CODE_SIGN_IDENTITY = "-";
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.14;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Profile;
};
338D0CEA231458BD00FA5F75 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_VERSION = 5.0;
};
name = Profile;
};
338D0CEB231458BD00FA5F75 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Manual;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Profile;
};
33CC10F92044A3C60003C045 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CODE_SIGN_IDENTITY = "-";
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.14;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
33CC10FA2044A3C60003C045 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CODE_SIGN_IDENTITY = "-";
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.14;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
33CC10FC2044A3C60003C045 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
};
name = Debug;
};
33CC10FD2044A3C60003C045 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_VERSION = 5.0;
};
name = Release;
};
33CC111C2044C6BA0003C045 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Manual;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
};
33CC111D2044C6BA0003C045 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
331C80DB294CF71000263BE5 /* Debug */,
331C80DC294CF71000263BE5 /* Release */,
331C80DD294CF71000263BE5 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
33CC10F92044A3C60003C045 /* Debug */,
33CC10FA2044A3C60003C045 /* Release */,
338D0CE9231458BD00FA5F75 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
33CC10FC2044A3C60003C045 /* Debug */,
33CC10FD2044A3C60003C045 /* Release */,
338D0CEA231458BD00FA5F75 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = {
isa = XCConfigurationList;
buildConfigurations = (
33CC111C2044C6BA0003C045 /* Debug */,
33CC111D2044C6BA0003C045 /* Release */,
338D0CEB231458BD00FA5F75 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 33CC10E52044A3C60003C045 /* Project object */;
}
| 32,966 | project | pbxproj | en | unknown | unknown | {} | 0 | {} |
0015/esp_rlottie | rlottie/src/vector/vdrawhelper.cpp | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
* 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.
*/
#include "vdrawhelper.h"
#include <algorithm>
#include <climits>
#include <cstring>
#include <mutex>
#include <unordered_map>
#include <array>
static RenderFuncTable RenderTable;
void VTextureData::setClip(const VRect &clip)
{
left = clip.left();
top = clip.top();
right = std::min(clip.right(), int(width())) - 1;
bottom = std::min(clip.bottom(), int(height())) - 1;
}
class VGradientCache {
public:
struct CacheInfo : public VColorTable {
inline CacheInfo(VGradientStops s) : stops(std::move(s)) {}
VGradientStops stops;
};
using VCacheData = std::shared_ptr<const CacheInfo>;
using VCacheKey = int64_t;
using VGradientColorTableHash =
std::unordered_multimap<VCacheKey, VCacheData>;
bool generateGradientColorTable(const VGradientStops &stops, float alpha,
uint32_t *colorTable, int size);
VCacheData getBuffer(const VGradient &gradient)
{
VCacheKey hash_val = 0;
VCacheData info;
const VGradientStops &stops = gradient.mStops;
for (uint32_t i = 0; i < stops.size() && i <= 2; i++)
hash_val +=
VCacheKey(stops[i].second.premulARGB() * gradient.alpha());
{
std::lock_guard<std::mutex> guard(mMutex);
size_t count = mCache.count(hash_val);
if (!count) {
// key is not present in the hash
info = addCacheElement(hash_val, gradient);
} else if (count == 1) {
auto search = mCache.find(hash_val);
if (search->second->stops == stops) {
info = search->second;
} else {
// didn't find an exact match
info = addCacheElement(hash_val, gradient);
}
} else {
// we have a multiple data with same key
auto range = mCache.equal_range(hash_val);
for (auto it = range.first; it != range.second; ++it) {
if (it->second->stops == stops) {
info = it->second;
break;
}
}
if (!info) {
// didn't find an exact match
info = addCacheElement(hash_val, gradient);
}
}
}
return info;
}
static VGradientCache &instance()
{
static VGradientCache CACHE;
return CACHE;
}
protected:
uint32_t maxCacheSize() const { return 60; }
VCacheData addCacheElement(VCacheKey hash_val, const VGradient &gradient)
{
if (mCache.size() == maxCacheSize()) {
uint32_t count = maxCacheSize() / 10;
while (count--) {
mCache.erase(mCache.begin());
}
}
auto cache_entry = std::make_shared<CacheInfo>(gradient.mStops);
cache_entry->alpha = generateGradientColorTable(
gradient.mStops, gradient.alpha(), cache_entry->buffer32,
VGradient::colorTableSize);
mCache.insert(std::make_pair(hash_val, cache_entry));
return cache_entry;
}
private:
VGradientCache() = default;
VGradientColorTableHash mCache;
std::mutex mMutex;
};
bool VGradientCache::generateGradientColorTable(const VGradientStops &stops,
float opacity,
uint32_t *colorTable, int size)
{
int dist, idist, pos = 0;
size_t i;
bool alpha = false;
size_t stopCount = stops.size();
const VGradientStop *curr, *next, *start;
uint32_t curColor, nextColor;
float delta, t, incr, fpos;
if (!vCompare(opacity, 1.0f)) alpha = true;
start = stops.data();
curr = start;
if (!curr->second.isOpaque()) alpha = true;
curColor = curr->second.premulARGB(opacity);
incr = 1.0f / (float)size;
fpos = 1.5f * incr;
colorTable[pos++] = curColor;
while (fpos <= curr->first && pos < size) {
colorTable[pos] = colorTable[pos - 1];
pos++;
fpos += incr;
}
for (i = 0; i < stopCount - 1; ++i) {
curr = (start + i);
next = (start + i + 1);
delta = 1 / (next->first - curr->first);
if (!next->second.isOpaque()) alpha = true;
nextColor = next->second.premulARGB(opacity);
while (fpos < next->first && pos < size) {
t = (fpos - curr->first) * delta;
dist = (int)(255 * t);
idist = 255 - dist;
colorTable[pos] =
interpolate_pixel(curColor, idist, nextColor, dist);
++pos;
fpos += incr;
}
curColor = nextColor;
}
for (; pos < size; ++pos) colorTable[pos] = curColor;
// Make sure the last color stop is represented at the end of the table
colorTable[size - 1] = curColor;
return alpha;
}
void VRasterBuffer::clear()
{
memset(mBuffer, 0, mHeight * mBytesPerLine);
}
VBitmap::Format VRasterBuffer::prepare(const VBitmap *image)
{
mBuffer = image->data();
mWidth = image->width();
mHeight = image->height();
mBytesPerPixel = 4;
mBytesPerLine = image->stride();
mFormat = image->format();
return mFormat;
}
void VSpanData::init(VRasterBuffer *image)
{
mRasterBuffer = image;
setDrawRegion(VRect(0, 0, int(image->width()), int(image->height())));
mType = VSpanData::Type::None;
mBlendFunc = nullptr;
mUnclippedBlendFunc = nullptr;
}
/*
* Gradient Draw routines
*
*/
#define FIXPT_BITS 8
#define FIXPT_SIZE (1 << FIXPT_BITS)
static inline void getLinearGradientValues(LinearGradientValues *v,
const VSpanData * data)
{
const VGradientData *grad = &data->mGradient;
v->dx = grad->linear.x2 - grad->linear.x1;
v->dy = grad->linear.y2 - grad->linear.y1;
v->l = v->dx * v->dx + v->dy * v->dy;
v->off = 0;
if (v->l != 0) {
v->dx /= v->l;
v->dy /= v->l;
v->off = -v->dx * grad->linear.x1 - v->dy * grad->linear.y1;
}
}
static inline void getRadialGradientValues(RadialGradientValues *v,
const VSpanData * data)
{
const VGradientData &gradient = data->mGradient;
v->dx = gradient.radial.cx - gradient.radial.fx;
v->dy = gradient.radial.cy - gradient.radial.fy;
v->dr = gradient.radial.cradius - gradient.radial.fradius;
v->sqrfr = gradient.radial.fradius * gradient.radial.fradius;
v->a = v->dr * v->dr - v->dx * v->dx - v->dy * v->dy;
v->inv2a = 1 / (2 * v->a);
v->extended = !vIsZero(gradient.radial.fradius) || v->a <= 0;
}
static inline int gradientClamp(const VGradientData *grad, int ipos)
{
int limit;
if (grad->mSpread == VGradient::Spread::Repeat) {
ipos = ipos % VGradient::colorTableSize;
ipos = ipos < 0 ? VGradient::colorTableSize + ipos : ipos;
} else if (grad->mSpread == VGradient::Spread::Reflect) {
limit = VGradient::colorTableSize * 2;
ipos = ipos % limit;
ipos = ipos < 0 ? limit + ipos : ipos;
ipos = ipos >= VGradient::colorTableSize ? limit - 1 - ipos : ipos;
} else {
if (ipos < 0)
ipos = 0;
else if (ipos >= VGradient::colorTableSize)
ipos = VGradient::colorTableSize - 1;
}
return ipos;
}
static uint32_t gradientPixelFixed(const VGradientData *grad, int fixed_pos)
{
int ipos = (fixed_pos + (FIXPT_SIZE / 2)) >> FIXPT_BITS;
return grad->mColorTable[gradientClamp(grad, ipos)];
}
static inline uint32_t gradientPixel(const VGradientData *grad, float pos)
{
int ipos = (int)(pos * (VGradient::colorTableSize - 1) + (float)(0.5));
return grad->mColorTable[gradientClamp(grad, ipos)];
}
void fetch_linear_gradient(uint32_t *buffer, const Operator *op,
const VSpanData *data, int y, int x, int length)
{
float t, inc;
const VGradientData *gradient = &data->mGradient;
bool affine = true;
float rx = 0, ry = 0;
if (op->linear.l == 0) {
t = inc = 0;
} else {
rx = data->m21 * (y + float(0.5)) + data->m11 * (x + float(0.5)) +
data->dx;
ry = data->m22 * (y + float(0.5)) + data->m12 * (x + float(0.5)) +
data->dy;
t = op->linear.dx * rx + op->linear.dy * ry + op->linear.off;
inc = op->linear.dx * data->m11 + op->linear.dy * data->m12;
affine = !data->m13 && !data->m23;
if (affine) {
t *= (VGradient::colorTableSize - 1);
inc *= (VGradient::colorTableSize - 1);
}
}
const uint32_t *end = buffer + length;
if (affine) {
if (inc > float(-1e-5) && inc < float(1e-5)) {
memfill32(buffer, gradientPixelFixed(gradient, int(t * FIXPT_SIZE)),
length);
} else {
if (t + inc * length < float(INT_MAX >> (FIXPT_BITS + 1)) &&
t + inc * length > float(INT_MIN >> (FIXPT_BITS + 1))) {
// we can use fixed point math
int t_fixed = int(t * FIXPT_SIZE);
int inc_fixed = int(inc * FIXPT_SIZE);
while (buffer < end) {
*buffer = gradientPixelFixed(gradient, t_fixed);
t_fixed += inc_fixed;
++buffer;
}
} else {
// we have to fall back to float math
while (buffer < end) {
*buffer =
gradientPixel(gradient, t / VGradient::colorTableSize);
t += inc;
++buffer;
}
}
}
} else { // fall back to float math here as well
float rw = data->m23 * (y + float(0.5)) + data->m13 * (x + float(0.5)) +
data->m33;
while (buffer < end) {
float xt = rx / rw;
float yt = ry / rw;
t = (op->linear.dx * xt + op->linear.dy * yt) + op->linear.off;
*buffer = gradientPixel(gradient, t);
rx += data->m11;
ry += data->m12;
rw += data->m13;
if (!rw) {
rw += data->m13;
}
++buffer;
}
}
}
static inline float radialDeterminant(float a, float b, float c)
{
return (b * b) - (4 * a * c);
}
static void fetch(uint32_t *buffer, uint32_t *end, const Operator *op,
const VSpanData *data, float det, float delta_det,
float delta_delta_det, float b, float delta_b)
{
if (op->radial.extended) {
while (buffer < end) {
uint32_t result = 0;
if (det >= 0) {
float w = std::sqrt(det) - b;
if (data->mGradient.radial.fradius + op->radial.dr * w >= 0)
result = gradientPixel(&data->mGradient, w);
}
*buffer = result;
det += delta_det;
delta_det += delta_delta_det;
b += delta_b;
++buffer;
}
} else {
while (buffer < end) {
*buffer++ = gradientPixel(&data->mGradient, std::sqrt(det) - b);
det += delta_det;
delta_det += delta_delta_det;
b += delta_b;
}
}
}
void fetch_radial_gradient(uint32_t *buffer, const Operator *op,
const VSpanData *data, int y, int x, int length)
{
// avoid division by zero
if (vIsZero(op->radial.a)) {
memfill32(buffer, 0, length);
return;
}
float rx =
data->m21 * (y + float(0.5)) + data->dx + data->m11 * (x + float(0.5));
float ry =
data->m22 * (y + float(0.5)) + data->dy + data->m12 * (x + float(0.5));
bool affine = !data->m13 && !data->m23;
uint32_t *end = buffer + length;
if (affine) {
rx -= data->mGradient.radial.fx;
ry -= data->mGradient.radial.fy;
float inv_a = 1 / float(2 * op->radial.a);
const float delta_rx = data->m11;
const float delta_ry = data->m12;
float b = 2 * (op->radial.dr * data->mGradient.radial.fradius +
rx * op->radial.dx + ry * op->radial.dy);
float delta_b =
2 * (delta_rx * op->radial.dx + delta_ry * op->radial.dy);
const float b_delta_b = 2 * b * delta_b;
const float delta_b_delta_b = 2 * delta_b * delta_b;
const float bb = b * b;
const float delta_bb = delta_b * delta_b;
b *= inv_a;
delta_b *= inv_a;
const float rxrxryry = rx * rx + ry * ry;
const float delta_rxrxryry = delta_rx * delta_rx + delta_ry * delta_ry;
const float rx_plus_ry = 2 * (rx * delta_rx + ry * delta_ry);
const float delta_rx_plus_ry = 2 * delta_rxrxryry;
inv_a *= inv_a;
float det =
(bb - 4 * op->radial.a * (op->radial.sqrfr - rxrxryry)) * inv_a;
float delta_det = (b_delta_b + delta_bb +
4 * op->radial.a * (rx_plus_ry + delta_rxrxryry)) *
inv_a;
const float delta_delta_det =
(delta_b_delta_b + 4 * op->radial.a * delta_rx_plus_ry) * inv_a;
fetch(buffer, end, op, data, det, delta_det, delta_delta_det, b,
delta_b);
} else {
float rw = data->m23 * (y + float(0.5)) + data->m33 +
data->m13 * (x + float(0.5));
while (buffer < end) {
if (rw == 0) {
*buffer = 0;
} else {
float invRw = 1 / rw;
float gx = rx * invRw - data->mGradient.radial.fx;
float gy = ry * invRw - data->mGradient.radial.fy;
float b = 2 * (op->radial.dr * data->mGradient.radial.fradius +
gx * op->radial.dx + gy * op->radial.dy);
float det = radialDeterminant(
op->radial.a, b, op->radial.sqrfr - (gx * gx + gy * gy));
uint32_t result = 0;
if (det >= 0) {
float detSqrt = std::sqrt(det);
float s0 = (-b - detSqrt) * op->radial.inv2a;
float s1 = (-b + detSqrt) * op->radial.inv2a;
float s = vMax(s0, s1);
if (data->mGradient.radial.fradius + op->radial.dr * s >= 0)
result = gradientPixel(&data->mGradient, s);
}
*buffer = result;
}
rx += data->m11;
ry += data->m12;
rw += data->m13;
++buffer;
}
}
}
static inline Operator getOperator(const VSpanData *data)
{
Operator op;
bool solidSource = false;
switch (data->mType) {
case VSpanData::Type::Solid:
solidSource = (vAlpha(data->mSolid) == 255);
op.srcFetch = nullptr;
break;
case VSpanData::Type::LinearGradient:
solidSource = false;
getLinearGradientValues(&op.linear, data);
op.srcFetch = &fetch_linear_gradient;
break;
case VSpanData::Type::RadialGradient:
solidSource = false;
getRadialGradientValues(&op.radial, data);
op.srcFetch = &fetch_radial_gradient;
break;
default:
op.srcFetch = nullptr;
break;
}
op.mode = data->mBlendMode;
if (op.mode == BlendMode::SrcOver && solidSource) op.mode = BlendMode::Src;
op.funcSolid = RenderTable.color(op.mode);
op.func = RenderTable.src(op.mode);
return op;
}
static void blend_color(size_t size, const VRle::Span *array, void *userData)
{
VSpanData *data = (VSpanData *)(userData);
Operator op = getOperator(data);
const uint32_t color = data->mSolid;
for (size_t i = 0 ; i < size; ++i) {
const auto &span = array[i];
op.funcSolid(data->buffer(span.x, span.y), span.len, color, span.coverage);
}
}
// Signature of Process Object
// void Pocess(uint* scratchBuffer, size_t x, size_t y, uint8_t cov)
template <class Process>
static inline void process_in_chunk(const VRle::Span *array, size_t size,
Process process)
{
std::array<uint32_t, 2048> buf;
for (size_t i = 0; i < size; i++) {
const auto &span = array[i];
size_t len = span.len;
auto x = span.x;
while (len) {
auto l = std::min(len, buf.size());
process(buf.data(), x, span.y, l, span.coverage);
x += l;
len -= l;
}
}
}
static void blend_gradient(size_t size, const VRle::Span *array,
void *userData)
{
VSpanData *data = (VSpanData *)(userData);
Operator op = getOperator(data);
if (!op.srcFetch) return;
process_in_chunk(
array, size,
[&](uint32_t *scratch, size_t x, size_t y, size_t len, uint8_t cov) {
op.srcFetch(scratch, &op, data, (int)y, (int)x, (int)len);
op.func(data->buffer((int)x, (int)y), (int)len, scratch, cov);
});
}
template <class T>
constexpr const T &clamp(const T &v, const T &lo, const T &hi)
{
return v < lo ? lo : hi < v ? hi : v;
}
static constexpr inline uint8_t alpha_mul(uint8_t a, uint8_t b)
{
return ((a * b) >> 8);
}
static void blend_image_xform(size_t size, const VRle::Span *array,
void *userData)
{
const auto data = reinterpret_cast<const VSpanData *>(userData);
const auto &src = data->texture();
if (src.format() != VBitmap::Format::ARGB32_Premultiplied &&
src.format() != VBitmap::Format::ARGB32) {
//@TODO other formats not yet handled.
return;
}
Operator op = getOperator(data);
process_in_chunk(
array, size,
[&](uint32_t *scratch, size_t x, size_t y, size_t len, uint8_t cov) {
const auto coverage = (cov * src.alpha()) >> 8;
const float xfactor = y * data->m21 + data->dx + data->m11;
const float yfactor = y * data->m22 + data->dy + data->m12;
for (size_t i = 0; i < len; i++) {
const float fx = (x + i) * data->m11 + xfactor;
const float fy = (x + i) * data->m12 + yfactor;
const int px = clamp(int(fx), src.left, src.right);
const int py = clamp(int(fy), src.top, src.bottom);
scratch[i] = src.pixel(px, py);
}
op.func(data->buffer((int)x, (int)y), (int)len, scratch, coverage);
});
}
static void blend_image(size_t size, const VRle::Span *array, void *userData)
{
const auto data = reinterpret_cast<const VSpanData *>(userData);
const auto &src = data->texture();
if (src.format() != VBitmap::Format::ARGB32_Premultiplied &&
src.format() != VBitmap::Format::ARGB32) {
//@TODO other formats not yet handled.
return;
}
Operator op = getOperator(data);
for (size_t i = 0; i < size; i++) {
const auto &span = array[i];
int x = span.x;
int length = span.len;
int sx = x + int(data->dx);
int sy = span.y + int(data->dy);
// notyhing to copy.
if (sy < 0 || sy >= int(src.height()) || sx >= int(src.width()) ||
(sx + length) <= 0)
continue;
// intersecting left edge of image
if (sx < 0) {
x -= sx;
length += sx;
sx = 0;
}
// intersecting right edge of image
if (sx + length > int(src.width())) length = (int)src.width() - sx;
op.func(data->buffer(x, span.y), length, src.pixelRef(sx, sy),
alpha_mul(span.coverage, src.alpha()));
}
}
void VSpanData::setup(const VBrush &brush, BlendMode /*mode*/, int /*alpha*/)
{
transformType = VMatrix::MatrixType::None;
switch (brush.type()) {
case VBrush::Type::NoBrush:
mType = VSpanData::Type::None;
break;
case VBrush::Type::Solid:
mType = VSpanData::Type::Solid;
mSolid = brush.mColor.premulARGB();
break;
case VBrush::Type::LinearGradient: {
mType = VSpanData::Type::LinearGradient;
mColorTable = VGradientCache::instance().getBuffer(*brush.mGradient);
mGradient.mColorTable = mColorTable->buffer32;
mGradient.mColorTableAlpha = mColorTable->alpha;
mGradient.linear.x1 = brush.mGradient->linear.x1;
mGradient.linear.y1 = brush.mGradient->linear.y1;
mGradient.linear.x2 = brush.mGradient->linear.x2;
mGradient.linear.y2 = brush.mGradient->linear.y2;
mGradient.mSpread = brush.mGradient->mSpread;
setupMatrix(brush.mGradient->mMatrix);
break;
}
case VBrush::Type::RadialGradient: {
mType = VSpanData::Type::RadialGradient;
mColorTable = VGradientCache::instance().getBuffer(*brush.mGradient);
mGradient.mColorTable = mColorTable->buffer32;
mGradient.mColorTableAlpha = mColorTable->alpha;
mGradient.radial.cx = brush.mGradient->radial.cx;
mGradient.radial.cy = brush.mGradient->radial.cy;
mGradient.radial.fx = brush.mGradient->radial.fx;
mGradient.radial.fy = brush.mGradient->radial.fy;
mGradient.radial.cradius = brush.mGradient->radial.cradius;
mGradient.radial.fradius = brush.mGradient->radial.fradius;
mGradient.mSpread = brush.mGradient->mSpread;
setupMatrix(brush.mGradient->mMatrix);
break;
}
case VBrush::Type::Texture: {
mType = VSpanData::Type::Texture;
initTexture(&brush.mTexture->mBitmap, brush.mTexture->mAlpha,
brush.mTexture->mBitmap.rect());
setupMatrix(brush.mTexture->mMatrix);
break;
}
default:
break;
}
updateSpanFunc();
}
void VSpanData::setupMatrix(const VMatrix &matrix)
{
VMatrix inv = matrix.inverted();
m11 = inv.m11;
m12 = inv.m12;
m13 = inv.m13;
m21 = inv.m21;
m22 = inv.m22;
m23 = inv.m23;
m33 = inv.m33;
dx = inv.mtx;
dy = inv.mty;
transformType = inv.type();
const bool affine = inv.isAffine();
const float f1 = m11 * m11 + m21 * m21;
const float f2 = m12 * m12 + m22 * m22;
fast_matrix = affine && f1 < 1e4 && f2 < 1e4 && f1 > (1.0 / 65536) &&
f2 > (1.0 / 65536) && fabs(dx) < 1e4 && fabs(dy) < 1e4;
}
void VSpanData::initTexture(const VBitmap *bitmap, int alpha,
const VRect &sourceRect)
{
mType = VSpanData::Type::Texture;
mTexture.prepare(bitmap);
mTexture.setClip(sourceRect);
mTexture.setAlpha(alpha);
updateSpanFunc();
}
void VSpanData::updateSpanFunc()
{
switch (mType) {
case VSpanData::Type::None:
mUnclippedBlendFunc = nullptr;
break;
case VSpanData::Type::Solid:
mUnclippedBlendFunc = &blend_color;
break;
case VSpanData::Type::LinearGradient:
case VSpanData::Type::RadialGradient: {
mUnclippedBlendFunc = &blend_gradient;
break;
}
case VSpanData::Type::Texture: {
//@TODO update proper image function.
if (transformType <= VMatrix::MatrixType::Translate) {
mUnclippedBlendFunc = &blend_image;
} else {
mUnclippedBlendFunc = &blend_image_xform;
}
break;
}
}
}
#if !defined(__SSE2__) && !defined(__ARM_NEON__)
void memfill32(uint32_t *dest, uint32_t value, int length)
{
// let compiler do the auto vectorization.
for (int i = 0 ; i < length; i++) {
*dest++ = value;
}
}
#endif
| 25,053 | vdrawhelper | cpp | en | cpp | code | {"qsc_code_num_words": 2871, "qsc_code_num_chars": 25053.0, "qsc_code_mean_word_length": 4.70323929, "qsc_code_frac_words_unique": 0.16440265, "qsc_code_frac_chars_top_2grams": 0.01140487, "qsc_code_frac_chars_top_3grams": 0.00673924, "qsc_code_frac_chars_top_4grams": 0.0073317, "qsc_code_frac_chars_dupe_5grams": 0.27727172, "qsc_code_frac_chars_dupe_6grams": 0.2070651, "qsc_code_frac_chars_dupe_7grams": 0.1740354, "qsc_code_frac_chars_dupe_8grams": 0.16588906, "qsc_code_frac_chars_dupe_9grams": 0.15033696, "qsc_code_frac_chars_dupe_10grams": 0.13826557, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02173399, "qsc_code_frac_chars_whitespace": 0.3241528, "qsc_code_size_file_byte": 25053.0, "qsc_code_num_lines": 766.0, "qsc_code_num_chars_line_max": 84.0, "qsc_code_num_chars_line_mean": 32.70626632, "qsc_code_frac_chars_alphabet": 0.77575006, "qsc_code_frac_chars_comments": 0.07563964, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.2128, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00056139, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.00391645, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.024, "qsc_codecpp_frac_lines_func_ratio": 0.0352, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.0656, "qsc_codecpp_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/vector/vdrawhelper_common.cpp | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
* 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.
*/
#include <cstring>
#include "vdrawhelper.h"
/*
result = s
dest = s * ca + d * cia
*/
static void color_Source(uint32_t *dest, int length, uint32_t color,
uint32_t alpha)
{
int ialpha, i;
if (alpha == 255) {
memfill32(dest, color, length);
} else {
ialpha = 255 - alpha;
color = BYTE_MUL(color, alpha);
for (i = 0; i < length; ++i)
dest[i] = color + BYTE_MUL(dest[i], ialpha);
}
}
/*
r = s + d * sia
dest = r * ca + d * cia
= (s + d * sia) * ca + d * cia
= s * ca + d * (sia * ca + cia)
= s * ca + d * (1 - sa*ca)
= s' + d ( 1 - s'a)
*/
static void color_SourceOver(uint32_t *dest, int length, uint32_t color,
uint32_t alpha)
{
int ialpha, i;
if (alpha != 255) color = BYTE_MUL(color, alpha);
ialpha = 255 - vAlpha(color);
for (i = 0; i < length; ++i) dest[i] = color + BYTE_MUL(dest[i], ialpha);
}
/*
result = d * sa
dest = d * sa * ca + d * cia
= d * (sa * ca + cia)
*/
static void color_DestinationIn(uint32_t *dest, int length, uint32_t color,
uint32_t alpha)
{
uint32_t a = vAlpha(color);
if (alpha != 255) {
a = BYTE_MUL(a, alpha) + 255 - alpha;
}
for (int i = 0; i < length; ++i) {
dest[i] = BYTE_MUL(dest[i], a);
}
}
/*
result = d * sia
dest = d * sia * ca + d * cia
= d * (sia * ca + cia)
*/
static void color_DestinationOut(uint32_t *dest, int length, uint32_t color,
uint32_t alpha)
{
uint32_t a = vAlpha(~color);
if (alpha != 255) a = BYTE_MUL(a, alpha) + 255 - alpha;
for (int i = 0; i < length; ++i) {
dest[i] = BYTE_MUL(dest[i], a);
}
}
static void src_Source(uint32_t *dest, int length, const uint32_t *src,
uint32_t alpha)
{
if (alpha == 255) {
memcpy(dest, src, size_t(length) * sizeof(uint32_t));
} else {
uint32_t ialpha = 255 - alpha;
for (int i = 0; i < length; ++i) {
dest[i] =
interpolate_pixel(src[i], alpha, dest[i], ialpha);
}
}
}
/* s' = s * ca
* d' = s' + d (1 - s'a)
*/
static void src_SourceOver(uint32_t *dest, int length, const uint32_t *src,
uint32_t alpha)
{
uint32_t s, sia;
if (alpha == 255) {
for (int i = 0; i < length; ++i) {
s = src[i];
if (s >= 0xff000000)
dest[i] = s;
else if (s != 0) {
sia = vAlpha(~s);
dest[i] = s + BYTE_MUL(dest[i], sia);
}
}
} else {
/* source' = source * const_alpha
* dest = source' + dest ( 1- source'a)
*/
for (int i = 0; i < length; ++i) {
s = BYTE_MUL(src[i], alpha);
sia = vAlpha(~s);
dest[i] = s + BYTE_MUL(dest[i], sia);
}
}
}
static void src_DestinationIn(uint32_t *dest, int length, const uint32_t *src,
uint32_t alpha)
{
if (alpha == 255) {
for (int i = 0; i < length; ++i) {
dest[i] = BYTE_MUL(dest[i], vAlpha(src[i]));
}
} else {
uint32_t cia = 255 - alpha;
for (int i = 0; i < length; ++i) {
uint32_t a = BYTE_MUL(vAlpha(src[i]), alpha) + cia;
dest[i] = BYTE_MUL(dest[i], a);
}
}
}
static void src_DestinationOut(uint32_t *dest, int length, const uint32_t *src,
uint32_t alpha)
{
if (alpha == 255) {
for (int i = 0; i < length; ++i) {
dest[i] = BYTE_MUL(dest[i], vAlpha(~src[i]));
}
} else {
uint32_t cia = 255 - alpha;
for (int i = 0; i < length; ++i) {
uint32_t sia = BYTE_MUL(vAlpha(~src[i]), alpha) + cia;
dest[i] = BYTE_MUL(dest[i], sia);
}
}
}
RenderFuncTable::RenderFuncTable()
{
updateColor(BlendMode::Src, color_Source);
updateColor(BlendMode::SrcOver, color_SourceOver);
updateColor(BlendMode::DestIn, color_DestinationIn);
updateColor(BlendMode::DestOut, color_DestinationOut);
updateSrc(BlendMode::Src, src_Source);
updateSrc(BlendMode::SrcOver, src_SourceOver);
updateSrc(BlendMode::DestIn, src_DestinationIn);
updateSrc(BlendMode::DestOut, src_DestinationOut);
#if defined(__ARM_NEON__)
neon();
#endif
#if defined(__SSE2__)
sse();
#endif
}
| 5,615 | vdrawhelper_common | cpp | en | cpp | code | {"qsc_code_num_words": 755, "qsc_code_num_chars": 5615.0, "qsc_code_mean_word_length": 4.02516556, "qsc_code_frac_words_unique": 0.20529801, "qsc_code_frac_chars_top_2grams": 0.07601185, "qsc_code_frac_chars_top_3grams": 0.01085884, "qsc_code_frac_chars_top_4grams": 0.03257651, "qsc_code_frac_chars_dupe_5grams": 0.44027641, "qsc_code_frac_chars_dupe_6grams": 0.40276407, "qsc_code_frac_chars_dupe_7grams": 0.37446528, "qsc_code_frac_chars_dupe_8grams": 0.36459362, "qsc_code_frac_chars_dupe_9grams": 0.35867062, "qsc_code_frac_chars_dupe_10grams": 0.35867062, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03673788, "qsc_code_frac_chars_whitespace": 0.31647373, "qsc_code_size_file_byte": 5615.0, "qsc_code_num_lines": 189.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 29.70899471, "qsc_code_frac_chars_alphabet": 0.75508077, "qsc_code_frac_chars_comments": 0.29937667, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.32, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00330452, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00254194, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.048, "qsc_codecpp_frac_lines_func_ratio": 0.08, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.096, "qsc_codecpp_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0} |
0015/T-Glass-Applications | image_capture_app/main/include/jd9613.h | #pragma once
#include "esp_lcd_panel_interface.h"
#include "esp_lcd_panel_vendor.h"
#define AMOLED_DEFAULT_BRIGHTNESS 175
typedef struct
{
uint32_t addr;
uint8_t param[20];
uint32_t len;
} lcd_cmd_t;
#define JD9613_INIT_SEQUENCE_LENGTH 88
#define JD9613_WIDTH 126
#define JD9613_HEIGHT 294
#define LCD_CMD_RGB 0x00
#ifdef __cplusplus
extern "C"
{
#endif
/**
* @brief OLED panel initialization commands.
*
*/
static const lcd_cmd_t jd9613_cmd[JD9613_INIT_SEQUENCE_LENGTH] = {
{0xfe, {0x01}, 0x02},
{0xf7, {0x96, 0x13, 0xa9}, 0x04},
{0x90, {0x01}, 0x02},
{0x2c, {0x19, 0x0b, 0x24, 0x1b, 0x1b, 0x1b, 0xaa, 0x50, 0x01, 0x16, 0x04, 0x04, 0x04, 0xd7}, 0x0f},
{0x2d, {0x66, 0x56, 0x55}, 0x04},
{0x2e, {0x24, 0x04, 0x3f, 0x30, 0x30, 0xa8, 0xb8, 0xb8, 0x07}, 0x0a},
{0x33, {0x03, 0x03, 0x03, 0x19, 0x19, 0x19, 0x13, 0x13, 0x13, 0x1a, 0x1a, 0x1a}, 0x0d},
{0x10, {0x0b, 0x08, 0x64, 0xae, 0x0b, 0x08, 0x64, 0xae, 0x00, 0x80, 0x00, 0x00, 0x01}, 0x0e},
{0x11, {0x01, 0x1e, 0x01, 0x1e, 0x00}, 0x06},
{0x03, {0x93, 0x1c, 0x00, 0x01, 0x7e}, 0x06},
{0x19, {0x00}, 0x02},
{0x31, {0x1b, 0x00, 0x06, 0x05, 0x05, 0x05}, 0x07},
{0x35, {0x00, 0x80, 0x80, 0x00}, 0x05},
{0x12, {0x1b}, 0x02},
{0x1a, {0x01, 0x20, 0x00, 0x08, 0x01, 0x06, 0x06, 0x06}, 0x09},
{0x74, {0xbd, 0x00, 0x01, 0x08, 0x01, 0xbb, 0x98}, 0x08},
{0x6c, {0xdc, 0x08, 0x02, 0x01, 0x08, 0x01, 0x30, 0x08, 0x00}, 0x0a},
{0x6d, {0xdc, 0x08, 0x02, 0x01, 0x08, 0x02, 0x30, 0x08, 0x00}, 0x0a},
{0x76, {0xda, 0x00, 0x02, 0x20, 0x39, 0x80, 0x80, 0x50, 0x05}, 0x0a},
{0x6e, {0xdc, 0x00, 0x02, 0x01, 0x00, 0x02, 0x4f, 0x02, 0x00}, 0x0a},
{0x6f, {0xdc, 0x00, 0x02, 0x01, 0x00, 0x01, 0x4f, 0x02, 0x00}, 0x0a},
{0x80, {0xbd, 0x00, 0x01, 0x08, 0x01, 0xbb, 0x98}, 0x08},
{0x78, {0xdc, 0x08, 0x02, 0x01, 0x08, 0x01, 0x30, 0x08, 0x00}, 0x0a},
{0x79, {0xdc, 0x08, 0x02, 0x01, 0x08, 0x02, 0x30, 0x08, 0x00}, 0x0a},
{0x82, {0xda, 0x40, 0x02, 0x20, 0x39, 0x00, 0x80, 0x50, 0x05}, 0x0a},
{0x7a, {0xdc, 0x00, 0x02, 0x01, 0x00, 0x02, 0x4f, 0x02, 0x00}, 0x0a},
{0x7b, {0xdc, 0x00, 0x02, 0x01, 0x00, 0x01, 0x4f, 0x02, 0x00}, 0x0a},
{0x84, {0x01, 0x00, 0x09, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19}, 0x0b},
{0x85, {0x19, 0x19, 0x19, 0x03, 0x02, 0x08, 0x19, 0x19, 0x19, 0x19}, 0x0b},
{0x20, {0x20, 0x00, 0x08, 0x00, 0x02, 0x00, 0x40, 0x00, 0x10, 0x00, 0x04, 0x00}, 0x0d},
{0x1e, {0x40, 0x00, 0x10, 0x00, 0x04, 0x00, 0x20, 0x00, 0x08, 0x00, 0x02, 0x00}, 0x0d},
{0x24, {0x20, 0x00, 0x08, 0x00, 0x02, 0x00, 0x40, 0x00, 0x10, 0x00, 0x04, 0x00}, 0x0d},
{0x22, {0x40, 0x00, 0x10, 0x00, 0x04, 0x00, 0x20, 0x00, 0x08, 0x00, 0x02, 0x00}, 0x0d},
{0x13, {0x63, 0x52, 0x41}, 0x04},
{0x14, {0x36, 0x25, 0x14}, 0x04},
{0x15, {0x63, 0x52, 0x41}, 0x04},
{0x16, {0x36, 0x25, 0x14}, 0x04},
{0x1d, {0x10, 0x00, 0x00}, 0x04},
{0x2a, {0x0d, 0x07}, 0x03},
{0x27, {0x00, 0x01, 0x02, 0x03, 0x04, 0x05}, 0x07},
{0x28, {0x00, 0x01, 0x02, 0x03, 0x04, 0x05}, 0x07},
{0x26, {0x01, 0x01}, 0x03},
{0x86, {0x01, 0x01}, 0x03},
{0xfe, {0x02}, 0x02},
{0x16, {0x81, 0x43, 0x23, 0x1e, 0x03}, 0x06},
{0xfe, {0x03}, 0x02},
{0x60, {0x01}, 0x02},
{0x61, {0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x0d, 0x26, 0x5a, 0x80, 0x80, 0x95, 0xf8, 0x3b, 0x75}, 0x10},
{0x62, {0x21, 0x22, 0x32, 0x43, 0x44, 0xd7, 0x0a, 0x59, 0xa1, 0xe1, 0x52, 0xb7, 0x11, 0x64, 0xb1}, 0x10},
{0x63, {0x54, 0x55, 0x66, 0x06, 0xfb, 0x3f, 0x81, 0xc6, 0x06, 0x45, 0x83}, 0x0c},
{0x64, {0x00, 0x00, 0x11, 0x11, 0x21, 0x00, 0x23, 0x6a, 0xf8, 0x63, 0x67, 0x70, 0xa5, 0xdc, 0x02}, 0x10},
{0x65, {0x22, 0x22, 0x32, 0x43, 0x44, 0x24, 0x44, 0x82, 0xc1, 0xf8, 0x61, 0xbf, 0x13, 0x62, 0xad}, 0x10},
{0x66, {0x54, 0x55, 0x65, 0x06, 0xf5, 0x37, 0x76, 0xb8, 0xf5, 0x31, 0x6c}, 0x0c},
{0x67, {0x00, 0x10, 0x22, 0x22, 0x22, 0x00, 0x37, 0xa4, 0x7e, 0x22, 0x25, 0x2c, 0x4c, 0x72, 0x9a}, 0x10},
{0x68, {0x22, 0x33, 0x43, 0x44, 0x55, 0xc1, 0xe5, 0x2d, 0x6f, 0xaf, 0x23, 0x8f, 0xf3, 0x50, 0xa6}, 0x10},
{0x69, {0x65, 0x66, 0x77, 0x07, 0xfd, 0x4e, 0x9c, 0xed, 0x39, 0x86, 0xd3}, 0x0c},
{0xfe, {0x05}, 0x02},
{0x61, {0x00, 0x31, 0x44, 0x54, 0x55, 0x00, 0x92, 0xb5, 0x88, 0x19, 0x90, 0xe8, 0x3e, 0x71, 0xa5}, 0x10},
{0x62, {0x55, 0x66, 0x76, 0x77, 0x88, 0xce, 0xf2, 0x32, 0x6e, 0xc4, 0x34, 0x8b, 0xd9, 0x2a, 0x7d}, 0x10},
{0x63, {0x98, 0x99, 0xaa, 0x0a, 0xdc, 0x2e, 0x7d, 0xc3, 0x0d, 0x5b, 0x9e}, 0x0c},
{0x64, {0x00, 0x31, 0x44, 0x54, 0x55, 0x00, 0xa2, 0xe5, 0xcd, 0x5c, 0x94, 0xcf, 0x09, 0x4a, 0x72}, 0x10},
{0x65, {0x55, 0x65, 0x66, 0x77, 0x87, 0x9c, 0xc2, 0xff, 0x36, 0x6a, 0xec, 0x45, 0x91, 0xd8, 0x20}, 0x10},
{0x66, {0x88, 0x98, 0x99, 0x0a, 0x68, 0xb0, 0xfb, 0x43, 0x8c, 0xd5, 0x0e}, 0x0c},
{0x67, {0x00, 0x42, 0x55, 0x55, 0x55, 0x00, 0xcb, 0x62, 0xc5, 0x09, 0x44, 0x72, 0xa9, 0xd6, 0xfd}, 0x10},
{0x68, {0x66, 0x66, 0x77, 0x87, 0x98, 0x21, 0x45, 0x96, 0xed, 0x29, 0x90, 0xee, 0x4b, 0xb1, 0x13}, 0x10},
{0x69, {0x99, 0xaa, 0xba, 0x0b, 0x6a, 0xb8, 0x0d, 0x62, 0xb8, 0x0e, 0x54}, 0x0c},
{0xfe, {0x07}, 0x02},
{0x3e, {0x00}, 0x02},
{0x42, {0x03, 0x10}, 0x03},
{0x4a, {0x31}, 0x02},
{0x5c, {0x01}, 0x02},
{0x3c, {0x07, 0x00, 0x24, 0x04, 0x3f, 0xe2}, 0x07},
{0x44, {0x03, 0x40, 0x3f, 0x02}, 0x05},
{0x12, {0xaa, 0xaa, 0xc0, 0xc8, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8}, 0x0b},
{0x11, {0xaa, 0xaa, 0xaa, 0x60, 0x68, 0x70, 0x78, 0x80, 0x88, 0x90, 0x98, 0xa0, 0xa8, 0xb0, 0xb8}, 0x10},
{0x10, {0xaa, 0xaa, 0xaa, 0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x40, 0x48, 0x50, 0x58}, 0x10},
{0x14, {0x03, 0x1f, 0x3f, 0x5f, 0x7f, 0x9f, 0xbf, 0xdf, 0x03, 0x1f, 0x3f, 0x5f, 0x7f, 0x9f, 0xbf, 0xdf}, 0x11},
{0x18, {0x70, 0x1a, 0x22, 0xbb, 0xaa, 0xff, 0x24, 0x71, 0x0f, 0x01, 0x00, 0x03}, 0x0d},
{0xfe, {0x00}, 0x02},
{0x3a, {0x55}, 0x02},
{0xc4, {0x80}, 0x02},
{0x2a, {0x00, 0x00, 0x00, 0x7d}, 0x05},
{0x2b, {0x00, 0x00, 0x01, 0x25}, 0x05},
{0x35, {0x00}, 0x02},
{0x53, {0x28}, 0x02},
{0x51, {0xff}, 0x02},
{0, {0}, 0xff},
};
/**
* @brief Create OLED panel for model jd9613
*
* @note Vendor specific initialization can be different between manufacturers, should consult the LCD supplier for initialization sequence code.
*
* @param[in] io LCD panel IO handle
* @param[in] panel_dev_config general panel device configuration
* @param[out] ret_panel Returned LCD panel handle
* @return
* - ESP_ERR_INVALID_ARG if parameter is invalid
* - ESP_ERR_NO_MEM if out of memory
* - ESP_OK on success
*/
esp_err_t esp_lcd_new_panel_jd9613(const esp_lcd_panel_io_handle_t io, const esp_lcd_panel_dev_config_t *panel_dev_config, esp_lcd_panel_handle_t *ret_panel);
esp_err_t panel_jd9613_set_rotation(esp_lcd_panel_t *panel, uint8_t r);
void flipHorizontal(esp_lcd_panel_t *panel, bool enable);
void setBrightness(esp_lcd_panel_t *panel, uint8_t level);
#ifdef __cplusplus
}
#endif
| 7,450 | jd9613 | h | en | c | code | {"qsc_code_num_words": 1033, "qsc_code_num_chars": 7450.0, "qsc_code_mean_word_length": 4.12100678, "qsc_code_frac_words_unique": 0.2875121, "qsc_code_frac_chars_top_2grams": 0.02818887, "qsc_code_frac_chars_top_3grams": 0.02536998, "qsc_code_frac_chars_top_4grams": 0.01879258, "qsc_code_frac_chars_dupe_5grams": 0.20554381, "qsc_code_frac_chars_dupe_6grams": 0.19591261, "qsc_code_frac_chars_dupe_7grams": 0.17805967, "qsc_code_frac_chars_dupe_8grams": 0.15409913, "qsc_code_frac_chars_dupe_9grams": 0.12403101, "qsc_code_frac_chars_dupe_10grams": 0.12403101, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.39318222, "qsc_code_frac_chars_whitespace": 0.24791946, "qsc_code_size_file_byte": 7450.0, "qsc_code_num_lines": 137.0, "qsc_code_num_chars_line_max": 163.0, "qsc_code_num_chars_line_mean": 54.37956204, "qsc_code_frac_chars_alphabet": 0.36658933, "qsc_code_frac_chars_comments": 0.08671141, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.03508772, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00705467, "qsc_code_frac_chars_long_word_length": 0.0069077, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.48089359, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.03508772, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.05263158, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 1, "qsc_code_frac_chars_digital": 1, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 1, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/T-Glass-Applications | ancs_app/main/include/t_glass.h | #pragma once
#include "jd9613.h"
#include "driver/gpio.h"
#include "lvgl.h"
#include "esp_lvgl_port.h"
#include "ancs_app.h"
#define BOARD_DISP_HOST SPI3_HOST
#define BOARD_NONE_PIN (-1)
#define BOARD_DISP_CS (17)
#define BOARD_DISP_SCK (15)
#define BOARD_DISP_MISO (BOARD_NONE_PIN)
#define BOARD_DISP_MOSI (16)
#define BOARD_DISP_DC (21)
#define BOARD_DISP_RST (18)
#define BOARD_I2C_SDA (9)
#define BOARD_I2C_SCL (8)
#define BOARD_BHI_IRQ (37)
#define BOARD_BHI_CS (36)
#define BOARD_BHI_SCK (35)
#define BOARD_BHI_MISO (34)
#define BOARD_BHI_MOSI (33)
#define BOARD_BHI_RST (47)
#define BOARD_BHI_EN (48)
#define BOARD_RTC_IRQ (7)
#define BOARD_TOUCH_BUTTON (14)
#define BOARD_BOOT_PIN (0)
#define BOARD_BAT_ADC (13)
#define BOARD_VIBRATION_PIN (38)
#define DEFAULT_SCK_SPEED (70 * 1000 * 1000)
#define BOARD_MIC_CLOCK (6)
#define BOARD_MIC_DATA (5)
#define GlassViewable_X_Offset 168
#define GlassViewableWidth 126
#define GlassViewableHeight 126
extern lv_obj_t *base_ui;
extern lv_timer_t *base_timer;
extern lv_color_t font_color;
extern lv_color_t bg_color;
esp_err_t init_tglass();
void add_tile_view(int index, NotificationAttributes *notification);
void lv_gui_ble_status(bool isOn);
void lv_gui_set_inbox_title(int notification_count); | 1,257 | t_glass | h | en | c | code | {"qsc_code_num_words": 215, "qsc_code_num_chars": 1257.0, "qsc_code_mean_word_length": 4.2744186, "qsc_code_frac_words_unique": 0.48372093, "qsc_code_frac_chars_top_2grams": 0.28726877, "qsc_code_frac_chars_top_3grams": 0.11425462, "qsc_code_frac_chars_top_4grams": 0.0304679, "qsc_code_frac_chars_dupe_5grams": 0.0, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.05609973, "qsc_code_frac_chars_whitespace": 0.10660302, "qsc_code_size_file_byte": 1257.0, "qsc_code_num_lines": 52.0, "qsc_code_num_chars_line_max": 69.0, "qsc_code_num_chars_line_mean": 24.17307692, "qsc_code_frac_chars_alphabet": 0.76224399, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.04133545, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.0952381, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.21428571, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 1, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/lottieloader.cpp | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
* 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.
*/
#include <cstring>
#include <fstream>
#include <sstream>
#include "lottiemodel.h"
using namespace rlottie::internal;
#ifdef LOTTIE_CACHE_SUPPORT
#include <mutex>
#include <unordered_map>
class ModelCache {
public:
static ModelCache &instance()
{
static ModelCache singleton;
return singleton;
}
std::shared_ptr<model::Composition> find(const std::string &key)
{
std::lock_guard<std::mutex> guard(mMutex);
if (!mcacheSize) return nullptr;
auto search = mHash.find(key);
return (search != mHash.end()) ? search->second : nullptr;
}
void add(const std::string &key, std::shared_ptr<model::Composition> value)
{
std::lock_guard<std::mutex> guard(mMutex);
if (!mcacheSize) return;
//@TODO just remove the 1st element
// not the best of LRU logic
if (mcacheSize == mHash.size()) mHash.erase(mHash.cbegin());
mHash[key] = std::move(value);
}
void configureCacheSize(size_t cacheSize)
{
std::lock_guard<std::mutex> guard(mMutex);
mcacheSize = cacheSize;
if (!mcacheSize) mHash.clear();
}
private:
ModelCache() = default;
std::unordered_map<std::string, std::shared_ptr<model::Composition>> mHash;
std::mutex mMutex;
size_t mcacheSize{10};
};
#else
class ModelCache {
public:
static ModelCache &instance()
{
static ModelCache singleton;
return singleton;
}
std::shared_ptr<model::Composition> find(const std::string &)
{
return nullptr;
}
void add(const std::string &, std::shared_ptr<model::Composition>) {}
void configureCacheSize(size_t) {}
};
#endif
static std::string dirname(const std::string &path)
{
const char *ptr = strrchr(path.c_str(), '/');
#ifdef _WIN32
if (ptr) ptr = strrchr(ptr + 1, '\\');
#endif
int len = int(ptr + 1 - path.c_str()); // +1 to include '/'
return std::string(path, 0, len);
}
void model::configureModelCacheSize(size_t cacheSize)
{
ModelCache::instance().configureCacheSize(cacheSize);
}
std::shared_ptr<model::Composition> model::loadFromFile(const std::string &path,
bool cachePolicy)
{
if (cachePolicy) {
auto obj = ModelCache::instance().find(path);
if (obj) return obj;
}
std::ifstream f;
f.open(path);
if (!f.is_open()) {
vCritical << "failed to open file = " << path.c_str();
return {};
} else {
std::string content;
std::getline(f, content, '\0');
f.close();
if (content.empty()) return {};
auto obj = internal::model::parse(const_cast<char *>(content.c_str()),
dirname(path));
if (obj && cachePolicy) ModelCache::instance().add(path, obj);
return obj;
}
}
std::shared_ptr<model::Composition> model::loadFromData(
std::string jsonData, const std::string &key, std::string resourcePath,
bool cachePolicy)
{
if (cachePolicy) {
auto obj = ModelCache::instance().find(key);
if (obj) return obj;
}
auto obj = internal::model::parse(const_cast<char *>(jsonData.c_str()),
std::move(resourcePath));
if (obj && cachePolicy) ModelCache::instance().add(key, obj);
return obj;
}
std::shared_ptr<model::Composition> model::loadFromData(
std::string jsonData, std::string resourcePath, model::ColorFilter filter)
{
return internal::model::parse(const_cast<char *>(jsonData.c_str()),
std::move(resourcePath), std::move(filter));
}
| 4,889 | lottieloader | cpp | en | cpp | code | {"qsc_code_num_words": 583, "qsc_code_num_chars": 4889.0, "qsc_code_mean_word_length": 5.23327616, "qsc_code_frac_words_unique": 0.33962264, "qsc_code_frac_chars_top_2grams": 0.04424779, "qsc_code_frac_chars_top_3grams": 0.03146509, "qsc_code_frac_chars_top_4grams": 0.04457555, "qsc_code_frac_chars_dupe_5grams": 0.36184857, "qsc_code_frac_chars_dupe_6grams": 0.34414946, "qsc_code_frac_chars_dupe_7grams": 0.29367421, "qsc_code_frac_chars_dupe_8grams": 0.25925926, "qsc_code_frac_chars_dupe_9grams": 0.24451, "qsc_code_frac_chars_dupe_10grams": 0.2071452, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0038116, "qsc_code_frac_chars_whitespace": 0.24872162, "qsc_code_size_file_byte": 4889.0, "qsc_code_num_lines": 169.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 28.92899408, "qsc_code_frac_chars_alphabet": 0.82684454, "qsc_code_frac_chars_comments": 0.25240335, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.24324324, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01094391, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.00591716, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.10810811, "qsc_codecpp_frac_lines_func_ratio": 0.04504505, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.17117117, "qsc_codecpp_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/lottieanimation.cpp | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
* 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.
*/
#include "config.h"
#include "lottieitem.h"
#include "lottiemodel.h"
#include "rlottie.h"
#include <fstream>
using namespace rlottie;
using namespace rlottie::internal;
RLOTTIE_API void rlottie::configureModelCacheSize(size_t cacheSize)
{
internal::model::configureModelCacheSize(cacheSize);
}
struct RenderTask {
RenderTask() { receiver = sender.get_future(); }
std::promise<Surface> sender;
std::future<Surface> receiver;
AnimationImpl * playerImpl{nullptr};
size_t frameNo{0};
Surface surface;
bool keepAspectRatio{true};
};
using SharedRenderTask = std::shared_ptr<RenderTask>;
class AnimationImpl {
public:
void init(std::shared_ptr<model::Composition> composition);
bool update(size_t frameNo, const VSize &size, bool keepAspectRatio);
VSize size() const { return mModel->size(); }
double duration() const { return mModel->duration(); }
double frameRate() const { return mModel->frameRate(); }
size_t totalFrame() const { return mModel->totalFrame(); }
size_t frameAtPos(double pos) const { return mModel->frameAtPos(pos); }
Surface render(size_t frameNo, const Surface &surface,
bool keepAspectRatio);
std::future<Surface> renderAsync(size_t frameNo, Surface &&surface,
bool keepAspectRatio);
const LOTLayerNode * renderTree(size_t frameNo, const VSize &size);
const LayerInfoList &layerInfoList() const
{
if (mLayerList.empty()) {
mLayerList = mModel->layerInfoList();
}
return mLayerList;
}
const MarkerList &markers() const { return mModel->markers(); }
void setValue(const std::string &keypath, LOTVariant &&value);
void removeFilter(const std::string &keypath, Property prop);
private:
mutable LayerInfoList mLayerList;
model::Composition * mModel;
SharedRenderTask mTask;
std::atomic<bool> mRenderInProgress;
std::unique_ptr<renderer::Composition> mRenderer{nullptr};
};
void AnimationImpl::setValue(const std::string &keypath, LOTVariant &&value)
{
if (keypath.empty()) return;
mRenderer->setValue(keypath, value);
}
const LOTLayerNode *AnimationImpl::renderTree(size_t frameNo, const VSize &size)
{
if (update(frameNo, size, true)) {
mRenderer->buildRenderTree();
}
return mRenderer->renderTree();
}
bool AnimationImpl::update(size_t frameNo, const VSize &size,
bool keepAspectRatio)
{
frameNo += mModel->startFrame();
if (frameNo > mModel->endFrame()) frameNo = mModel->endFrame();
if (frameNo < mModel->startFrame()) frameNo = mModel->startFrame();
return mRenderer->update(int(frameNo), size, keepAspectRatio);
}
Surface AnimationImpl::render(size_t frameNo, const Surface &surface,
bool keepAspectRatio)
{
bool renderInProgress = mRenderInProgress.load();
if (renderInProgress) {
vCritical << "Already Rendering Scheduled for this Animation";
return surface;
}
mRenderInProgress.store(true);
update(
frameNo,
VSize(int(surface.drawRegionWidth()), int(surface.drawRegionHeight())),
keepAspectRatio);
mRenderer->render(surface);
mRenderInProgress.store(false);
return surface;
}
void AnimationImpl::init(std::shared_ptr<model::Composition> composition)
{
mModel = composition.get();
mRenderer = std::make_unique<renderer::Composition>(composition);
mRenderInProgress = false;
}
#ifdef LOTTIE_THREAD_SUPPORT
#include <thread>
#include "vtaskqueue.h"
/*
* Implement a task stealing schduler to perform render task
* As each player draws into its own buffer we can delegate this
* task to a slave thread. The scheduler creates a threadpool depending
* on the number of cores available in the system and does a simple fair
* scheduling by assigning the task in a round-robin fashion. Each thread
* in the threadpool has its own queue. once it finishes all the task on its
* own queue it goes through rest of the queue and looks for task if it founds
* one it steals the task from it and executes. if it couldn't find one then it
* just waits for new task on its own queue.
*/
class RenderTaskScheduler {
const unsigned _count{std::thread::hardware_concurrency()};
std::vector<std::thread> _threads;
std::vector<TaskQueue<SharedRenderTask>> _q{_count};
std::atomic<unsigned> _index{0};
void run(unsigned i)
{
while (true) {
bool success = false;
SharedRenderTask task;
for (unsigned n = 0; n != _count * 2; ++n) {
if (_q[(i + n) % _count].try_pop(task)) {
success = true;
break;
}
}
if (!success && !_q[i].pop(task)) break;
auto result = task->playerImpl->render(task->frameNo, task->surface,
task->keepAspectRatio);
task->sender.set_value(result);
}
}
RenderTaskScheduler()
{
for (unsigned n = 0; n != _count; ++n) {
_threads.emplace_back([&, n] { run(n); });
}
IsRunning = true;
}
public:
static bool IsRunning;
static RenderTaskScheduler &instance()
{
static RenderTaskScheduler singleton;
return singleton;
}
~RenderTaskScheduler() { stop(); }
void stop()
{
if (IsRunning) {
IsRunning = false;
for (auto &e : _q) e.done();
for (auto &e : _threads) e.join();
}
}
std::future<Surface> process(SharedRenderTask task)
{
auto receiver = std::move(task->receiver);
auto i = _index++;
for (unsigned n = 0; n != _count; ++n) {
if (_q[(i + n) % _count].try_push(std::move(task))) return receiver;
}
if (_count > 0) {
_q[i % _count].push(std::move(task));
}
return receiver;
}
};
#else
class RenderTaskScheduler {
public:
static bool IsRunning;
static RenderTaskScheduler &instance()
{
static RenderTaskScheduler singleton;
return singleton;
}
void stop() {}
std::future<Surface> process(SharedRenderTask task)
{
auto result = task->playerImpl->render(task->frameNo, task->surface,
task->keepAspectRatio);
task->sender.set_value(result);
return std::move(task->receiver);
}
};
#endif
bool RenderTaskScheduler::IsRunning{false};
std::future<Surface> AnimationImpl::renderAsync(size_t frameNo,
Surface &&surface,
bool keepAspectRatio)
{
if (!mTask) {
mTask = std::make_shared<RenderTask>();
} else {
mTask->sender = std::promise<Surface>();
mTask->receiver = mTask->sender.get_future();
}
mTask->playerImpl = this;
mTask->frameNo = frameNo;
mTask->surface = std::move(surface);
mTask->keepAspectRatio = keepAspectRatio;
return RenderTaskScheduler::instance().process(mTask);
}
/**
* \breif Brief abput the Api.
* Description about the setFilePath Api
* @param path add the details
*/
std::unique_ptr<Animation> Animation::loadFromData(
std::string jsonData, const std::string &key,
const std::string &resourcePath, bool cachePolicy)
{
if (jsonData.empty()) {
vWarning << "jason data is empty";
return nullptr;
}
auto composition = model::loadFromData(std::move(jsonData), key,
resourcePath, cachePolicy);
if (composition) {
auto animation = std::unique_ptr<Animation>(new Animation);
animation->d->init(std::move(composition));
return animation;
}
return nullptr;
}
std::unique_ptr<Animation> Animation::loadFromData(std::string jsonData,
std::string resourcePath,
ColorFilter filter)
{
if (jsonData.empty()) {
vWarning << "jason data is empty";
return nullptr;
}
auto composition = model::loadFromData(
std::move(jsonData), std::move(resourcePath), std::move(filter));
if (composition) {
auto animation = std::unique_ptr<Animation>(new Animation);
animation->d->init(std::move(composition));
return animation;
}
return nullptr;
}
std::unique_ptr<Animation> Animation::loadFromFile(const std::string &path,
bool cachePolicy)
{
if (path.empty()) {
vWarning << "File path is empty";
return nullptr;
}
auto composition = model::loadFromFile(path, cachePolicy);
if (composition) {
auto animation = std::unique_ptr<Animation>(new Animation);
animation->d->init(std::move(composition));
return animation;
}
return nullptr;
}
void Animation::size(size_t &width, size_t &height) const
{
VSize sz = d->size();
width = sz.width();
height = sz.height();
}
double Animation::duration() const
{
return d->duration();
}
double Animation::frameRate() const
{
return d->frameRate();
}
size_t Animation::totalFrame() const
{
return d->totalFrame();
}
size_t Animation::frameAtPos(double pos)
{
return d->frameAtPos(pos);
}
const LOTLayerNode *Animation::renderTree(size_t frameNo, size_t width,
size_t height) const
{
return d->renderTree(frameNo, VSize(int(width), int(height)));
}
std::future<Surface> Animation::render(size_t frameNo, Surface surface,
bool keepAspectRatio)
{
return d->renderAsync(frameNo, std::move(surface), keepAspectRatio);
}
void Animation::renderSync(size_t frameNo, Surface surface,
bool keepAspectRatio)
{
d->render(frameNo, surface, keepAspectRatio);
}
const LayerInfoList &Animation::layers() const
{
return d->layerInfoList();
}
const MarkerList &Animation::markers() const
{
return d->markers();
}
void Animation::setValue(Color_Type, Property prop, const std::string &keypath,
Color value)
{
d->setValue(keypath,
LOTVariant(prop, [value](const FrameInfo &) { return value; }));
}
void Animation::setValue(Float_Type, Property prop, const std::string &keypath,
float value)
{
d->setValue(keypath,
LOTVariant(prop, [value](const FrameInfo &) { return value; }));
}
void Animation::setValue(Size_Type, Property prop, const std::string &keypath,
Size value)
{
d->setValue(keypath,
LOTVariant(prop, [value](const FrameInfo &) { return value; }));
}
void Animation::setValue(Point_Type, Property prop, const std::string &keypath,
Point value)
{
d->setValue(keypath,
LOTVariant(prop, [value](const FrameInfo &) { return value; }));
}
void Animation::setValue(Color_Type, Property prop, const std::string &keypath,
std::function<Color(const FrameInfo &)> &&value)
{
d->setValue(keypath, LOTVariant(prop, value));
}
void Animation::setValue(Float_Type, Property prop, const std::string &keypath,
std::function<float(const FrameInfo &)> &&value)
{
d->setValue(keypath, LOTVariant(prop, value));
}
void Animation::setValue(Size_Type, Property prop, const std::string &keypath,
std::function<Size(const FrameInfo &)> &&value)
{
d->setValue(keypath, LOTVariant(prop, value));
}
void Animation::setValue(Point_Type, Property prop, const std::string &keypath,
std::function<Point(const FrameInfo &)> &&value)
{
d->setValue(keypath, LOTVariant(prop, value));
}
Animation::~Animation() = default;
Animation::Animation() : d(std::make_unique<AnimationImpl>()) {}
Surface::Surface(uint32_t *buffer, size_t width, size_t height,
size_t bytesPerLine)
: mBuffer(buffer),
mWidth(width),
mHeight(height),
mBytesPerLine(bytesPerLine)
{
mDrawArea.w = mWidth;
mDrawArea.h = mHeight;
}
void Surface::setDrawRegion(size_t x, size_t y, size_t width, size_t height)
{
if ((x + width > mWidth) || (y + height > mHeight)) return;
mDrawArea.x = x;
mDrawArea.y = y;
mDrawArea.w = width;
mDrawArea.h = height;
}
namespace {
void lottieShutdownRenderTaskScheduler()
{
if (RenderTaskScheduler::IsRunning) {
RenderTaskScheduler::instance().stop();
}
}
} // namespace
// private apis exposed to c interface
void lottie_init_impl()
{
// do nothing for now.
}
extern void lottieShutdownRasterTaskScheduler();
void lottie_shutdown_impl()
{
lottieShutdownRenderTaskScheduler();
lottieShutdownRasterTaskScheduler();
}
#ifdef LOTTIE_LOGGING_SUPPORT
void initLogging()
{
#if defined(__ARM_NEON__)
set_log_level(LogLevel::OFF);
#else
initialize(GuaranteedLogger(), "/tmp/", "rlottie", 1);
set_log_level(LogLevel::INFO);
#endif
}
V_CONSTRUCTOR_FUNCTION(initLogging)
#endif
| 14,622 | lottieanimation | cpp | en | cpp | code | {"qsc_code_num_words": 1542, "qsc_code_num_chars": 14622.0, "qsc_code_mean_word_length": 5.86964981, "qsc_code_frac_words_unique": 0.23281453, "qsc_code_frac_chars_top_2grams": 0.0154679, "qsc_code_frac_chars_top_3grams": 0.02165507, "qsc_code_frac_chars_top_4grams": 0.02552204, "qsc_code_frac_chars_dupe_5grams": 0.35520937, "qsc_code_frac_chars_dupe_6grams": 0.35145288, "qsc_code_frac_chars_dupe_7grams": 0.33830516, "qsc_code_frac_chars_dupe_8grams": 0.27367142, "qsc_code_frac_chars_dupe_9grams": 0.26129709, "qsc_code_frac_chars_dupe_10grams": 0.21710308, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00129606, "qsc_code_frac_chars_whitespace": 0.26125017, "qsc_code_size_file_byte": 14622.0, "qsc_code_num_lines": 495.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 29.53939394, "qsc_code_frac_chars_alphabet": 0.83660433, "qsc_code_frac_chars_comments": 0.13445493, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.21899736, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01327434, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.05013193, "qsc_codecpp_frac_lines_func_ratio": 0.05540897, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.12137203, "qsc_codecpp_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/lottieitem.cpp | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
* 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.
*/
#include "lottieitem.h"
#include <algorithm>
#include <cmath>
#include <iterator>
#include "lottiekeypath.h"
#include "vbitmap.h"
#include "vpainter.h"
#include "vraster.h"
/* Lottie Layer Rules
* 1. time stretch is pre calculated and applied to all the properties of the
* lottilayer model and all its children
* 2. The frame property could be reversed using,time-reverse layer property in
* AE. which means (start frame > endFrame) 3.
*/
static bool transformProp(rlottie::Property prop)
{
switch (prop) {
case rlottie::Property::TrAnchor:
case rlottie::Property::TrScale:
case rlottie::Property::TrOpacity:
case rlottie::Property::TrPosition:
case rlottie::Property::TrRotation:
return true;
default:
return false;
}
}
static bool fillProp(rlottie::Property prop)
{
switch (prop) {
case rlottie::Property::FillColor:
case rlottie::Property::FillOpacity:
return true;
default:
return false;
}
}
static bool strokeProp(rlottie::Property prop)
{
switch (prop) {
case rlottie::Property::StrokeColor:
case rlottie::Property::StrokeOpacity:
case rlottie::Property::StrokeWidth:
return true;
default:
return false;
}
}
static renderer::Layer *createLayerItem(model::Layer *layerData,
VArenaAlloc * allocator)
{
switch (layerData->mLayerType) {
case model::Layer::Type::Precomp: {
return allocator->make<renderer::CompLayer>(layerData, allocator);
}
case model::Layer::Type::Solid: {
return allocator->make<renderer::SolidLayer>(layerData);
}
case model::Layer::Type::Shape: {
return allocator->make<renderer::ShapeLayer>(layerData, allocator);
}
case model::Layer::Type::Null: {
return allocator->make<renderer::NullLayer>(layerData);
}
case model::Layer::Type::Image: {
return allocator->make<renderer::ImageLayer>(layerData);
}
default:
return nullptr;
break;
}
}
renderer::Composition::Composition(std::shared_ptr<model::Composition> model)
: mCurFrameNo(-1)
{
mModel = std::move(model);
mRootLayer = createLayerItem(mModel->mRootLayer, &mAllocator);
mRootLayer->setComplexContent(false);
mViewSize = mModel->size();
}
void renderer::Composition::setValue(const std::string &keypath,
LOTVariant & value)
{
LOTKeyPath key(keypath);
mRootLayer->resolveKeyPath(key, 0, value);
}
bool renderer::Composition::update(int frameNo, const VSize &size,
bool keepAspectRatio)
{
// check if cached frame is same as requested frame.
if ((mViewSize == size) && (mCurFrameNo == frameNo) &&
(mKeepAspectRatio == keepAspectRatio))
return false;
mViewSize = size;
mCurFrameNo = frameNo;
mKeepAspectRatio = keepAspectRatio;
/*
* if viewbox dosen't scale exactly to the viewport
* we scale the viewbox keeping AspectRatioPreserved and then align the
* viewbox to the viewport using AlignCenter rule.
*/
VMatrix m;
VSize viewPort = mViewSize;
VSize viewBox = mModel->size();
float sx = float(viewPort.width()) / viewBox.width();
float sy = float(viewPort.height()) / viewBox.height();
if (mKeepAspectRatio) {
float scale = std::min(sx, sy);
float tx = (viewPort.width() - viewBox.width() * scale) * 0.5f;
float ty = (viewPort.height() - viewBox.height() * scale) * 0.5f;
m.translate(tx, ty).scale(scale, scale);
} else {
m.scale(sx, sy);
}
mRootLayer->update(frameNo, m, 1.0);
return true;
}
bool renderer::Composition::render(const rlottie::Surface &surface)
{
mSurface.reset(reinterpret_cast<uint8_t *>(surface.buffer()),
uint32_t(surface.width()), uint32_t(surface.height()),
uint32_t(surface.bytesPerLine()),
VBitmap::Format::ARGB32_Premultiplied);
/* schedule all preprocess task for this frame at once.
*/
VRect clip(0, 0, int(surface.drawRegionWidth()),
int(surface.drawRegionHeight()));
mRootLayer->preprocess(clip);
VPainter painter(&mSurface);
// set sub surface area for drawing.
painter.setDrawRegion(
VRect(int(surface.drawRegionPosX()), int(surface.drawRegionPosY()),
int(surface.drawRegionWidth()), int(surface.drawRegionHeight())));
mRootLayer->render(&painter, {}, {}, mSurfaceCache);
painter.end();
return true;
}
void renderer::Mask::update(int frameNo, const VMatrix &parentMatrix,
float /*parentAlpha*/, const DirtyFlag &flag)
{
bool dirtyPath = false;
if (flag.testFlag(DirtyFlagBit::None) && mData->isStatic()) return;
if (mData->mShape.isStatic()) {
if (mLocalPath.empty()) {
dirtyPath = true;
mData->mShape.value(frameNo, mLocalPath);
}
} else {
dirtyPath = true;
mData->mShape.value(frameNo, mLocalPath);
}
/* mask item dosen't inherit opacity */
mCombinedAlpha = mData->opacity(frameNo);
if ( flag.testFlag(DirtyFlagBit::Matrix) || dirtyPath ) {
mFinalPath.clone(mLocalPath);
mFinalPath.transform(parentMatrix);
mRasterRequest = true;
}
}
VRle renderer::Mask::rle()
{
if (!vCompare(mCombinedAlpha, 1.0f)) {
VRle obj = mRasterizer.rle();
obj *= uint8_t(mCombinedAlpha * 255);
return obj;
} else {
return mRasterizer.rle();
}
}
void renderer::Mask::preprocess(const VRect &clip)
{
if (mRasterRequest)
mRasterizer.rasterize(mFinalPath, FillRule::Winding, clip);
}
void renderer::Layer::render(VPainter *painter, const VRle &inheritMask,
const VRle &matteRle, SurfaceCache &)
{
auto renderlist = renderList();
if (renderlist.empty()) return;
VRle mask;
if (mLayerMask) {
mask = mLayerMask->maskRle(painter->clipBoundingRect());
if (!inheritMask.empty()) mask = mask & inheritMask;
// if resulting mask is empty then return.
if (mask.empty()) return;
} else {
mask = inheritMask;
}
for (auto &i : renderlist) {
painter->setBrush(i->mBrush);
VRle rle = i->rle();
if (matteRle.empty()) {
if (mask.empty()) {
// no mask no matte
painter->drawRle(VPoint(), rle);
} else {
// only mask
painter->drawRle(rle, mask);
}
} else {
if (!mask.empty()) rle = rle & mask;
if (rle.empty()) continue;
if (matteType() == model::MatteType::AlphaInv) {
rle = rle - matteRle;
painter->drawRle(VPoint(), rle);
} else {
// render with matteRle as clip.
painter->drawRle(rle, matteRle);
}
}
}
}
void renderer::LayerMask::preprocess(const VRect &clip)
{
for (auto &i : mMasks) {
i.preprocess(clip);
}
}
renderer::LayerMask::LayerMask(model::Layer *layerData)
{
if (!layerData->mExtra) return;
mMasks.reserve(layerData->mExtra->mMasks.size());
for (auto &i : layerData->mExtra->mMasks) {
mMasks.emplace_back(i);
mStatic &= i->isStatic();
}
}
void renderer::LayerMask::update(int frameNo, const VMatrix &parentMatrix,
float parentAlpha, const DirtyFlag &flag)
{
if (flag.testFlag(DirtyFlagBit::None) && isStatic()) return;
for (auto &i : mMasks) {
i.update(frameNo, parentMatrix, parentAlpha, flag);
}
mDirty = true;
}
VRle renderer::LayerMask::maskRle(const VRect &clipRect)
{
if (!mDirty) return mRle;
VRle rle;
for (auto &e : mMasks) {
const auto cur = [&]() {
if (e.inverted())
return clipRect - e.rle();
else
return e.rle();
}();
switch (e.maskMode()) {
case model::Mask::Mode::Add: {
rle = rle + cur;
break;
}
case model::Mask::Mode::Substarct: {
if (rle.empty() && !clipRect.empty())
rle = clipRect - cur;
else
rle = rle - cur;
break;
}
case model::Mask::Mode::Intersect: {
if (rle.empty() && !clipRect.empty())
rle = clipRect & cur;
else
rle = rle & cur;
break;
}
case model::Mask::Mode::Difference: {
rle = rle ^ cur;
break;
}
default:
break;
}
}
if (!rle.empty() && !rle.unique()) {
mRle.clone(rle);
} else {
mRle = rle;
}
mDirty = false;
return mRle;
}
renderer::Layer::Layer(model::Layer *layerData) : mLayerData(layerData)
{
if (mLayerData->mHasMask)
mLayerMask = std::make_unique<renderer::LayerMask>(mLayerData);
}
bool renderer::Layer::resolveKeyPath(LOTKeyPath &keyPath, uint32_t depth,
LOTVariant &value)
{
if (!keyPath.matches(name(), depth)) {
return false;
}
if (!keyPath.skip(name())) {
if (keyPath.fullyResolvesTo(name(), depth) &&
transformProp(value.property())) {
//@TODO handle propery update.
}
}
return true;
}
bool renderer::ShapeLayer::resolveKeyPath(LOTKeyPath &keyPath, uint32_t depth,
LOTVariant &value)
{
if (renderer::Layer::resolveKeyPath(keyPath, depth, value)) {
if (keyPath.propagate(name(), depth)) {
uint32_t newDepth = keyPath.nextDepth(name(), depth);
mRoot->resolveKeyPath(keyPath, newDepth, value);
}
return true;
}
return false;
}
bool renderer::CompLayer::resolveKeyPath(LOTKeyPath &keyPath, uint32_t depth,
LOTVariant &value)
{
if (renderer::Layer::resolveKeyPath(keyPath, depth, value)) {
if (keyPath.propagate(name(), depth)) {
uint32_t newDepth = keyPath.nextDepth(name(), depth);
for (const auto &layer : mLayers) {
layer->resolveKeyPath(keyPath, newDepth, value);
}
}
return true;
}
return false;
}
void renderer::Layer::update(int frameNumber, const VMatrix &parentMatrix,
float parentAlpha)
{
mFrameNo = frameNumber;
// 1. check if the layer is part of the current frame
if (!visible()) return;
float alpha = parentAlpha * opacity(frameNo());
if (vIsZero(alpha)) {
mCombinedAlpha = 0;
return;
}
// 2. calculate the parent matrix and alpha
VMatrix m = matrix(frameNo());
m *= parentMatrix;
// 3. update the dirty flag based on the change
if (mCombinedMatrix != m) {
mDirtyFlag |= DirtyFlagBit::Matrix;
mCombinedMatrix = m;
}
if (!vCompare(mCombinedAlpha, alpha)) {
mDirtyFlag |= DirtyFlagBit::Alpha;
mCombinedAlpha = alpha;
}
// 4. update the mask
if (mLayerMask) {
mLayerMask->update(frameNo(), mCombinedMatrix, mCombinedAlpha,
mDirtyFlag);
}
// 5. if no parent property change and layer is static then nothing to do.
if (!mLayerData->precompLayer() && flag().testFlag(DirtyFlagBit::None) &&
isStatic())
return;
// 6. update the content of the layer
updateContent();
// 7. reset the dirty flag
mDirtyFlag = DirtyFlagBit::None;
}
VMatrix renderer::Layer::matrix(int frameNo) const
{
return mParentLayer
? (mLayerData->matrix(frameNo) * mParentLayer->matrix(frameNo))
: mLayerData->matrix(frameNo);
}
bool renderer::Layer::visible() const
{
return (frameNo() >= mLayerData->inFrame() &&
frameNo() <= mLayerData->outFrame());
}
void renderer::Layer::preprocess(const VRect &clip)
{
// layer dosen't contribute to the frame
if (skipRendering()) return;
// preprocess layer masks
if (mLayerMask) mLayerMask->preprocess(clip);
preprocessStage(clip);
}
renderer::CompLayer::CompLayer(model::Layer *layerModel, VArenaAlloc *allocator)
: renderer::Layer(layerModel)
{
if (!mLayerData->mChildren.empty())
mLayers.reserve(mLayerData->mChildren.size());
// 1. keep the layer in back-to-front order.
// as lottie model keeps the data in front-toback-order.
for (auto it = mLayerData->mChildren.crbegin();
it != mLayerData->mChildren.rend(); ++it) {
auto model = static_cast<model::Layer *>(*it);
auto item = createLayerItem(model, allocator);
if (item) mLayers.push_back(item);
}
// 2. update parent layer
for (const auto &layer : mLayers) {
int id = layer->parentId();
if (id >= 0) {
auto search =
std::find_if(mLayers.begin(), mLayers.end(),
[id](const auto &val) { return val->id() == id; });
if (search != mLayers.end()) layer->setParentLayer(*search);
}
}
// 4. check if its a nested composition
if (!layerModel->layerSize().empty()) {
mClipper = std::make_unique<renderer::Clipper>(layerModel->layerSize());
}
if (mLayers.size() > 1) setComplexContent(true);
}
void renderer::CompLayer::render(VPainter *painter, const VRle &inheritMask,
const VRle &matteRle, SurfaceCache &cache)
{
if (vIsZero(combinedAlpha())) return;
if (vCompare(combinedAlpha(), 1.0)) {
renderHelper(painter, inheritMask, matteRle, cache);
} else {
if (complexContent()) {
VSize size = painter->clipBoundingRect().size();
VPainter srcPainter;
VBitmap srcBitmap = cache.make_surface(size.width(), size.height());
srcPainter.begin(&srcBitmap);
renderHelper(&srcPainter, inheritMask, matteRle, cache);
srcPainter.end();
painter->drawBitmap(VPoint(), srcBitmap,
uint8_t(combinedAlpha() * 255.0f));
cache.release_surface(srcBitmap);
} else {
renderHelper(painter, inheritMask, matteRle, cache);
}
}
}
void renderer::CompLayer::renderHelper(VPainter * painter,
const VRle & inheritMask,
const VRle & matteRle,
SurfaceCache &cache)
{
VRle mask;
if (mLayerMask) {
mask = mLayerMask->maskRle(painter->clipBoundingRect());
if (!inheritMask.empty()) mask = mask & inheritMask;
// if resulting mask is empty then return.
if (mask.empty()) return;
} else {
mask = inheritMask;
}
if (mClipper) {
mask = mClipper->rle(mask);
if (mask.empty()) return;
}
renderer::Layer *matte = nullptr;
for (const auto &layer : mLayers) {
if (layer->hasMatte()) {
matte = layer;
} else {
if (layer->visible()) {
if (matte) {
if (matte->visible())
renderMatteLayer(painter, mask, matteRle, matte, layer,
cache);
} else {
layer->render(painter, mask, matteRle, cache);
}
}
matte = nullptr;
}
}
}
void renderer::CompLayer::renderMatteLayer(VPainter *painter, const VRle &mask,
const VRle & matteRle,
renderer::Layer *layer,
renderer::Layer *src,
SurfaceCache & cache)
{
VSize size = painter->clipBoundingRect().size();
// Decide if we can use fast matte.
// 1. draw src layer to matte buffer
VPainter srcPainter;
VBitmap srcBitmap = cache.make_surface(size.width(), size.height());
srcPainter.begin(&srcBitmap);
src->render(&srcPainter, mask, matteRle, cache);
srcPainter.end();
// 2. draw layer to layer buffer
VPainter layerPainter;
VBitmap layerBitmap = cache.make_surface(size.width(), size.height());
layerPainter.begin(&layerBitmap);
layer->render(&layerPainter, mask, matteRle, cache);
// 2.1update composition mode
switch (layer->matteType()) {
case model::MatteType::Alpha:
case model::MatteType::Luma: {
layerPainter.setBlendMode(BlendMode::DestIn);
break;
}
case model::MatteType::AlphaInv:
case model::MatteType::LumaInv: {
layerPainter.setBlendMode(BlendMode::DestOut);
break;
}
default:
break;
}
// 2.2 update srcBuffer if the matte is luma type
if (layer->matteType() == model::MatteType::Luma ||
layer->matteType() == model::MatteType::LumaInv) {
srcBitmap.updateLuma();
}
auto clip = layerPainter.clipBoundingRect();
// if the layer has only one renderer then use it as the clip rect
// when blending 2 buffer and copy back to final buffer to avoid
// unnecessary pixel processing.
if (layer->renderList().size() == 1)
{
clip = layer->renderList()[0]->rle().boundingRect();
}
// 2.3 draw src buffer as mask
layerPainter.drawBitmap(clip, srcBitmap, clip);
layerPainter.end();
// 3. draw the result buffer into painter
painter->drawBitmap(clip, layerBitmap, clip);
cache.release_surface(srcBitmap);
cache.release_surface(layerBitmap);
}
void renderer::Clipper::update(const VMatrix &matrix)
{
mPath.reset();
mPath.addRect(VRectF(0, 0, mSize.width(), mSize.height()));
mPath.transform(matrix);
mRasterRequest = true;
}
void renderer::Clipper::preprocess(const VRect &clip)
{
if (mRasterRequest) mRasterizer.rasterize(mPath, FillRule::Winding, clip);
mRasterRequest = false;
}
VRle renderer::Clipper::rle(const VRle &mask)
{
if (mask.empty()) return mRasterizer.rle();
mMaskedRle.clone(mask);
mMaskedRle &= mRasterizer.rle();
return mMaskedRle;
}
void renderer::CompLayer::updateContent()
{
if (mClipper && flag().testFlag(DirtyFlagBit::Matrix)) {
mClipper->update(combinedMatrix());
}
int mappedFrame = mLayerData->timeRemap(frameNo());
float alpha = combinedAlpha();
if (complexContent()) alpha = 1;
for (const auto &layer : mLayers) {
layer->update(mappedFrame, combinedMatrix(), alpha);
}
}
void renderer::CompLayer::preprocessStage(const VRect &clip)
{
// if layer has clipper
if (mClipper) mClipper->preprocess(clip);
renderer::Layer *matte = nullptr;
for (const auto &layer : mLayers) {
if (layer->hasMatte()) {
matte = layer;
} else {
if (layer->visible()) {
if (matte) {
if (matte->visible()) {
layer->preprocess(clip);
matte->preprocess(clip);
}
} else {
layer->preprocess(clip);
}
}
matte = nullptr;
}
}
}
renderer::SolidLayer::SolidLayer(model::Layer *layerData)
: renderer::Layer(layerData)
{
mDrawableList = &mRenderNode;
}
void renderer::SolidLayer::updateContent()
{
if (flag() & DirtyFlagBit::Matrix) {
mPath.reset();
mPath.addRect(VRectF(0, 0, mLayerData->layerSize().width(),
mLayerData->layerSize().height()));
mPath.transform(combinedMatrix());
mRenderNode.mFlag |= VDrawable::DirtyState::Path;
mRenderNode.mPath = mPath;
}
if (flag() & DirtyFlagBit::Alpha) {
model::Color color = mLayerData->solidColor();
VBrush brush(color.toColor(combinedAlpha()));
mRenderNode.setBrush(brush);
mRenderNode.mFlag |= VDrawable::DirtyState::Brush;
}
}
void renderer::SolidLayer::preprocessStage(const VRect &clip)
{
mRenderNode.preprocess(clip);
}
renderer::DrawableList renderer::SolidLayer::renderList()
{
if (skipRendering()) return {};
return {&mDrawableList, 1};
}
renderer::ImageLayer::ImageLayer(model::Layer *layerData)
: renderer::Layer(layerData)
{
mDrawableList = &mRenderNode;
if (!mLayerData->asset()) return;
mTexture.mBitmap = mLayerData->asset()->bitmap();
VBrush brush(&mTexture);
mRenderNode.setBrush(brush);
}
void renderer::ImageLayer::updateContent()
{
if (!mLayerData->asset()) return;
if (flag() & DirtyFlagBit::Matrix) {
mPath.reset();
mPath.addRect(VRectF(0, 0, mLayerData->asset()->mWidth,
mLayerData->asset()->mHeight));
mPath.transform(combinedMatrix());
mRenderNode.mFlag |= VDrawable::DirtyState::Path;
mRenderNode.mPath = mPath;
mTexture.mMatrix = combinedMatrix();
}
if (flag() & DirtyFlagBit::Alpha) {
mTexture.mAlpha = int(combinedAlpha() * 255);
}
}
void renderer::ImageLayer::preprocessStage(const VRect &clip)
{
mRenderNode.preprocess(clip);
}
renderer::DrawableList renderer::ImageLayer::renderList()
{
if (skipRendering()) return {};
return {&mDrawableList, 1};
}
renderer::NullLayer::NullLayer(model::Layer *layerData)
: renderer::Layer(layerData)
{
}
void renderer::NullLayer::updateContent() {}
static renderer::Object *createContentItem(model::Object *contentData,
VArenaAlloc * allocator)
{
switch (contentData->type()) {
case model::Object::Type::Group: {
return allocator->make<renderer::Group>(
static_cast<model::Group *>(contentData), allocator);
}
case model::Object::Type::Rect: {
return allocator->make<renderer::Rect>(
static_cast<model::Rect *>(contentData));
}
case model::Object::Type::Ellipse: {
return allocator->make<renderer::Ellipse>(
static_cast<model::Ellipse *>(contentData));
}
case model::Object::Type::Path: {
return allocator->make<renderer::Path>(
static_cast<model::Path *>(contentData));
}
case model::Object::Type::Polystar: {
return allocator->make<renderer::Polystar>(
static_cast<model::Polystar *>(contentData));
}
case model::Object::Type::Fill: {
return allocator->make<renderer::Fill>(
static_cast<model::Fill *>(contentData));
}
case model::Object::Type::GFill: {
return allocator->make<renderer::GradientFill>(
static_cast<model::GradientFill *>(contentData));
}
case model::Object::Type::Stroke: {
return allocator->make<renderer::Stroke>(
static_cast<model::Stroke *>(contentData));
}
case model::Object::Type::GStroke: {
return allocator->make<renderer::GradientStroke>(
static_cast<model::GradientStroke *>(contentData));
}
case model::Object::Type::Repeater: {
return allocator->make<renderer::Repeater>(
static_cast<model::Repeater *>(contentData), allocator);
}
case model::Object::Type::Trim: {
return allocator->make<renderer::Trim>(
static_cast<model::Trim *>(contentData));
}
default:
return nullptr;
break;
}
}
renderer::ShapeLayer::ShapeLayer(model::Layer *layerData,
VArenaAlloc * allocator)
: renderer::Layer(layerData),
mRoot(allocator->make<renderer::Group>(nullptr, allocator))
{
mRoot->addChildren(layerData, allocator);
std::vector<renderer::Shape *> list;
mRoot->processPaintItems(list);
if (layerData->hasPathOperator()) {
list.clear();
mRoot->processTrimItems(list);
}
}
void renderer::ShapeLayer::updateContent()
{
mRoot->update(frameNo(), combinedMatrix(), combinedAlpha(), flag());
if (mLayerData->hasPathOperator()) {
mRoot->applyTrim();
}
}
void renderer::ShapeLayer::preprocessStage(const VRect &clip)
{
mDrawableList.clear();
mRoot->renderList(mDrawableList);
for (auto &drawable : mDrawableList) drawable->preprocess(clip);
}
renderer::DrawableList renderer::ShapeLayer::renderList()
{
if (skipRendering()) return {};
mDrawableList.clear();
mRoot->renderList(mDrawableList);
if (mDrawableList.empty()) return {};
return {mDrawableList.data(), mDrawableList.size()};
}
bool renderer::Group::resolveKeyPath(LOTKeyPath &keyPath, uint32_t depth,
LOTVariant &value)
{
if (!keyPath.skip(name())) {
if (!keyPath.matches(mModel.name(), depth)) {
return false;
}
if (!keyPath.skip(mModel.name())) {
if (keyPath.fullyResolvesTo(mModel.name(), depth) &&
transformProp(value.property())) {
mModel.filter()->addValue(value);
}
}
}
if (keyPath.propagate(name(), depth)) {
uint32_t newDepth = keyPath.nextDepth(name(), depth);
for (auto &child : mContents) {
child->resolveKeyPath(keyPath, newDepth, value);
}
}
return true;
}
bool renderer::Fill::resolveKeyPath(LOTKeyPath &keyPath, uint32_t depth,
LOTVariant &value)
{
if (!keyPath.matches(mModel.name(), depth)) {
return false;
}
if (keyPath.fullyResolvesTo(mModel.name(), depth) &&
fillProp(value.property())) {
mModel.filter()->addValue(value);
return true;
}
return false;
}
bool renderer::Stroke::resolveKeyPath(LOTKeyPath &keyPath, uint32_t depth,
LOTVariant &value)
{
if (!keyPath.matches(mModel.name(), depth)) {
return false;
}
if (keyPath.fullyResolvesTo(mModel.name(), depth) &&
strokeProp(value.property())) {
mModel.filter()->addValue(value);
return true;
}
return false;
}
renderer::Group::Group(model::Group *data, VArenaAlloc *allocator)
: mModel(data)
{
addChildren(data, allocator);
}
void renderer::Group::addChildren(model::Group *data, VArenaAlloc *allocator)
{
if (!data) return;
if (!data->mChildren.empty()) mContents.reserve(data->mChildren.size());
// keep the content in back-to-front order.
// as lottie model keeps it in front-to-back order.
for (auto it = data->mChildren.crbegin(); it != data->mChildren.rend();
++it) {
auto content = createContentItem(*it, allocator);
if (content) {
mContents.push_back(content);
}
}
}
void renderer::Group::update(int frameNo, const VMatrix &parentMatrix,
float parentAlpha, const DirtyFlag &flag)
{
DirtyFlag newFlag = flag;
float alpha;
if (mModel.hasModel() && mModel.transform()) {
VMatrix m = mModel.matrix(frameNo);
m *= parentMatrix;
if (!(flag & DirtyFlagBit::Matrix) && !mModel.transform()->isStatic() &&
(m != mMatrix)) {
newFlag |= DirtyFlagBit::Matrix;
}
mMatrix = m;
alpha = parentAlpha * mModel.transform()->opacity(frameNo);
if (!vCompare(alpha, parentAlpha)) {
newFlag |= DirtyFlagBit::Alpha;
}
} else {
mMatrix = parentMatrix;
alpha = parentAlpha;
}
for (const auto &content : mContents) {
content->update(frameNo, matrix(), alpha, newFlag);
}
}
void renderer::Group::applyTrim()
{
for (auto i = mContents.rbegin(); i != mContents.rend(); ++i) {
auto content = (*i);
switch (content->type()) {
case renderer::Object::Type::Trim: {
static_cast<renderer::Trim *>(content)->update();
break;
}
case renderer::Object::Type::Group: {
static_cast<renderer::Group *>(content)->applyTrim();
break;
}
default:
break;
}
}
}
void renderer::Group::renderList(std::vector<VDrawable *> &list)
{
for (const auto &content : mContents) {
content->renderList(list);
}
}
void renderer::Group::processPaintItems(std::vector<renderer::Shape *> &list)
{
size_t curOpCount = list.size();
for (auto i = mContents.rbegin(); i != mContents.rend(); ++i) {
auto content = (*i);
switch (content->type()) {
case renderer::Object::Type::Shape: {
auto pathItem = static_cast<renderer::Shape *>(content);
pathItem->setParent(this);
list.push_back(pathItem);
break;
}
case renderer::Object::Type::Paint: {
static_cast<renderer::Paint *>(content)->addPathItems(list,
curOpCount);
break;
}
case renderer::Object::Type::Group: {
static_cast<renderer::Group *>(content)->processPaintItems(list);
break;
}
default:
break;
}
}
}
void renderer::Group::processTrimItems(std::vector<renderer::Shape *> &list)
{
size_t curOpCount = list.size();
for (auto i = mContents.rbegin(); i != mContents.rend(); ++i) {
auto content = (*i);
switch (content->type()) {
case renderer::Object::Type::Shape: {
list.push_back(static_cast<renderer::Shape *>(content));
break;
}
case renderer::Object::Type::Trim: {
static_cast<renderer::Trim *>(content)->addPathItems(list,
curOpCount);
break;
}
case renderer::Object::Type::Group: {
static_cast<renderer::Group *>(content)->processTrimItems(list);
break;
}
default:
break;
}
}
}
/*
* renderer::Shape uses 2 path objects for path object reuse.
* mLocalPath - keeps track of the local path of the item before
* applying path operation and transformation.
* mTemp - keeps a referece to the mLocalPath and can be updated by the
* path operation objects(trim, merge path),
* We update the DirtyPath flag if the path needs to be updated again
* beacuse of local path or matrix or some path operation has changed which
* affects the final path.
* The PaintObject queries the dirty flag to check if it needs to compute the
* final path again and calls finalPath() api to do the same.
* finalPath() api passes a result Object so that we keep only one copy of
* the path object in the paintItem (for memory efficiency).
* NOTE: As path objects are COW objects we have to be
* carefull about the refcount so that we don't generate deep copy while
* modifying the path objects.
*/
void renderer::Shape::update(int frameNo, const VMatrix &, float,
const DirtyFlag &flag)
{
mDirtyPath = false;
// 1. update the local path if needed
if (hasChanged(frameNo)) {
// loose the reference to mLocalPath if any
// from the last frame update.
mTemp = VPath();
updatePath(mLocalPath, frameNo);
mDirtyPath = true;
}
// 2. keep a reference path in temp in case there is some
// path operation like trim which will update the path.
// we don't want to update the local path.
mTemp = mLocalPath;
// 3. mark the path dirty if matrix has changed.
if (flag & DirtyFlagBit::Matrix) {
mDirtyPath = true;
}
}
void renderer::Shape::finalPath(VPath &result)
{
result.addPath(mTemp, static_cast<renderer::Group *>(parent())->matrix());
}
renderer::Rect::Rect(model::Rect *data)
: renderer::Shape(data->isStatic()), mData(data)
{
}
void renderer::Rect::updatePath(VPath &path, int frameNo)
{
VPointF pos = mData->mPos.value(frameNo);
VPointF size = mData->mSize.value(frameNo);
float roundness = mData->roundness(frameNo);
VRectF r(pos.x() - size.x() / 2, pos.y() - size.y() / 2, size.x(),
size.y());
path.reset();
path.addRoundRect(r, roundness, mData->direction());
}
renderer::Ellipse::Ellipse(model::Ellipse *data)
: renderer::Shape(data->isStatic()), mData(data)
{
}
void renderer::Ellipse::updatePath(VPath &path, int frameNo)
{
VPointF pos = mData->mPos.value(frameNo);
VPointF size = mData->mSize.value(frameNo);
VRectF r(pos.x() - size.x() / 2, pos.y() - size.y() / 2, size.x(),
size.y());
path.reset();
path.addOval(r, mData->direction());
}
renderer::Path::Path(model::Path *data)
: renderer::Shape(data->isStatic()), mData(data)
{
}
void renderer::Path::updatePath(VPath &path, int frameNo)
{
mData->mShape.value(frameNo, path);
}
renderer::Polystar::Polystar(model::Polystar *data)
: renderer::Shape(data->isStatic()), mData(data)
{
}
void renderer::Polystar::updatePath(VPath &path, int frameNo)
{
VPointF pos = mData->mPos.value(frameNo);
float points = mData->mPointCount.value(frameNo);
float innerRadius = mData->mInnerRadius.value(frameNo);
float outerRadius = mData->mOuterRadius.value(frameNo);
float innerRoundness = mData->mInnerRoundness.value(frameNo);
float outerRoundness = mData->mOuterRoundness.value(frameNo);
float rotation = mData->mRotation.value(frameNo);
path.reset();
VMatrix m;
if (mData->mPolyType == model::Polystar::PolyType::Star) {
path.addPolystar(points, innerRadius, outerRadius, innerRoundness,
outerRoundness, 0.0, 0.0, 0.0, mData->direction());
} else {
path.addPolygon(points, outerRadius, outerRoundness, 0.0, 0.0, 0.0,
mData->direction());
}
m.translate(pos.x(), pos.y()).rotate(rotation);
m.rotate(rotation);
path.transform(m);
}
/*
* PaintData Node handling
*
*/
renderer::Paint::Paint(bool staticContent) : mStaticContent(staticContent) {}
void renderer::Paint::update(int frameNo, const VMatrix &parentMatrix,
float parentAlpha, const DirtyFlag & /*flag*/)
{
mRenderNodeUpdate = true;
mContentToRender = updateContent(frameNo, parentMatrix, parentAlpha);
}
void renderer::Paint::updateRenderNode()
{
bool dirty = false;
for (auto &i : mPathItems) {
if (i->dirty()) {
dirty = true;
break;
}
}
if (dirty) {
mPath.reset();
for (const auto &i : mPathItems) {
i->finalPath(mPath);
}
mDrawable.setPath(mPath);
} else {
if (mDrawable.mFlag & VDrawable::DirtyState::Path)
mDrawable.mPath = mPath;
}
}
void renderer::Paint::renderList(std::vector<VDrawable *> &list)
{
if (mRenderNodeUpdate) {
updateRenderNode();
mRenderNodeUpdate = false;
}
// Q: Why we even update the final path if we don't have content
// to render ?
// Ans: We update the render nodes because we will loose the
// dirty path information at end of this frame.
// so if we return early without updating the final path.
// in the subsequent frame when we have content to render but
// we may not able to update our final path properly as we
// don't know what paths got changed in between.
if (mContentToRender) list.push_back(&mDrawable);
}
void renderer::Paint::addPathItems(std::vector<renderer::Shape *> &list,
size_t startOffset)
{
std::copy(list.begin() + startOffset, list.end(),
back_inserter(mPathItems));
}
renderer::Fill::Fill(model::Fill *data)
: renderer::Paint(data->isStatic()), mModel(data)
{
mDrawable.setName(mModel.name());
}
bool renderer::Fill::updateContent(int frameNo, const VMatrix &, float alpha)
{
auto combinedAlpha = alpha * mModel.opacity(frameNo);
auto color = mModel.color(frameNo).toColor(combinedAlpha);
VBrush brush(color);
mDrawable.setBrush(brush);
mDrawable.setFillRule(mModel.fillRule());
return !color.isTransparent();
}
renderer::GradientFill::GradientFill(model::GradientFill *data)
: renderer::Paint(data->isStatic()), mData(data)
{
mDrawable.setName(mData->name());
}
bool renderer::GradientFill::updateContent(int frameNo, const VMatrix &matrix,
float alpha)
{
float combinedAlpha = alpha * mData->opacity(frameNo);
mData->update(mGradient, frameNo);
mGradient->setAlpha(combinedAlpha);
mGradient->mMatrix = matrix;
mDrawable.setBrush(VBrush(mGradient.get()));
mDrawable.setFillRule(mData->fillRule());
return !vIsZero(combinedAlpha);
}
renderer::Stroke::Stroke(model::Stroke *data)
: renderer::Paint(data->isStatic()), mModel(data)
{
mDrawable.setName(mModel.name());
if (mModel.hasDashInfo()) {
mDrawable.setType(VDrawable::Type::StrokeWithDash);
} else {
mDrawable.setType(VDrawable::Type::Stroke);
}
}
static vthread_local std::vector<float> Dash_Vector;
bool renderer::Stroke::updateContent(int frameNo, const VMatrix &matrix,
float alpha)
{
auto combinedAlpha = alpha * mModel.opacity(frameNo);
auto color = mModel.color(frameNo).toColor(combinedAlpha);
VBrush brush(color);
mDrawable.setBrush(brush);
float scale = matrix.scale();
mDrawable.setStrokeInfo(mModel.capStyle(), mModel.joinStyle(),
mModel.miterLimit(),
mModel.strokeWidth(frameNo) * scale);
if (mModel.hasDashInfo()) {
Dash_Vector.clear();
mModel.getDashInfo(frameNo, Dash_Vector);
if (!Dash_Vector.empty()) {
for (auto &elm : Dash_Vector) elm *= scale;
mDrawable.setDashInfo(Dash_Vector);
}
}
return !color.isTransparent();
}
renderer::GradientStroke::GradientStroke(model::GradientStroke *data)
: renderer::Paint(data->isStatic()), mData(data)
{
mDrawable.setName(mData->name());
if (mData->hasDashInfo()) {
mDrawable.setType(VDrawable::Type::StrokeWithDash);
} else {
mDrawable.setType(VDrawable::Type::Stroke);
}
}
bool renderer::GradientStroke::updateContent(int frameNo, const VMatrix &matrix,
float alpha)
{
float combinedAlpha = alpha * mData->opacity(frameNo);
mData->update(mGradient, frameNo);
mGradient->setAlpha(combinedAlpha);
mGradient->mMatrix = matrix;
auto scale = mGradient->mMatrix.scale();
mDrawable.setBrush(VBrush(mGradient.get()));
mDrawable.setStrokeInfo(mData->capStyle(), mData->joinStyle(),
mData->miterLimit(), mData->width(frameNo) * scale);
if (mData->hasDashInfo()) {
Dash_Vector.clear();
mData->getDashInfo(frameNo, Dash_Vector);
if (!Dash_Vector.empty()) {
for (auto &elm : Dash_Vector) elm *= scale;
mDrawable.setDashInfo(Dash_Vector);
}
}
return !vIsZero(combinedAlpha);
}
void renderer::Trim::update(int frameNo, const VMatrix & /*parentMatrix*/,
float /*parentAlpha*/, const DirtyFlag & /*flag*/)
{
mDirty = false;
if (mCache.mFrameNo == frameNo) return;
model::Trim::Segment segment = mData->segment(frameNo);
if (!(vCompare(mCache.mSegment.start, segment.start) &&
vCompare(mCache.mSegment.end, segment.end))) {
mDirty = true;
mCache.mSegment = segment;
}
mCache.mFrameNo = frameNo;
}
void renderer::Trim::update()
{
// when both path and trim are not dirty
if (!(mDirty || pathDirty())) return;
if (vCompare(mCache.mSegment.start, mCache.mSegment.end)) {
for (auto &i : mPathItems) {
i->updatePath(VPath());
}
return;
}
if (vCompare(std::fabs(mCache.mSegment.start - mCache.mSegment.end), 1)) {
for (auto &i : mPathItems) {
i->updatePath(i->localPath());
}
return;
}
if (mData->type() == model::Trim::TrimType::Simultaneously) {
for (auto &i : mPathItems) {
mPathMesure.setRange(mCache.mSegment.start, mCache.mSegment.end);
i->updatePath(mPathMesure.trim(i->localPath()));
}
} else { // model::Trim::TrimType::Individually
float totalLength = 0.0;
for (auto &i : mPathItems) {
totalLength += i->localPath().length();
}
float start = totalLength * mCache.mSegment.start;
float end = totalLength * mCache.mSegment.end;
if (start < end) {
float curLen = 0.0;
for (auto &i : mPathItems) {
if (curLen > end) {
// update with empty path.
i->updatePath(VPath());
continue;
}
float len = i->localPath().length();
if (curLen < start && curLen + len < start) {
curLen += len;
// update with empty path.
i->updatePath(VPath());
continue;
} else if (start <= curLen && end >= curLen + len) {
// inside segment
curLen += len;
continue;
} else {
float local_start = start > curLen ? start - curLen : 0;
local_start /= len;
float local_end = curLen + len < end ? len : end - curLen;
local_end /= len;
mPathMesure.setRange(local_start, local_end);
i->updatePath(mPathMesure.trim(i->localPath()));
curLen += len;
}
}
}
}
}
void renderer::Trim::addPathItems(std::vector<renderer::Shape *> &list,
size_t startOffset)
{
std::copy(list.begin() + startOffset, list.end(),
back_inserter(mPathItems));
}
renderer::Repeater::Repeater(model::Repeater *data, VArenaAlloc *allocator)
: mRepeaterData(data)
{
assert(mRepeaterData->content());
mCopies = mRepeaterData->maxCopies();
for (int i = 0; i < mCopies; i++) {
auto content = allocator->make<renderer::Group>(
mRepeaterData->content(), allocator);
// content->setParent(this);
mContents.push_back(content);
}
}
void renderer::Repeater::update(int frameNo, const VMatrix &parentMatrix,
float parentAlpha, const DirtyFlag &flag)
{
DirtyFlag newFlag = flag;
float copies = mRepeaterData->copies(frameNo);
int visibleCopies = int(copies);
if (visibleCopies == 0) {
mHidden = true;
return;
}
mHidden = false;
if (!mRepeaterData->isStatic()) newFlag |= DirtyFlagBit::Matrix;
float offset = mRepeaterData->offset(frameNo);
float startOpacity = mRepeaterData->mTransform.startOpacity(frameNo);
float endOpacity = mRepeaterData->mTransform.endOpacity(frameNo);
newFlag |= DirtyFlagBit::Alpha;
for (int i = 0; i < mCopies; ++i) {
float newAlpha =
parentAlpha * lerp(startOpacity, endOpacity, i / copies);
// hide rest of the copies , @TODO find a better solution.
if (i >= visibleCopies) newAlpha = 0;
VMatrix result = mRepeaterData->mTransform.matrix(frameNo, i + offset) *
parentMatrix;
mContents[i]->update(frameNo, result, newAlpha, newFlag);
}
}
void renderer::Repeater::renderList(std::vector<VDrawable *> &list)
{
if (mHidden) return;
return renderer::Group::renderList(list);
}
| 45,195 | lottieitem | cpp | en | cpp | code | {"qsc_code_num_words": 4478, "qsc_code_num_chars": 45195.0, "qsc_code_mean_word_length": 5.94305494, "qsc_code_frac_words_unique": 0.15207682, "qsc_code_frac_chars_top_2grams": 0.01938902, "qsc_code_frac_chars_top_3grams": 0.01420358, "qsc_code_frac_chars_top_4grams": 0.01623267, "qsc_code_frac_chars_dupe_5grams": 0.37113441, "qsc_code_frac_chars_dupe_6grams": 0.31943035, "qsc_code_frac_chars_dupe_7grams": 0.27456506, "qsc_code_frac_chars_dupe_8grams": 0.2558524, "qsc_code_frac_chars_dupe_9grams": 0.2251907, "qsc_code_frac_chars_dupe_10grams": 0.21241499, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00380042, "qsc_code_frac_chars_whitespace": 0.27806173, "qsc_code_size_file_byte": 45195.0, "qsc_code_num_lines": 1491.0, "qsc_code_num_chars_line_max": 81.0, "qsc_code_num_chars_line_mean": 30.31187123, "qsc_code_frac_chars_alphabet": 0.81181807, "qsc_code_frac_chars_comments": 0.11215842, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.29297206, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00137072, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.00134138, "qsc_code_frac_lines_assert": 0.00084674, "qsc_codecpp_frac_lines_preprocessor_directives": 0.00677392, "qsc_codecpp_frac_lines_func_ratio": 0.01354784, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.04911092, "qsc_codecpp_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/lottieitem.h | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef LOTTIEITEM_H
#define LOTTIEITEM_H
#include <memory>
#include <sstream>
#include "lottiekeypath.h"
#include "lottiefiltermodel.h"
#include "rlottie.h"
#include "rlottiecommon.h"
#include "varenaalloc.h"
#include "vdrawable.h"
#include "vmatrix.h"
#include "vpainter.h"
#include "vpath.h"
#include "vpathmesure.h"
#include "vpoint.h"
V_USE_NAMESPACE
namespace rlottie {
namespace internal {
template <class T>
class VSpan {
public:
using reference = T &;
using pointer = T *;
using const_pointer = T const *;
using const_reference = T const &;
using index_type = size_t;
using iterator = pointer;
using const_iterator = const_pointer;
VSpan() = default;
VSpan(pointer data, index_type size) : _data(data), _size(size) {}
constexpr pointer data() const noexcept { return _data; }
constexpr index_type size() const noexcept { return _size; }
constexpr bool empty() const noexcept { return size() == 0; }
constexpr iterator begin() const noexcept { return data(); }
constexpr iterator end() const noexcept { return data() + size(); }
constexpr const_iterator cbegin() const noexcept { return data(); }
constexpr const_iterator cend() const noexcept { return data() + size(); }
constexpr reference operator[](index_type idx) const
{
return *(data() + idx);
}
private:
pointer _data{nullptr};
index_type _size{0};
};
namespace renderer {
using DrawableList = VSpan<VDrawable *>;
enum class DirtyFlagBit : uint8_t {
None = 0x00,
Matrix = 0x01,
Alpha = 0x02,
All = (Matrix | Alpha)
};
typedef vFlag<DirtyFlagBit> DirtyFlag;
class SurfaceCache {
public:
SurfaceCache() { mCache.reserve(10); }
VBitmap make_surface(
size_t width, size_t height,
VBitmap::Format format = VBitmap::Format::ARGB32_Premultiplied)
{
if (mCache.empty()) return {width, height, format};
auto surface = mCache.back();
surface.reset(width, height, format);
mCache.pop_back();
return surface;
}
void release_surface(VBitmap &surface) { mCache.push_back(surface); }
private:
std::vector<VBitmap> mCache;
};
class Drawable final : public VDrawable {
public:
void sync();
public:
std::unique_ptr<LOTNode> mCNode{nullptr};
~Drawable() noexcept
{
if (mCNode && mCNode->mGradient.stopPtr)
free(mCNode->mGradient.stopPtr);
}
};
struct CApiData {
CApiData();
LOTLayerNode mLayer;
std::vector<LOTMask> mMasks;
std::vector<LOTLayerNode *> mLayers;
std::vector<LOTNode *> mCNodeList;
};
class Clipper {
public:
explicit Clipper(VSize size) : mSize(size) {}
void update(const VMatrix &matrix);
void preprocess(const VRect &clip);
VRle rle(const VRle &mask);
public:
VSize mSize;
VPath mPath;
VRle mMaskedRle;
VRasterizer mRasterizer;
bool mRasterRequest{false};
};
class Mask {
public:
explicit Mask(model::Mask *data) : mData(data) {}
void update(int frameNo, const VMatrix &parentMatrix, float parentAlpha,
const DirtyFlag &flag);
model::Mask::Mode maskMode() const { return mData->mMode; }
VRle rle();
void preprocess(const VRect &clip);
bool inverted() const { return mData->mInv; }
public:
model::Mask *mData{nullptr};
VPath mLocalPath;
VPath mFinalPath;
VRasterizer mRasterizer;
float mCombinedAlpha{0};
bool mRasterRequest{false};
};
/*
* Handels mask property of a layer item
*/
class LayerMask {
public:
explicit LayerMask(model::Layer *layerData);
void update(int frameNo, const VMatrix &parentMatrix, float parentAlpha,
const DirtyFlag &flag);
bool isStatic() const { return mStatic; }
VRle maskRle(const VRect &clipRect);
void preprocess(const VRect &clip);
public:
std::vector<Mask> mMasks;
VRle mRle;
bool mStatic{true};
bool mDirty{true};
};
class Layer;
class Composition {
public:
explicit Composition(std::shared_ptr<model::Composition> composition);
bool update(int frameNo, const VSize &size, bool keepAspectRatio);
VSize size() const { return mViewSize; }
void buildRenderTree();
const LOTLayerNode *renderTree() const;
bool render(const rlottie::Surface &surface);
void setValue(const std::string &keypath, LOTVariant &value);
private:
SurfaceCache mSurfaceCache;
VBitmap mSurface;
VMatrix mScaleMatrix;
VSize mViewSize;
std::shared_ptr<model::Composition> mModel;
Layer * mRootLayer{nullptr};
VArenaAlloc mAllocator{2048};
int mCurFrameNo;
bool mKeepAspectRatio{true};
};
class Layer {
public:
virtual ~Layer() = default;
Layer &operator=(Layer &&) noexcept = delete;
Layer(model::Layer *layerData);
int id() const { return mLayerData->id(); }
int parentId() const { return mLayerData->parentId(); }
void setParentLayer(Layer *parent) { mParentLayer = parent; }
void setComplexContent(bool value) { mComplexContent = value; }
bool complexContent() const { return mComplexContent; }
virtual void update(int frameNo, const VMatrix &parentMatrix,
float parentAlpha);
VMatrix matrix(int frameNo) const;
void preprocess(const VRect &clip);
virtual DrawableList renderList() { return {}; }
virtual void render(VPainter *painter, const VRle &mask,
const VRle &matteRle, SurfaceCache &cache);
bool hasMatte()
{
if (mLayerData->mMatteType == model::MatteType::None) return false;
return true;
}
model::MatteType matteType() const { return mLayerData->mMatteType; }
bool visible() const;
virtual void buildLayerNode();
LOTLayerNode & clayer() { return mCApiData->mLayer; }
std::vector<LOTLayerNode *> &clayers() { return mCApiData->mLayers; }
std::vector<LOTMask> & cmasks() { return mCApiData->mMasks; }
std::vector<LOTNode *> & cnodes() { return mCApiData->mCNodeList; }
const char * name() const { return mLayerData->name(); }
virtual bool resolveKeyPath(LOTKeyPath &keyPath, uint32_t depth,
LOTVariant &value);
protected:
virtual void preprocessStage(const VRect &clip) = 0;
virtual void updateContent() = 0;
inline VMatrix combinedMatrix() const { return mCombinedMatrix; }
inline int frameNo() const { return mFrameNo; }
inline float combinedAlpha() const { return mCombinedAlpha; }
inline bool isStatic() const { return mLayerData->isStatic(); }
float opacity(int frameNo) const { return mLayerData->opacity(frameNo); }
inline DirtyFlag flag() const { return mDirtyFlag; }
bool skipRendering() const
{
return (!visible() || vIsZero(combinedAlpha()));
}
protected:
std::unique_ptr<LayerMask> mLayerMask;
model::Layer * mLayerData{nullptr};
Layer * mParentLayer{nullptr};
VMatrix mCombinedMatrix;
float mCombinedAlpha{0.0};
int mFrameNo{-1};
DirtyFlag mDirtyFlag{DirtyFlagBit::All};
bool mComplexContent{false};
std::unique_ptr<CApiData> mCApiData;
};
class CompLayer final : public Layer {
public:
explicit CompLayer(model::Layer *layerData, VArenaAlloc *allocator);
void render(VPainter *painter, const VRle &mask, const VRle &matteRle,
SurfaceCache &cache) final;
void buildLayerNode() final;
bool resolveKeyPath(LOTKeyPath &keyPath, uint32_t depth,
LOTVariant &value) override;
protected:
void preprocessStage(const VRect &clip) final;
void updateContent() final;
private:
void renderHelper(VPainter *painter, const VRle &mask, const VRle &matteRle,
SurfaceCache &cache);
void renderMatteLayer(VPainter *painter, const VRle &inheritMask,
const VRle &matteRle, Layer *layer, Layer *src,
SurfaceCache &cache);
private:
std::vector<Layer *> mLayers;
std::unique_ptr<Clipper> mClipper;
};
class SolidLayer final : public Layer {
public:
explicit SolidLayer(model::Layer *layerData);
void buildLayerNode() final;
DrawableList renderList() final;
protected:
void preprocessStage(const VRect &clip) final;
void updateContent() final;
private:
Drawable mRenderNode;
VPath mPath;
VDrawable *mDrawableList{nullptr}; // to work with the Span api
};
class Group;
class ShapeLayer final : public Layer {
public:
explicit ShapeLayer(model::Layer *layerData, VArenaAlloc *allocator);
DrawableList renderList() final;
void buildLayerNode() final;
bool resolveKeyPath(LOTKeyPath &keyPath, uint32_t depth,
LOTVariant &value) override;
protected:
void preprocessStage(const VRect &clip) final;
void updateContent() final;
std::vector<VDrawable *> mDrawableList;
Group * mRoot{nullptr};
};
class NullLayer final : public Layer {
public:
explicit NullLayer(model::Layer *layerData);
protected:
void preprocessStage(const VRect &) final {}
void updateContent() final;
};
class ImageLayer final : public Layer {
public:
explicit ImageLayer(model::Layer *layerData);
void buildLayerNode() final;
DrawableList renderList() final;
protected:
void preprocessStage(const VRect &clip) final;
void updateContent() final;
private:
Drawable mRenderNode;
VTexture mTexture;
VPath mPath;
VDrawable *mDrawableList{nullptr}; // to work with the Span api
};
class Object {
public:
enum class Type : uint8_t { Unknown, Group, Shape, Paint, Trim };
virtual ~Object() = default;
Object & operator=(Object &&) noexcept = delete;
virtual void update(int frameNo, const VMatrix &parentMatrix,
float parentAlpha, const DirtyFlag &flag) = 0;
virtual void renderList(std::vector<VDrawable *> &) {}
virtual bool resolveKeyPath(LOTKeyPath &, uint32_t, LOTVariant &)
{
return false;
}
virtual Object::Type type() const { return Object::Type::Unknown; }
};
class Shape;
class Group : public Object {
public:
Group() = default;
explicit Group(model::Group *data, VArenaAlloc *allocator);
void addChildren(model::Group *data, VArenaAlloc *allocator);
void update(int frameNo, const VMatrix &parentMatrix, float parentAlpha,
const DirtyFlag &flag) override;
void applyTrim();
void processTrimItems(std::vector<Shape *> &list);
void processPaintItems(std::vector<Shape *> &list);
void renderList(std::vector<VDrawable *> &list) override;
Object::Type type() const final { return Object::Type::Group; }
const VMatrix &matrix() const { return mMatrix; }
const char * name() const
{
static const char *TAG = "__";
return mModel.hasModel() ? mModel.name() : TAG;
}
bool resolveKeyPath(LOTKeyPath &keyPath, uint32_t depth,
LOTVariant &value) override;
protected:
std::vector<Object *> mContents;
VMatrix mMatrix;
private:
model::Filter<model::Group> mModel;
};
class Shape : public Object {
public:
Shape(bool staticPath) : mStaticPath(staticPath) {}
void update(int frameNo, const VMatrix &parentMatrix, float parentAlpha,
const DirtyFlag &flag) final;
Object::Type type() const final { return Object::Type::Shape; }
bool dirty() const { return mDirtyPath; }
const VPath &localPath() const { return mTemp; }
void finalPath(VPath &result);
void updatePath(const VPath &path)
{
mTemp = path;
mDirtyPath = true;
}
bool staticPath() const { return mStaticPath; }
void setParent(Group *parent) { mParent = parent; }
Group *parent() const { return mParent; }
protected:
virtual void updatePath(VPath &path, int frameNo) = 0;
virtual bool hasChanged(int prevFrame, int curFrame) = 0;
private:
bool hasChanged(int frameNo)
{
int prevFrame = mFrameNo;
mFrameNo = frameNo;
if (prevFrame == -1) return true;
if (mStaticPath || (prevFrame == frameNo)) return false;
return hasChanged(prevFrame, frameNo);
}
Group *mParent{nullptr};
VPath mLocalPath;
VPath mTemp;
int mFrameNo{-1};
bool mDirtyPath{true};
bool mStaticPath;
};
class Rect final : public Shape {
public:
explicit Rect(model::Rect *data);
protected:
void updatePath(VPath &path, int frameNo) final;
model::Rect *mData{nullptr};
bool hasChanged(int prevFrame, int curFrame) final
{
return (mData->mPos.changed(prevFrame, curFrame) ||
mData->mSize.changed(prevFrame, curFrame) ||
mData->roundnessChanged(prevFrame, curFrame));
}
};
class Ellipse final : public Shape {
public:
explicit Ellipse(model::Ellipse *data);
private:
void updatePath(VPath &path, int frameNo) final;
model::Ellipse *mData{nullptr};
bool hasChanged(int prevFrame, int curFrame) final
{
return (mData->mPos.changed(prevFrame, curFrame) ||
mData->mSize.changed(prevFrame, curFrame));
}
};
class Path final : public Shape {
public:
explicit Path(model::Path *data);
private:
void updatePath(VPath &path, int frameNo) final;
model::Path *mData{nullptr};
bool hasChanged(int prevFrame, int curFrame) final
{
return mData->mShape.changed(prevFrame, curFrame);
}
};
class Polystar final : public Shape {
public:
explicit Polystar(model::Polystar *data);
private:
void updatePath(VPath &path, int frameNo) final;
model::Polystar *mData{nullptr};
bool hasChanged(int prevFrame, int curFrame) final
{
return (mData->mPos.changed(prevFrame, curFrame) ||
mData->mPointCount.changed(prevFrame, curFrame) ||
mData->mInnerRadius.changed(prevFrame, curFrame) ||
mData->mOuterRadius.changed(prevFrame, curFrame) ||
mData->mInnerRoundness.changed(prevFrame, curFrame) ||
mData->mOuterRoundness.changed(prevFrame, curFrame) ||
mData->mRotation.changed(prevFrame, curFrame));
}
};
class Paint : public Object {
public:
Paint(bool staticContent);
void addPathItems(std::vector<Shape *> &list, size_t startOffset);
void update(int frameNo, const VMatrix &parentMatrix, float parentAlpha,
const DirtyFlag &flag) override;
void renderList(std::vector<VDrawable *> &list) final;
Object::Type type() const final { return Object::Type::Paint; }
protected:
virtual bool updateContent(int frameNo, const VMatrix &matrix,
float alpha) = 0;
private:
void updateRenderNode();
protected:
std::vector<Shape *> mPathItems;
Drawable mDrawable;
VPath mPath;
DirtyFlag mFlag;
bool mStaticContent;
bool mRenderNodeUpdate{true};
bool mContentToRender{true};
};
class Fill final : public Paint {
public:
explicit Fill(model::Fill *data);
protected:
bool updateContent(int frameNo, const VMatrix &matrix, float alpha) final;
bool resolveKeyPath(LOTKeyPath &keyPath, uint32_t depth,
LOTVariant &value) final;
private:
model::Filter<model::Fill> mModel;
};
class GradientFill final : public Paint {
public:
explicit GradientFill(model::GradientFill *data);
protected:
bool updateContent(int frameNo, const VMatrix &matrix, float alpha) final;
private:
model::GradientFill * mData{nullptr};
std::unique_ptr<VGradient> mGradient;
};
class Stroke : public Paint {
public:
explicit Stroke(model::Stroke *data);
protected:
bool updateContent(int frameNo, const VMatrix &matrix, float alpha) final;
bool resolveKeyPath(LOTKeyPath &keyPath, uint32_t depth,
LOTVariant &value) final;
private:
model::Filter<model::Stroke> mModel;
};
class GradientStroke final : public Paint {
public:
explicit GradientStroke(model::GradientStroke *data);
protected:
bool updateContent(int frameNo, const VMatrix &matrix, float alpha) final;
private:
model::GradientStroke * mData{nullptr};
std::unique_ptr<VGradient> mGradient;
};
class Trim final : public Object {
public:
explicit Trim(model::Trim *data) : mData(data) {}
void update(int frameNo, const VMatrix &parentMatrix, float parentAlpha,
const DirtyFlag &flag) final;
Object::Type type() const final { return Object::Type::Trim; }
void update();
void addPathItems(std::vector<Shape *> &list, size_t startOffset);
private:
bool pathDirty() const
{
for (auto &i : mPathItems) {
if (i->dirty()) return true;
}
return false;
}
struct Cache {
int mFrameNo{-1};
model::Trim::Segment mSegment{};
};
Cache mCache;
std::vector<Shape *> mPathItems;
model::Trim * mData{nullptr};
VPathMesure mPathMesure;
bool mDirty{true};
};
class Repeater final : public Group {
public:
explicit Repeater(model::Repeater *data, VArenaAlloc *allocator);
void update(int frameNo, const VMatrix &parentMatrix, float parentAlpha,
const DirtyFlag &flag) final;
void renderList(std::vector<VDrawable *> &list) final;
private:
model::Repeater *mRepeaterData{nullptr};
bool mHidden{false};
int mCopies{0};
};
} // namespace renderer
} // namespace internal
} // namespace rlottie
#endif // LOTTIEITEM_H
| 19,784 | lottieitem | h | en | c | code | {"qsc_code_num_words": 2016, "qsc_code_num_chars": 19784.0, "qsc_code_mean_word_length": 6.17857143, "qsc_code_frac_words_unique": 0.19990079, "qsc_code_frac_chars_top_2grams": 0.01926782, "qsc_code_frac_chars_top_3grams": 0.0216763, "qsc_code_frac_chars_top_4grams": 0.02472704, "qsc_code_frac_chars_dupe_5grams": 0.3717887, "qsc_code_frac_chars_dupe_6grams": 0.3039499, "qsc_code_frac_chars_dupe_7grams": 0.28580604, "qsc_code_frac_chars_dupe_8grams": 0.27994541, "qsc_code_frac_chars_dupe_9grams": 0.26573539, "qsc_code_frac_chars_dupe_10grams": 0.24470135, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00366224, "qsc_code_frac_chars_whitespace": 0.2684998, "qsc_code_size_file_byte": 19784.0, "qsc_code_num_lines": 626.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 31.60383387, "qsc_code_frac_chars_alphabet": 0.85703427, "qsc_code_frac_chars_comments": 0.06742822, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.36614173, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00710027, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00065041, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.2992126, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.36220472, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/lottieitem_capi.cpp | /*
* Implements LottieItem functions needed
* to support renderTree() api.
* Moving all those implementation to its own
* file make clear separation as well easy of
* maintenance.
*/
#include "lottieitem.h"
#include "vdasher.h"
using namespace rlottie::internal;
renderer::CApiData::CApiData()
{
mLayer.mMaskList.ptr = nullptr;
mLayer.mMaskList.size = 0;
mLayer.mLayerList.ptr = nullptr;
mLayer.mLayerList.size = 0;
mLayer.mNodeList.ptr = nullptr;
mLayer.mNodeList.size = 0;
mLayer.mMatte = MatteNone;
mLayer.mVisible = 0;
mLayer.mAlpha = 255;
mLayer.mClipPath.ptPtr = nullptr;
mLayer.mClipPath.elmPtr = nullptr;
mLayer.mClipPath.ptCount = 0;
mLayer.mClipPath.elmCount = 0;
mLayer.keypath = nullptr;
}
void renderer::Composition::buildRenderTree()
{
mRootLayer->buildLayerNode();
}
const LOTLayerNode *renderer::Composition::renderTree() const
{
return &mRootLayer->clayer();
}
void renderer::CompLayer::buildLayerNode()
{
renderer::Layer::buildLayerNode();
if (mClipper) {
const auto &elm = mClipper->mPath.elements();
const auto &pts = mClipper->mPath.points();
auto ptPtr = reinterpret_cast<const float *>(pts.data());
auto elmPtr = reinterpret_cast<const char *>(elm.data());
clayer().mClipPath.ptPtr = ptPtr;
clayer().mClipPath.elmPtr = elmPtr;
clayer().mClipPath.ptCount = 2 * pts.size();
clayer().mClipPath.elmCount = elm.size();
}
if (mLayers.size() != clayers().size()) {
for (const auto &layer : mLayers) {
layer->buildLayerNode();
clayers().push_back(&layer->clayer());
}
clayer().mLayerList.ptr = clayers().data();
clayer().mLayerList.size = clayers().size();
} else {
for (const auto &layer : mLayers) {
layer->buildLayerNode();
}
}
}
void renderer::ShapeLayer::buildLayerNode()
{
renderer::Layer::buildLayerNode();
auto renderlist = renderList();
cnodes().clear();
for (auto &i : renderlist) {
auto lotDrawable = static_cast<renderer::Drawable *>(i);
lotDrawable->sync();
cnodes().push_back(lotDrawable->mCNode.get());
}
clayer().mNodeList.ptr = cnodes().data();
clayer().mNodeList.size = cnodes().size();
}
void renderer::Layer::buildLayerNode()
{
if (!mCApiData) {
mCApiData = std::make_unique<renderer::CApiData>();
clayer().keypath = name();
}
if (complexContent()) clayer().mAlpha = uint8_t(combinedAlpha() * 255.f);
clayer().mVisible = visible();
// update matte
if (hasMatte()) {
switch (mLayerData->mMatteType) {
case model::MatteType::Alpha:
clayer().mMatte = MatteAlpha;
break;
case model::MatteType::AlphaInv:
clayer().mMatte = MatteAlphaInv;
break;
case model::MatteType::Luma:
clayer().mMatte = MatteLuma;
break;
case model::MatteType::LumaInv:
clayer().mMatte = MatteLumaInv;
break;
default:
clayer().mMatte = MatteNone;
break;
}
}
if (mLayerMask) {
cmasks().clear();
cmasks().resize(mLayerMask->mMasks.size());
size_t i = 0;
for (const auto &mask : mLayerMask->mMasks) {
auto & cNode = cmasks()[i++];
const auto &elm = mask.mFinalPath.elements();
const auto &pts = mask.mFinalPath.points();
auto ptPtr = reinterpret_cast<const float *>(pts.data());
auto elmPtr = reinterpret_cast<const char *>(elm.data());
cNode.mPath.ptPtr = ptPtr;
cNode.mPath.ptCount = 2 * pts.size();
cNode.mPath.elmPtr = elmPtr;
cNode.mPath.elmCount = elm.size();
cNode.mAlpha = uint8_t(mask.mCombinedAlpha * 255.0f);
switch (mask.maskMode()) {
case model::Mask::Mode::Add:
cNode.mMode = MaskAdd;
break;
case model::Mask::Mode::Substarct:
cNode.mMode = MaskSubstract;
break;
case model::Mask::Mode::Intersect:
cNode.mMode = MaskIntersect;
break;
case model::Mask::Mode::Difference:
cNode.mMode = MaskDifference;
break;
default:
cNode.mMode = MaskAdd;
break;
}
}
clayer().mMaskList.ptr = cmasks().data();
clayer().mMaskList.size = cmasks().size();
}
}
void renderer::SolidLayer::buildLayerNode()
{
renderer::Layer::buildLayerNode();
auto renderlist = renderList();
cnodes().clear();
for (auto &i : renderlist) {
auto lotDrawable = static_cast<renderer::Drawable *>(i);
lotDrawable->sync();
cnodes().push_back(lotDrawable->mCNode.get());
}
clayer().mNodeList.ptr = cnodes().data();
clayer().mNodeList.size = cnodes().size();
}
void renderer::ImageLayer::buildLayerNode()
{
renderer::Layer::buildLayerNode();
auto renderlist = renderList();
cnodes().clear();
for (auto &i : renderlist) {
auto lotDrawable = static_cast<renderer::Drawable *>(i);
lotDrawable->sync();
lotDrawable->mCNode->mImageInfo.data =
lotDrawable->mBrush.mTexture->mBitmap.data();
lotDrawable->mCNode->mImageInfo.width =
int(lotDrawable->mBrush.mTexture->mBitmap.width());
lotDrawable->mCNode->mImageInfo.height =
int(lotDrawable->mBrush.mTexture->mBitmap.height());
lotDrawable->mCNode->mImageInfo.mMatrix.m11 = combinedMatrix().m_11();
lotDrawable->mCNode->mImageInfo.mMatrix.m12 = combinedMatrix().m_12();
lotDrawable->mCNode->mImageInfo.mMatrix.m13 = combinedMatrix().m_13();
lotDrawable->mCNode->mImageInfo.mMatrix.m21 = combinedMatrix().m_21();
lotDrawable->mCNode->mImageInfo.mMatrix.m22 = combinedMatrix().m_22();
lotDrawable->mCNode->mImageInfo.mMatrix.m23 = combinedMatrix().m_23();
lotDrawable->mCNode->mImageInfo.mMatrix.m31 = combinedMatrix().m_tx();
lotDrawable->mCNode->mImageInfo.mMatrix.m32 = combinedMatrix().m_ty();
lotDrawable->mCNode->mImageInfo.mMatrix.m33 = combinedMatrix().m_33();
// Alpha calculation already combined.
lotDrawable->mCNode->mImageInfo.mAlpha =
uint8_t(lotDrawable->mBrush.mTexture->mAlpha);
cnodes().push_back(lotDrawable->mCNode.get());
}
clayer().mNodeList.ptr = cnodes().data();
clayer().mNodeList.size = cnodes().size();
}
static void updateGStops(LOTNode *n, const VGradient *grad)
{
if (grad->mStops.size() != n->mGradient.stopCount) {
if (n->mGradient.stopCount) free(n->mGradient.stopPtr);
n->mGradient.stopCount = grad->mStops.size();
n->mGradient.stopPtr = (LOTGradientStop *)malloc(
n->mGradient.stopCount * sizeof(LOTGradientStop));
}
LOTGradientStop *ptr = n->mGradient.stopPtr;
for (const auto &i : grad->mStops) {
ptr->pos = i.first;
ptr->a = uint8_t(i.second.alpha() * grad->alpha());
ptr->r = i.second.red();
ptr->g = i.second.green();
ptr->b = i.second.blue();
ptr++;
}
}
void renderer::Drawable::sync()
{
if (!mCNode) {
mCNode = std::make_unique<LOTNode>();
mCNode->mGradient.stopPtr = nullptr;
mCNode->mGradient.stopCount = 0;
}
mCNode->mFlag = ChangeFlagNone;
if (mFlag & DirtyState::None) return;
if (mFlag & DirtyState::Path) {
applyDashOp();
const std::vector<VPath::Element> &elm = mPath.elements();
const std::vector<VPointF> & pts = mPath.points();
const float *ptPtr = reinterpret_cast<const float *>(pts.data());
const char * elmPtr = reinterpret_cast<const char *>(elm.data());
mCNode->mPath.elmPtr = elmPtr;
mCNode->mPath.elmCount = elm.size();
mCNode->mPath.ptPtr = ptPtr;
mCNode->mPath.ptCount = 2 * pts.size();
mCNode->mFlag |= ChangeFlagPath;
mCNode->keypath = name();
}
if (mStrokeInfo) {
mCNode->mStroke.width = mStrokeInfo->width;
mCNode->mStroke.miterLimit = mStrokeInfo->miterLimit;
mCNode->mStroke.enable = 1;
switch (mStrokeInfo->cap) {
case CapStyle::Flat:
mCNode->mStroke.cap = LOTCapStyle::CapFlat;
break;
case CapStyle::Square:
mCNode->mStroke.cap = LOTCapStyle::CapSquare;
break;
case CapStyle::Round:
mCNode->mStroke.cap = LOTCapStyle::CapRound;
break;
}
switch (mStrokeInfo->join) {
case JoinStyle::Miter:
mCNode->mStroke.join = LOTJoinStyle::JoinMiter;
break;
case JoinStyle::Bevel:
mCNode->mStroke.join = LOTJoinStyle::JoinBevel;
break;
case JoinStyle::Round:
mCNode->mStroke.join = LOTJoinStyle::JoinRound;
break;
default:
mCNode->mStroke.join = LOTJoinStyle::JoinMiter;
break;
}
} else {
mCNode->mStroke.enable = 0;
}
switch (mFillRule) {
case FillRule::EvenOdd:
mCNode->mFillRule = LOTFillRule::FillEvenOdd;
break;
default:
mCNode->mFillRule = LOTFillRule::FillWinding;
break;
}
switch (mBrush.type()) {
case VBrush::Type::Solid:
mCNode->mBrushType = LOTBrushType::BrushSolid;
mCNode->mColor.r = mBrush.mColor.r;
mCNode->mColor.g = mBrush.mColor.g;
mCNode->mColor.b = mBrush.mColor.b;
mCNode->mColor.a = mBrush.mColor.a;
break;
case VBrush::Type::LinearGradient: {
mCNode->mBrushType = LOTBrushType::BrushGradient;
mCNode->mGradient.type = LOTGradientType::GradientLinear;
VPointF s = mBrush.mGradient->mMatrix.map(
{mBrush.mGradient->linear.x1, mBrush.mGradient->linear.y1});
VPointF e = mBrush.mGradient->mMatrix.map(
{mBrush.mGradient->linear.x2, mBrush.mGradient->linear.y2});
mCNode->mGradient.start.x = s.x();
mCNode->mGradient.start.y = s.y();
mCNode->mGradient.end.x = e.x();
mCNode->mGradient.end.y = e.y();
updateGStops(mCNode.get(), mBrush.mGradient);
break;
}
case VBrush::Type::RadialGradient: {
mCNode->mBrushType = LOTBrushType::BrushGradient;
mCNode->mGradient.type = LOTGradientType::GradientRadial;
VPointF c = mBrush.mGradient->mMatrix.map(
{mBrush.mGradient->radial.cx, mBrush.mGradient->radial.cy});
VPointF f = mBrush.mGradient->mMatrix.map(
{mBrush.mGradient->radial.fx, mBrush.mGradient->radial.fy});
mCNode->mGradient.center.x = c.x();
mCNode->mGradient.center.y = c.y();
mCNode->mGradient.focal.x = f.x();
mCNode->mGradient.focal.y = f.y();
float scale = mBrush.mGradient->mMatrix.scale();
mCNode->mGradient.cradius = mBrush.mGradient->radial.cradius * scale;
mCNode->mGradient.fradius = mBrush.mGradient->radial.fradius * scale;
updateGStops(mCNode.get(), mBrush.mGradient);
break;
}
default:
break;
}
}
| 11,381 | lottieitem_capi | cpp | en | cpp | code | {"qsc_code_num_words": 1111, "qsc_code_num_chars": 11381.0, "qsc_code_mean_word_length": 6.02970297, "qsc_code_frac_words_unique": 0.24482448, "qsc_code_frac_chars_top_2grams": 0.03806538, "qsc_code_frac_chars_top_3grams": 0.05239588, "qsc_code_frac_chars_top_4grams": 0.04567846, "qsc_code_frac_chars_dupe_5grams": 0.27048813, "qsc_code_frac_chars_dupe_6grams": 0.23705031, "qsc_code_frac_chars_dupe_7grams": 0.21197194, "qsc_code_frac_chars_dupe_8grams": 0.16062099, "qsc_code_frac_chars_dupe_9grams": 0.13822959, "qsc_code_frac_chars_dupe_10grams": 0.13822959, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00751073, "qsc_code_frac_chars_whitespace": 0.26298216, "qsc_code_size_file_byte": 11381.0, "qsc_code_num_lines": 339.0, "qsc_code_num_chars_line_max": 79.0, "qsc_code_num_chars_line_mean": 33.57227139, "qsc_code_frac_chars_alphabet": 0.79113019, "qsc_code_frac_chars_comments": 0.02135138, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.24915825, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00188544, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.01010101, "qsc_codecpp_frac_lines_func_ratio": 0.00673401, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.01346801, "qsc_codecpp_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/lottiemodel.cpp | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
* 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.
*/
#include "lottiemodel.h"
#include <cassert>
#include <iterator>
#include <stack>
#include "vimageloader.h"
#include "vline.h"
using namespace rlottie::internal;
/*
* We process the iterator objects in the children list
* by iterating from back to front. when we find a repeater object
* we remove the objects from satrt till repeater object and then place
* under a new shape group object which we add it as children to the repeater
* object.
* Then we visit the childrens of the newly created shape group object to
* process the remaining repeater object(when children list contains more than
* one repeater).
*
*/
class LottieRepeaterProcesser {
public:
void visitChildren(model::Group *obj)
{
for (auto i = obj->mChildren.rbegin(); i != obj->mChildren.rend();
++i) {
auto child = (*i);
if (child->type() == model::Object::Type::Repeater) {
model::Repeater *repeater =
static_cast<model::Repeater *>(child);
// check if this repeater is already processed
// can happen if the layer is an asset and referenced by
// multiple layer.
if (repeater->processed()) continue;
repeater->markProcessed();
auto content = repeater->content();
// 1. increment the reverse iterator to point to the
// object before the repeater
++i;
// 2. move all the children till repater to the group
std::move(obj->mChildren.begin(), i.base(),
back_inserter(content->mChildren));
// 3. erase the objects from the original children list
obj->mChildren.erase(obj->mChildren.begin(), i.base());
// 5. visit newly created group to process remaining repeater
// object.
visitChildren(content);
// 6. exit the loop as the current iterators are invalid
break;
}
visit(child);
}
}
void visit(model::Object *obj)
{
switch (obj->type()) {
case model::Object::Type::Group:
case model::Object::Type::Layer: {
visitChildren(static_cast<model::Group *>(obj));
break;
}
default:
break;
}
}
};
class LottieUpdateStatVisitor {
model::Composition::Stats *stat;
public:
explicit LottieUpdateStatVisitor(model::Composition::Stats *s) : stat(s) {}
void visitChildren(model::Group *obj)
{
for (const auto &child : obj->mChildren) {
if (child) visit(child);
}
}
void visitLayer(model::Layer *layer)
{
switch (layer->mLayerType) {
case model::Layer::Type::Precomp:
stat->precompLayerCount++;
break;
case model::Layer::Type::Null:
stat->nullLayerCount++;
break;
case model::Layer::Type::Shape:
stat->shapeLayerCount++;
break;
case model::Layer::Type::Solid:
stat->solidLayerCount++;
break;
case model::Layer::Type::Image:
stat->imageLayerCount++;
break;
default:
break;
}
visitChildren(layer);
}
void visit(model::Object *obj)
{
switch (obj->type()) {
case model::Object::Type::Layer: {
visitLayer(static_cast<model::Layer *>(obj));
break;
}
case model::Object::Type::Repeater: {
visitChildren(static_cast<model::Repeater *>(obj)->content());
break;
}
case model::Object::Type::Group: {
visitChildren(static_cast<model::Group *>(obj));
break;
}
default:
break;
}
}
};
void model::Composition::processRepeaterObjects()
{
LottieRepeaterProcesser visitor;
visitor.visit(mRootLayer);
}
void model::Composition::updateStats()
{
LottieUpdateStatVisitor visitor(&mStats);
visitor.visit(mRootLayer);
}
VMatrix model::Repeater::Transform::matrix(int frameNo, float multiplier) const
{
VPointF scale = mScale.value(frameNo) / 100.f;
scale.setX(std::pow(scale.x(), multiplier));
scale.setY(std::pow(scale.y(), multiplier));
VMatrix m;
m.translate(mPosition.value(frameNo) * multiplier)
.translate(mAnchor.value(frameNo))
.scale(scale)
.rotate(mRotation.value(frameNo) * multiplier)
.translate(-mAnchor.value(frameNo));
return m;
}
VMatrix model::Transform::Data::matrix(int frameNo, bool autoOrient) const
{
VMatrix m;
VPointF position;
if (mExtra && mExtra->mSeparate) {
position.setX(mExtra->mSeparateX.value(frameNo));
position.setY(mExtra->mSeparateY.value(frameNo));
} else {
position = mPosition.value(frameNo);
}
float angle = autoOrient ? mPosition.angle(frameNo) : 0;
if (mExtra && mExtra->m3DData) {
m.translate(position)
.rotate(mExtra->m3DRz.value(frameNo) + angle)
.rotate(mExtra->m3DRy.value(frameNo), VMatrix::Axis::Y)
.rotate(mExtra->m3DRx.value(frameNo), VMatrix::Axis::X)
.scale(mScale.value(frameNo) / 100.f)
.translate(-mAnchor.value(frameNo));
} else {
m.translate(position)
.rotate(mRotation.value(frameNo) + angle)
.scale(mScale.value(frameNo) / 100.f)
.translate(-mAnchor.value(frameNo));
}
return m;
}
void model::Dash::getDashInfo(int frameNo, std::vector<float> &result) const
{
result.clear();
if (mData.size() <= 1) return;
if (result.capacity() < mData.size()) result.reserve(mData.size() + 1);
for (const auto &elm : mData) result.push_back(elm.value(frameNo));
// if the size is even then we are missing last
// gap information which is same as the last dash value
// copy it from the last dash value.
// NOTE: last value is the offset and last-1 is the last dash value.
auto size = result.size();
if ((size % 2) == 0) {
// copy offset value to end.
result.push_back(result.back());
// copy dash value to gap.
result[size - 1] = result[size - 2];
}
}
/**
* Both the color stops and opacity stops are in the same array.
* There are {@link #colorPoints} colors sequentially as:
* [
* ...,
* position,
* red,
* green,
* blue,
* ...
* ]
*
* The remainder of the array is the opacity stops sequentially as:
* [
* ...,
* position,
* opacity,
* ...
* ]
*/
void model::Gradient::populate(VGradientStops &stops, int frameNo)
{
model::Gradient::Data gradData = mGradient.value(frameNo);
auto size = gradData.mGradient.size();
float * ptr = gradData.mGradient.data();
int colorPoints = mColorPoints;
if (colorPoints == -1) { // for legacy bodymovin (ref: lottie-android)
colorPoints = int(size / 4);
}
auto opacityArraySize = size - colorPoints * 4;
float *opacityPtr = ptr + (colorPoints * 4);
stops.clear();
for (int i = 0; i < colorPoints; i++) {
float colorStop = ptr[0];
model::Color color = model::Color(ptr[1], ptr[2], ptr[3]);
if (opacityArraySize) {
float opacity = getOpacityAtPosition(opacityPtr, opacityArraySize, colorStop);
stops.push_back(std::make_pair(colorStop, color.toColor(opacity)));
} else {
stops.push_back(std::make_pair(colorStop, color.toColor()));
}
ptr += 4;
}
}
float model::Gradient::getOpacityAtPosition(float *opacities, size_t opacityArraySize, float position)
{
for (size_t i = 2; i < opacityArraySize; i += 2)
{
float lastPosition = opacities[i - 2];
float thisPosition = opacities[i];
if (opacities[i] >= position) {
float progress = (position - lastPosition) / (thisPosition - lastPosition);
progress = progress < 0.0f ? 0.0f : 1.0f < progress ? 1.0f : progress; //clamp(progress, 0, 1)
return opacities[i - 1] + progress * (opacities[i + 1] - opacities[i - 1]);
}
}
return 0.0f;
}
void model::Gradient::update(std::unique_ptr<VGradient> &grad, int frameNo)
{
bool init = false;
if (!grad) {
if (mGradientType == 1)
grad = std::make_unique<VGradient>(VGradient::Type::Linear);
else
grad = std::make_unique<VGradient>(VGradient::Type::Radial);
grad->mSpread = VGradient::Spread::Pad;
init = true;
}
if (!mGradient.isStatic() || init) {
populate(grad->mStops, frameNo);
}
if (mGradientType == 1) { // linear gradient
VPointF start = mStartPoint.value(frameNo);
VPointF end = mEndPoint.value(frameNo);
grad->linear.x1 = start.x();
grad->linear.y1 = start.y();
grad->linear.x2 = end.x();
grad->linear.y2 = end.y();
} else { // radial gradient
VPointF start = mStartPoint.value(frameNo);
VPointF end = mEndPoint.value(frameNo);
grad->radial.cx = start.x();
grad->radial.cy = start.y();
grad->radial.cradius =
VLine::length(start.x(), start.y(), end.x(), end.y());
/*
* Focal point is the point lives in highlight length distance from
* center along the line (start, end) and rotated by highlight angle.
* below calculation first finds the quadrant(angle) on which the point
* lives by applying inverse slope formula then adds the rotation angle
* to find the final angle. then point is retrived using circle equation
* of center, angle and distance.
*/
float progress = mHighlightLength.value(frameNo) / 100.0f;
if (vCompare(progress, 1.0f)) progress = 0.99f;
float startAngle = VLine(start, end).angle();
float highlightAngle = mHighlightAngle.value(frameNo);
static constexpr float K_PI = 3.1415926f;
float angle = (startAngle + highlightAngle) * (K_PI / 180.0f);
grad->radial.fx =
grad->radial.cx + std::cos(angle) * progress * grad->radial.cradius;
grad->radial.fy =
grad->radial.cy + std::sin(angle) * progress * grad->radial.cradius;
// Lottie dosen't have any focal radius concept.
grad->radial.fradius = 0;
}
}
void model::Asset::loadImageData(std::string data)
{
if (!data.empty())
mBitmap = VImageLoader::instance().load(data.c_str(), data.length());
}
void model::Asset::loadImagePath(std::string path)
{
if (!path.empty()) mBitmap = VImageLoader::instance().load(path.c_str());
}
std::vector<LayerInfo> model::Composition::layerInfoList() const
{
if (!mRootLayer || mRootLayer->mChildren.empty()) return {};
std::vector<LayerInfo> result;
result.reserve(mRootLayer->mChildren.size());
for (auto it : mRootLayer->mChildren) {
auto layer = static_cast<model::Layer *>(it);
result.emplace_back(layer->name(), layer->mInFrame, layer->mOutFrame);
}
return result;
}
| 12,452 | lottiemodel | cpp | en | cpp | code | {"qsc_code_num_words": 1406, "qsc_code_num_chars": 12452.0, "qsc_code_mean_word_length": 5.30085349, "qsc_code_frac_words_unique": 0.2916074, "qsc_code_frac_chars_top_2grams": 0.03864216, "qsc_code_frac_chars_top_3grams": 0.01207567, "qsc_code_frac_chars_top_4grams": 0.01274655, "qsc_code_frac_chars_dupe_5grams": 0.16261908, "qsc_code_frac_chars_dupe_6grams": 0.11498725, "qsc_code_frac_chars_dupe_7grams": 0.10063062, "qsc_code_frac_chars_dupe_8grams": 0.07674762, "qsc_code_frac_chars_dupe_9grams": 0.07674762, "qsc_code_frac_chars_dupe_10grams": 0.05044948, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00953754, "qsc_code_frac_chars_whitespace": 0.2758593, "qsc_code_size_file_byte": 12452.0, "qsc_code_num_lines": 365.0, "qsc_code_num_chars_line_max": 107.0, "qsc_code_num_chars_line_mean": 34.11506849, "qsc_code_frac_chars_alphabet": 0.81701231, "qsc_code_frac_chars_comments": 0.26429489, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.19047619, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00371139, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.00396825, "qsc_codecpp_frac_lines_preprocessor_directives": 0.02777778, "qsc_codecpp_frac_lines_func_ratio": 0.02777778, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.07142857, "qsc_codecpp_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0} |
0015/esp_rlottie | rlottie/src/lottie/lottiekeypath.cpp | #include "lottiekeypath.h"
#include <sstream>
LOTKeyPath::LOTKeyPath(const std::string &keyPath)
{
std::stringstream ss(keyPath);
std::string item;
while (getline(ss, item, '.')) {
mKeys.push_back(item);
}
}
bool LOTKeyPath::matches(const std::string &key, uint32_t depth)
{
if (skip(key)) {
// This is an object we programatically create.
return true;
}
if (depth > size()) {
return false;
}
if ((mKeys[depth] == key) || (mKeys[depth] == "*") ||
(mKeys[depth] == "**")) {
return true;
}
return false;
}
uint32_t LOTKeyPath::nextDepth(const std::string key, uint32_t depth)
{
if (skip(key)) {
// If it's a container then we added programatically and it isn't a part
// of the keypath.
return depth;
}
if (mKeys[depth] != "**") {
// If it's not a globstar then it is part of the keypath.
return depth + 1;
}
if (depth == size()) {
// The last key is a globstar.
return depth;
}
if (mKeys[depth + 1] == key) {
// We are a globstar and the next key is our current key so consume
// both.
return depth + 2;
}
return depth;
}
bool LOTKeyPath::fullyResolvesTo(const std::string key, uint32_t depth)
{
if (depth > mKeys.size()) {
return false;
}
bool isLastDepth = (depth == size());
if (!isGlobstar(depth)) {
bool matches = (mKeys[depth] == key) || isGlob(depth);
return (isLastDepth || (depth == size() - 1 && endsWithGlobstar())) &&
matches;
}
bool isGlobstarButNextKeyMatches = !isLastDepth && mKeys[depth + 1] == key;
if (isGlobstarButNextKeyMatches) {
return depth == size() - 1 ||
(depth == size() - 2 && endsWithGlobstar());
}
if (isLastDepth) {
return true;
}
if (depth + 1 < size()) {
// We are a globstar but there is more than 1 key after the globstar we
// we can't fully match.
return false;
}
// Return whether the next key (which we now know is the last one) is the
// same as the current key.
return mKeys[depth + 1] == key;
}
| 2,216 | lottiekeypath | cpp | en | cpp | code | {"qsc_code_num_words": 263, "qsc_code_num_chars": 2216.0, "qsc_code_mean_word_length": 4.65019011, "qsc_code_frac_words_unique": 0.30798479, "qsc_code_frac_chars_top_2grams": 0.06541292, "qsc_code_frac_chars_top_3grams": 0.04578904, "qsc_code_frac_chars_top_4grams": 0.04170074, "qsc_code_frac_chars_dupe_5grams": 0.16026165, "qsc_code_frac_chars_dupe_6grams": 0.1316435, "qsc_code_frac_chars_dupe_7grams": 0.08748978, "qsc_code_frac_chars_dupe_8grams": 0.08748978, "qsc_code_frac_chars_dupe_9grams": 0.06214227, "qsc_code_frac_chars_dupe_10grams": 0.06214227, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0117724, "qsc_code_frac_chars_whitespace": 0.31001805, "qsc_code_size_file_byte": 2216.0, "qsc_code_num_lines": 86.0, "qsc_code_num_chars_line_max": 81.0, "qsc_code_num_chars_line_mean": 25.76744186, "qsc_code_frac_chars_alphabet": 0.7880968, "qsc_code_frac_chars_comments": 0.22788809, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.1875, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01227352, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.03125, "qsc_codecpp_frac_lines_func_ratio": 0.015625, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.21875, "qsc_codecpp_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0} |
007idc/GoEdgeKeyGen | main.go | package main
import (
"GoEdgeKeyGen/third/encode"
"encoding/base64"
"encoding/json"
"fmt"
)
const (
id = "nameless"
dayFrom = "1949-10-01"
dayTo = "2077-06-04"
requestCode = ""
company = "GoEdge | 分遗产群出品"
nodes = 0
updatedAt = 1700000000
edition = "ultra"
email = ""
)
func main() {
fmt.Println("GoEdge License Keygen By @GoEdge | 分遗产群")
payload := KeyGen{
Id: id,
DayFrom: dayFrom,
DayTo: dayTo,
MacAddresses: []string{},
ReqCode: requestCode,
Hostname: "*",
Company: company,
Nodes: nodes,
UpdatedAt: updatedAt,
Components: []string{"*"},
Edition: edition,
Email: email,
}
key, _ := json.Marshal(payload)
license := encode.Encode(key)
licenseStr := base64.StdEncoding.EncodeToString(license)
fmt.Println("↓已产出注册码↓")
fmt.Println(licenseStr)
fmt.Scanln()
}
type KeyGen struct{
Id string `json:"id"`
DayFrom string `json:"dayFrom"`
DayTo string `json:"dayTo"`
MacAddresses []string `json:"macAddresses"`
ReqCode string `json:"requestCode"`
Hostname string `json:"hostname"`
Company string `json:"company"`
Nodes int64 `json:"nodes"`
UpdatedAt int64 `json:"updatedAt"`
Components []string `json:"components"`
Edition string `json:"edition"`
Email string `json:"email"`
} | 1,230 | main | go | en | go | code | {"qsc_code_num_words": 142, "qsc_code_num_chars": 1230.0, "qsc_code_mean_word_length": 5.94366197, "qsc_code_frac_words_unique": 0.38732394, "qsc_code_frac_chars_top_2grams": 0.11848341, "qsc_code_frac_chars_top_3grams": 0.05450237, "qsc_code_frac_chars_top_4grams": 0.0, "qsc_code_frac_chars_dupe_5grams": 0.0, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03378378, "qsc_code_frac_chars_whitespace": 0.15772358, "qsc_code_size_file_byte": 1230.0, "qsc_code_num_lines": 59.0, "qsc_code_num_chars_line_max": 58.0, "qsc_code_num_chars_line_mean": 20.84745763, "qsc_code_frac_chars_alphabet": 0.77895753, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.19577579, "qsc_code_frac_chars_long_word_length": 0.02030869, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codego_cate_testfile": 0.0, "qsc_codego_frac_lines_func_ratio": 0.01818182, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.05454545, "qsc_codego_frac_lines_print": 0.05454545} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_codego_cate_testfile": 0, "qsc_codego_frac_lines_func_ratio": 0, "qsc_codego_cate_var_zero": 0, "qsc_codego_score_lines_no_logic": 0, "qsc_codego_frac_lines_print": 0} |
007gzs/meeting | miniprogram/utils/meetings.js | "use strict";
const check_status = (start_time, end_time, now_time) => {
/**
* 0: 不在范围内
* 0x1: 第一
* 0x2: 最后
* 0x4: 中间
*/
let ret = 0
if (start_time > now_time || now_time > end_time) {
return ret
}
ret |= 0x4
if (start_time == now_time) {
ret |= 0x1
}
if (end_time == now_time) {
ret |= 0x2
}
return ret
}
const get_str_list = (str_arr, count) => {
const num = Math.floor(str_arr.length / count) /* 每格放文字数 */
const left = str_arr.length - num * count /* 剩余文字数 */
const float_pro_count = left / count /* 剩余文字每格需要放几个(小数) */
let c = 0
let left_c = 0
let ret = []
for (let i = 1; i < count; i++) {
let now_c = num
if (float_pro_count * i - left_c >= 0.5) {
now_c++
left_c++
}
ret.push(str_arr.slice(c, c + now_c).join(""))
c += now_c
}
ret.push(str_arr.slice(c, str_arr.length).join(""))
return ret
}
const get_meeting_data = (room_id, time, meetings) => {
const time_value = time.value()
const filter_meetings = meetings.filter(m => { return m.room.toString() == room_id.toString() })
for (let i in filter_meetings) {
let meeting = filter_meetings[i]
const start_time = getApp().time.parseTime(meeting.start_time).value()
const end_time = getApp().time.parseTime(meeting.end_time).value()
let status = check_status(start_time, end_time - 30 * 60, time_value)
if (status != 0) {
let count = Math.round((end_time - start_time) / 30 / 60)
let str_list = get_str_list(meeting.name.split(""), count)
//let str_list = meeting.name_list
let pos = Math.round((time_value - start_time) / 30 / 60)
return { status: status, text: str_list[pos], id: meeting.id }
}
}
return { status: 0, text: '', id: null }
}
const getTdData = (rooms, meetings, time_range, select, select_date) => {
let td_data = {}
let now = getApp().nowDate()
let now_time = getApp().time.Time(now.getHours(), now.getMinutes(), now.getSeconds()).value()
for (let i in rooms) {
let room = rooms[i]
td_data[room.id] = {}
for (let j in time_range) {
let time = time_range[j]
let selected_status = 0
if (select.selected && select.room.id == room.id) {
selected_status = check_status(
getApp().time.parseTime(select.start).value(),
getApp().time.parseTime(select.end).value(),
time.data.value()
)
}
let meeting_data = get_meeting_data(room.id, time.data, meetings)
let local_select_date = new Date(select_date)
let today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).valueOf()
local_select_date = new Date(local_select_date.getFullYear(), local_select_date.getMonth(), local_select_date.getDate()).valueOf()
let expire = false
if (local_select_date < today) {
expire = true
} else if (local_select_date == today) {
if (now_time > time.data.value()) {
expire = true
}
}
let clazz = []
if (expire) {
clazz.push("expire")
}
const border_style = function (_clazz, _status) {
if (_status & 0x1) {
_clazz.push("top")
}
if (_status & 0x2) {
_clazz.push("bottom")
}
}
if (meeting_data.status == 0 && selected_status == 0) {
border_style(clazz, 0x1 | 0x2 | 0x4)
}
if (meeting_data.status != 0) {
clazz.push("in_use")
border_style(clazz, meeting_data.status)
if (selected_status != 0) {
select.selected = false
select.click = false
select.start = ""
select.end = ""
select.room = {}
return getTdData(rooms, meetings, time_range, select, select_date)
}
}
if (selected_status != 0) {
clazz.push("selected")
border_style(clazz, selected_status)
}
td_data[room.id][time.id] = {
clazz: clazz.join(" "),
expire: expire,
meeting_id: meeting_data.id,
meeting_status: meeting_data.status,
text: meeting_data.text,
selected_status: selected_status
}
}
}
return td_data
}
module.exports = {
getTdData: getTdData
} | 4,208 | meetings | js | en | javascript | code | {"qsc_code_num_words": 548, "qsc_code_num_chars": 4208.0, "qsc_code_mean_word_length": 4.31751825, "qsc_code_frac_words_unique": 0.1770073, "qsc_code_frac_chars_top_2grams": 0.04226543, "qsc_code_frac_chars_top_3grams": 0.0443787, "qsc_code_frac_chars_top_4grams": 0.01775148, "qsc_code_frac_chars_dupe_5grams": 0.19442096, "qsc_code_frac_chars_dupe_6grams": 0.09974641, "qsc_code_frac_chars_dupe_7grams": 0.05663567, "qsc_code_frac_chars_dupe_8grams": 0.0397295, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01600261, "qsc_code_frac_chars_whitespace": 0.2723384, "qsc_code_size_file_byte": 4208.0, "qsc_code_num_lines": 136.0, "qsc_code_num_chars_line_max": 137.0, "qsc_code_num_chars_line_mean": 30.94117647, "qsc_code_frac_chars_alphabet": 0.75669497, "qsc_code_frac_chars_comments": 0.0335076, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.05555556, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00983284, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00589971, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.00793651, "qsc_codejavascript_num_statement_line": 0.04761905, "qsc_codejavascript_score_lines_no_logic": 0.11904762, "qsc_codejavascript_frac_words_legal_var_name": 0.55555556, "qsc_codejavascript_frac_words_legal_func_name": 0.0, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0} |
007gzs/meeting | miniprogram/utils/set-cookie.js | "use strict";
var defaultParseOptions = {
decodeValues: true
};
function extend(target, source) {
return Object.keys(source).reduce(function (target, key) {
target[key] = source[key];
return target;
}, target);
}
function isNonEmptyString(str) {
return typeof str === "string" && !!str.trim();
}
function parseString(setCookieValue, options) {
var parts = setCookieValue.split(";").filter(isNonEmptyString);
var nameValue = parts.shift().split("=");
var name = nameValue.shift();
var value = nameValue.join("="); // everything after the first =, joined by a "=" if there was more than one part
var cookie = {
name: name, // grab everything before the first =
value: options.decodeValues ? decodeURIComponent(value) : value // decode cookie value
};
parts.forEach(function (part) {
var sides = part.split("=");
var key = sides
.shift()
.trimLeft()
.toLowerCase();
var value = sides.join("=");
if (key === "expires") {
cookie.expires = new Date(value);
} else if (key === "max-age") {
cookie.maxAge = parseInt(value, 10);
} else if (key === "secure") {
cookie.secure = true;
} else if (key === "httponly") {
cookie.httpOnly = true;
} else if (key === "samesite") {
cookie.sameSite = value;
} else {
cookie[key] = value;
}
});
return cookie;
}
function parse(input, options) {
if (!input) {
return [];
}
if (input.headers) {
input = input.headers["set-cookie"];
}
if (!Array.isArray(input)) {
input = [input];
}
var defaultOptions = extend({}, defaultParseOptions);
if (options) {
options = extend(defaultOptions, options);
} else {
options = defaultOptions;
}
return input.filter(isNonEmptyString).map(function (str) {
return parseString(str, options);
});
}
/*
Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
that are within a single set-cookie field-value, such as in the Expires portion.
This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
React Native's fetch does this for *every* header, including set-cookie.
Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
*/
function splitCookiesString(cookiesString) {
if (Array.isArray(cookiesString)) {
return cookiesString;
}
if (typeof cookiesString !== "string") {
return [];
}
var cookiesStrings = [];
var pos = 0;
var start;
var ch;
var lastComma;
var nextStart;
var cookiesSeparatorFound;
function skipWhitespace() {
while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
pos += 1;
}
return pos < cookiesString.length;
}
function notSpecialChar() {
ch = cookiesString.charAt(pos);
return ch !== "=" && ch !== ";" && ch !== ",";
}
while (pos < cookiesString.length) {
start = pos;
cookiesSeparatorFound = false;
while (skipWhitespace()) {
ch = cookiesString.charAt(pos);
if (ch === ",") {
// ',' is a cookie separator if we have later first '=', not ';' or ','
lastComma = pos;
pos += 1;
skipWhitespace();
nextStart = pos;
while (pos < cookiesString.length && notSpecialChar()) {
pos += 1;
}
// currently special character
if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
// we found cookies separator
cookiesSeparatorFound = true;
// pos is inside the next cookie, so back up and return it.
pos = nextStart;
cookiesStrings.push(cookiesString.substring(start, lastComma));
start = pos;
} else {
// in param ',' or param separator ';',
// we continue from that comma
pos = lastComma + 1;
}
} else {
pos += 1;
}
}
if (!cookiesSeparatorFound || pos >= cookiesString.length) {
cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
}
}
return cookiesStrings;
}
module.exports = parse;
module.exports.parse = parse;
module.exports.splitCookiesString = splitCookiesString; | 4,551 | set-cookie | js | en | javascript | code | {"qsc_code_num_words": 484, "qsc_code_num_chars": 4551.0, "qsc_code_mean_word_length": 5.91322314, "qsc_code_frac_words_unique": 0.38016529, "qsc_code_frac_chars_top_2grams": 0.046471, "qsc_code_frac_chars_top_3grams": 0.04612159, "qsc_code_frac_chars_top_4grams": 0.02830189, "qsc_code_frac_chars_dupe_5grams": 0.04682041, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01925841, "qsc_code_frac_chars_whitespace": 0.23555263, "qsc_code_size_file_byte": 4551.0, "qsc_code_num_lines": 160.0, "qsc_code_num_chars_line_max": 167.0, "qsc_code_num_chars_line_mean": 28.44375, "qsc_code_frac_chars_alphabet": 0.80339178, "qsc_code_frac_chars_comments": 0.25291145, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.14634146, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.02293443, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.05691057, "qsc_codejavascript_num_statement_line": 0.08130081, "qsc_codejavascript_score_lines_no_logic": 0.15447154, "qsc_codejavascript_frac_words_legal_var_name": 1.0, "qsc_codejavascript_frac_words_legal_func_name": 1.0, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0} |
007gzs/meeting | miniprogram/utils/http-cookie.js | "use strict";
const setCookieTool = require('./set-cookie.js');
/**
* 设置cookie 参数为字符串,
* 例如cookieA=a; expires=Tue, 14-Aug-2018 10:00:45 GMT; path=/; HttpOnly,cookieB=b; expires=Wed, 15-Aug-2018 08:00:45 GMT; path=/
*/
const setCookie = (str) => {
// 处理参数
var splitCookieHeaders = setCookieTool.splitCookiesString(str);
var cookies = setCookieTool.parse(splitCookieHeaders);
// 获取本地的cookie
var localCookie = queryCookie();
// 循环处理 数组
cookies.forEach((c) => {
localCookie[c.name] = c;
});
// 过滤
localCookie = checkExpires(localCookie);
// 持久化cookies
saveCookie(localCookie);
}
/**
* 设置cookie 参数为wx.request的返回头
*/
const setCookieByHead = (head) => {
if (head && head['Set-Cookie']) {
setCookie(head['Set-Cookie']);
}
}
/**
* 获取cookie
* 如果 传递了参数key,返回key对应的值
* 如果 没有传递参数,返回所有cookie的kv对象
*/
const getCookie = (key) => {
// 获取本地的cookie
var localCookie = queryCookie();
// 过滤
localCookie = checkExpires(localCookie);
// 持久化cookies
saveCookie(localCookie);
// 返回
if (key) {
return localCookie[key];
} else {
return localCookie;
}
}
/**
* 获取请求用的cookie字符串
*/
const getCookieForReq = () => {
// 获取本地的cookie
var localCookie = queryCookie();
// 过滤
localCookie = checkExpires(localCookie);
// 持久化cookies
saveCookie(localCookie);
// 返回
var rs = '';
for (var i in localCookie) {
var c = localCookie[i];
rs += (c.name + "=" + c.value + "; ");
}
// 处理末端
if (rs.substr(rs.length - 2, 2) == '; ') {
rs = rs.substr(0, rs.length - 2);
}
return rs;
}
/**
* 检查cookie是否过期(内部)
* 返回过滤后的cookies
*/
const checkExpires = (cookies) => {
if (!cookies) {
cookies = queryCookie();
}
var app = getApp();
var now = app === undefined ? new Date() : app.nowDate();
var newCookies = {};
for (var i in cookies) {
var exp = new Date(cookies[i].expires);
if (exp > now) {
newCookies[i] = (cookies[i]);
}
}
return newCookies;
}
/**
* cookie持久化,会用cookies覆盖所有数据
*/
const saveCookie = (cookies) => {
wx.setStorageSync('cti_cookie', cookies);
}
/**
* 从持久化数据中返回cookie
*/
const queryCookie = () => {
return wx.getStorageSync('cti_cookie');
}
module.exports = {
getCookieForReq: getCookieForReq,
setCookieByHead: setCookieByHead
}
| 2,268 | http-cookie | js | en | javascript | code | {"qsc_code_num_words": 230, "qsc_code_num_chars": 2268.0, "qsc_code_mean_word_length": 6.1, "qsc_code_frac_words_unique": 0.42173913, "qsc_code_frac_chars_top_2grams": 0.01924448, "qsc_code_frac_chars_top_3grams": 0.05345688, "qsc_code_frac_chars_top_4grams": 0.0769779, "qsc_code_frac_chars_dupe_5grams": 0.19743407, "qsc_code_frac_chars_dupe_6grams": 0.19743407, "qsc_code_frac_chars_dupe_7grams": 0.19743407, "qsc_code_frac_chars_dupe_8grams": 0.14967926, "qsc_code_frac_chars_dupe_9grams": 0.14967926, "qsc_code_frac_chars_dupe_10grams": 0.14967926, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01568627, "qsc_code_frac_chars_whitespace": 0.21296296, "qsc_code_size_file_byte": 2268.0, "qsc_code_num_lines": 124.0, "qsc_code_num_chars_line_max": 129.0, "qsc_code_num_chars_line_mean": 18.29032258, "qsc_code_frac_chars_alphabet": 0.77030812, "qsc_code_frac_chars_comments": 0.23280423, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.13636364, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.04022989, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.0, "qsc_codejavascript_num_statement_line": 0.15151515, "qsc_codejavascript_score_lines_no_logic": 0.09090909, "qsc_codejavascript_frac_words_legal_var_name": 1.0, "qsc_codejavascript_frac_words_legal_func_name": null, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0} |
007revad/ContainerManager_for_all_armv8 | my-other-scripts.md | ## All my scripts, tools and guides
<img src="https://hitscounter.dev/api/hit?url=https%3A%2F%2F007revad.github.io%2F&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=UTC">
#### Contents
- [Plex](#plex)
- [Synology docker](#synology-docker)
- [Synology recovery](#synology-recovery)
- [Other Synology scripts](#other-synology-scripts)
- [Synology hardware restrictions](#synology-hardware-restrictions)
- [2025 plus models](#2025-plus-models)
- [How To Guides](#how-to-guides)
- [Synology dev](#synology-dev)
***
### Plex
- **<a href="https://github.com/007revad/Synology_Plex_Backup">Synology_Plex_Backup</a>**
- A script to backup Plex to a tgz file foror DSM 7 and DSM 6.
- Works for Plex Synology package and Plex in docker.
- **<a href="https://github.com/007revad/Asustor_Plex_Backup">Asustor_Plex_Backup</a>**
- Backup your Asustor's Plex Media Server settings and database.
- **<a href="https://github.com/007revad/Linux_Plex_Backup">Linux_Plex_Backup</a>**
- Backup your Linux Plex Media Server's settings and database.
- **<a href="https://github.com/007revad/Plex_Server_Sync">Plex_Server_Sync</a>**
- Sync your main Plex server database & metadata to a backup Plex server.
- Works for Synology, Asustor, Linux and supports Plex package or Plex in docker.
[Back to Contents](#contents)
### Synology docker
- **<a href="https://github.com/007revad/Synology_Docker_Export">Synology_Docker_export</a>**
- Export all Synology Container Manager or Docker containers' settings as json files to your docker shared folder.
- **<a href="https://github.com/007revad/Synology_ContainerManager_IPv6">Synology_ContainerManager_IPv6</a>**
- Enable IPv6 for Container Manager's bridge network.
- **<a href="https://github.com/007revad/ContainerManager_for_all_armv8">ContainerManager_for_all_armv8</a>**
- Script to install Container Manager on a RS819, DS119j, DS418, DS418j, DS218, DS218play or DS118.
- **<a href="https://github.com/007revad/Docker_Autocompose">Docker_Autocompose</a>**
- Create .yml files from your docker existing containers.
- **<a href="https://github.com/007revad/Synology_docker_cleanup">Synology_docker_cleanup</a>**
- Remove orphan docker btrfs subvolumes and images in Synology DSM 7 and DSM 6.
[Back to Contents](#contents)
### Synology recovery
- **<a href="https://github.com/007revad/Synology_DSM_reinstall">Synology_DSM_reinstall</a>**
- Easily re-install the same DSM version without losing any data or settings.
- **<a href="https://github.com/007revad/Synology_Recover_Data">Synology_Recover_Data</a>**
- A script to make it easy to recover your data from your Synology's drives using a computer.
- **<a href="https://github.com/007revad/Synology_clear_drive_error">Synology clear drive error</a>**
- Clear drive critical errors so DSM will let you use the drive.
- **<a href="https://github.com/007revad/Synology_DSM_Telnet_Password">Synology_DSM_Telnet_Password</a>**
- Synology DSM Recovery Telnet Password of the Day generator.
- **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>**
- Windows GUI for extracting Synology DSM 7 pat files and spk package files.
- **<a href="https://github.com/007revad/Synoboot_backup">Synoboot_backup</a>**
- Back up synoboot after each DSM update so you can recover from a corrupt USBDOM.
[Back to Contents](#contents)
### Other Synology scripts
- **<a href="https://github.com/007revad/Synology_app_mover">Synology_app_mover</a>**
- Easily move Synology packages from one volume to another volume.
- **<a href="https://github.com/007revad/Video_Station_for_DSM_722">Video_Station_for_DSM_722</a>**
- Script to install Video Station in DSM 7.2.2
- **<a href="https://github.com/007revad/SS_Motion_Detection">SS_Motion_Detection</a>**
- Installs previous Surveillance Station and Advanced Media Extensions versions so motion detection and HEVC are supported.
- **<a href="https://github.com/007revad/Synology_Config_Backup">Synology_Config_Backup</a>**
- Backup and export your Synology DSM configuration.
- **<a href="https://github.com/007revad/Synology_CPU_temperature">Synology_CPU_temperature</a>**
- Get and log Synology NAS CPU temperature via SSH.
- **<a href="https://github.com/007revad/Synology_SMART_info">Synology_SMART_info</a>**
- Show Synology smart test progress or smart health and attributes.
- **<a href="https://github.com/007revad/Synology_Cleanup_Coredumps">Synology_Cleanup_Coredumps</a>**
- Cleanup memory core dumps from crashed processes.
- **<a href="https://github.com/007revad/Synology_toggle_reset_button">Synology_toggle_reset_button</a>**
- Script to disable or enable the reset button and show current setting.
- **<a href="https://github.com/007revad/Synology_Download_Station_Chrome_Extension">Synology_Download_Station_Chrome_Extension</a>**
- Download Station Chrome Extension.
- **<a href="https://github.com/007revad/Seagate_lowCurrentSpinup">Seagate_lowCurrentSpinup</a>**
- This script avoids the need to buy and install a higher wattage power supply when using multiple large Seagate SATA HDDs.
[Back to Contents](#contents)
### Synology hardware restrictions
- **<a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a>**
- Add your SATA or SAS HDDs and SSDs plus SATA and NVMe M.2 drives to your Synology's compatible drive databases, including your Synology M.2 PCIe card and Expansion Unit databases.
- **<a href="https://github.com/007revad/Synology_enable_M2_volume">Synology_enable_M2_volume</a>**
- Enable creating volumes with non-Synology M.2 drives.
- Enable Health Info for non-Synology NVMe drives (not in DSM 7.2.1 or later).
- **<a href="https://github.com/007revad/Synology_M2_volume">Synology_M2_volume</a>**
- Easily create an M.2 volume on Synology NAS.
- **<a href="https://github.com/007revad/Synology_enable_M2_card">Synology_enable_M2_card</a>**
- Enable Synology M.2 PCIe cards in Synology NAS that don't officially support them.
- **<a href="https://github.com/007revad/Synology_enable_eunit">Synology_enable_eunit</a>**
- Enable an unsupported Synology eSATA Expansion Unit models.
- **<a href="https://github.com/007revad/Synology_enable_Deduplication">Synology_enable_Deduplication</a>**
- Enable deduplication with non-Synology SSDs and unsupported NAS models.
- **<a href="https://github.com/007revad/Synology_SHR_switch">Synology_SHR_switch</a>**
- Easily switch between SHR and RAID Groups, or enable RAID F1.
- **<a href="https://github.com/007revad/Synology_enable_sequential_IO">Synology_enable_sequential_IO</a>**
- Enables sequential I/O for your SSD caches, like DSM 6 had.
- **<a href="https://github.com/007revad/Synology_Information_Wiki">Synology_Information_Wiki</a>**
- Information about Synology hardware.
[Back to Contents](#contents)
### 2025 plus models
- **<a href="https://github.com/007revad/Transcode_for_x25">Transcode_for_x25</a>**
- Installs the modules needed for Plex or Jellyfin hardware transcoding in DS425+ and DS225+.
- **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md">2025 series or later Plus models</a>**
- Unverified 3rd party drive limitations and unofficial solutions.
- **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#setting-up-a-new-2025-or-later-plus-model-with-only-unverified-hdds">Setup with only 3rd party drives</a>**
- Setting up a new 2025 or later plus model with only unverified HDDs.
- **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#deleting-and-recreating-your-storage-pool-on-unverified-hdds">Recreating storage pool on migrated drives</a>**
- Deleting and recreating your storage pool on unverified HDDs.
[Back to Contents](#contents)
### How To Guides
- **<a href="https://github.com/007revad/Synology_SSH_key_setup">Synology_SSH_key_setup</a>**
- How to setup SSH key authentication for your Synology.
[Back to Contents](#contents)
### Synology dev
- **<a href="https://github.com/007revad/Download_Synology_Archive">Download_Synology_Archive</a>**
- Download all or part of the Synology archive.
- **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>**
- Windows GUI for extracting Synology DSM 7 pat files and spk package files.
- **<a href="https://github.com/007revad/ScriptNotify">ScriptNotify</a>**
- DSM 7 package to allow your scripts to send DSM notifications.
- **<a href="https://github.com/007revad/DTC_GUI_for_Windows">DTC_GUI_for_Windows</a>**
- GUI for DTC.exe for Windows.
[Back to Contents](#contents)
| 9,099 | my-other-scripts | md | en | markdown | text | {"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.16632653, "qsc_doc_num_sentences": 107.0, "qsc_doc_num_words": 1341, "qsc_doc_num_chars": 9099.0, "qsc_doc_num_lines": 180.0, "qsc_doc_mean_word_length": 4.94630872, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.23191648, "qsc_doc_entropy_unigram": 4.76529845, "qsc_doc_frac_words_all_caps": 0.02908163, "qsc_doc_frac_lines_dupe_lines": 0.1025641, "qsc_doc_frac_chars_dupe_lines": 0.10911978, "qsc_doc_frac_chars_top_2grams": 0.05789236, "qsc_doc_frac_chars_top_3grams": 0.06482738, "qsc_doc_frac_chars_top_4grams": 0.10372381, "qsc_doc_frac_chars_dupe_5grams": 0.39981909, "qsc_doc_frac_chars_dupe_6grams": 0.36891301, "qsc_doc_frac_chars_dupe_7grams": 0.34041912, "qsc_doc_frac_chars_dupe_8grams": 0.25569124, "qsc_doc_frac_chars_dupe_9grams": 0.20624152, "qsc_doc_frac_chars_dupe_10grams": 0.15829941, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 30.70731707, "qsc_doc_frac_chars_hyperlink_html_tag": 0.34762062, "qsc_doc_frac_chars_alphabet": 0.79007303, "qsc_doc_frac_chars_digital": 0.03094442, "qsc_doc_frac_chars_whitespace": 0.11210023, "qsc_doc_frac_chars_hex_words": 0.0} | 1 | {"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0} |
007revad/ContainerManager_for_all_armv8 | install_container_manager.sh | #!/usr/bin/env bash
# shellcheck disable=SC2076
#---------------------------------------------------------------------------------------
# Install Container Manager on RS819, DS119j, DS418, DS418j, DS218, DS218play and DS118
#
# Github: https://github.com/007revad/ContainerManager_for_all_armv8
# Script verified at https://www.shellcheck.net/
#
# To run in a shell (replace /volume1/scripts/ with path to script):
# sudo -s /volume1/scripts/install_container_manager.sh
#---------------------------------------------------------------------------------------
scriptver="v2.0.10"
script=ContainerManager_for_all_armv8
#repo="007revad/ContainerManager_for_all_armv8"
#scriptname=install_container_manager
# Shell Colors
#Black='\e[0;30m' # ${Black}
#Red='\e[0;31m' # ${Red}
#Green='\e[0;32m' # ${Green}
#Yellow='\e[0;33m' # ${Yellow}
#Blue='\e[0;34m' # ${Blue}
#Purple='\e[0;35m' # ${Purple}
Cyan='\e[0;36m' # ${Cyan}
#White='\e[0;37m' # ${White}
Error='\e[41m' # ${Error}
#Warn='\e[47;31m' # ${Warn}
Off='\e[0m' # ${Off}
ding(){
[ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}"
printf \\a
}
if [[ $1 == "--trace" ]] || [[ $1 == "-t" ]]; then
trace="yes"
fi
# Check script is running as root
if [[ $( whoami ) != "root" ]]; then
ding
echo -e "${Error}ERROR${Off} This script must be run as sudo or root!"
exit 1 # Not running as root
fi
# Check script is running on a Synology NAS
if ! /usr/bin/uname -a | grep -i synology >/dev/null; then
echo "This script is NOT running on a Synology NAS!"
echo "Copy the script to a folder on the Synology"
echo "and run it from there."
exit 1 # Not a Synology NAS
fi
# Get NAS model
model=$(cat /proc/sys/kernel/syno_hw_version)
#modelname="$model"
# Show script version
#echo -e "$script $scriptver\ngithub.com/$repo\n"
echo "$script $scriptver"
# Get DSM full version
productversion=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION productversion)
buildphase=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION buildphase)
buildnumber=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION buildnumber)
smallfixnumber=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION smallfixnumber)
majorversion=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION majorversion)
minorversion=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION minorversion)
# Show DSM full version and model
if [[ $buildphase == GM ]]; then buildphase=""; fi
if [[ $smallfixnumber -gt "0" ]]; then smallfix="-$smallfixnumber"; fi
echo -e "$model DSM $productversion-$buildnumber$smallfix $buildphase"
# Check DSM version
if [[ ! $majorversion -ge "7" ]] && [[ ! $minorversion -ge "2" ]]; then
echo -e "This script requires DSM 7.2 or later.\n"
exit 1 # Not DSM 7.2 or later
fi
# Get CPU arch
arch="$(uname -m)"; echo "CPU is $arch"
# Get value of unique
current_unique="$(synogetkeyvalue /etc.defaults/synoinfo.conf unique)"
echo -e "$current_unique\n"
# Check if arch is armv8
if [[ $arch == "armv71" ]]; then
echo -e "Container Manager is not available for 32-bit CPUs.\n"
exit 1 # 32-bit CPU
elif [[ $arch == "x86_64" ]]; then
echo -e "This script is only for ARMv8 CPUs.\n"
exit 1 # x86_64
fi
# List of models that need this script
exclude_list=("synology_rtd1296_ds118" "synology_rtd1296_ds218")
exclude_list+=("synology_rtd1296_ds218play" "synology_rtd1296_ds418")
exclude_list+=("synology_rtd1296_ds418j" "synology_armada37xx_ds119j")
exclude_list+=("synology_rtd1296_rs819")
# Check if this model needs this script
if [[ ! ${exclude_list[*]} =~ "$current_unique" ]]; then
echo -e "You don't need this script for your $model\n"
exit # Model has Container Manager available
fi
restore_unique(){
# Restore unique to original model
if [[ -n $current_unique ]]; then
echo "Restoring synoinfo.conf"
synosetkeyvalue /etc/synoinfo.conf unique "$current_unique"
synosetkeyvalue /etc.defaults/synoinfo.conf unique "$current_unique"
fi
}
progbar(){
# $1 is pid of process
# $2 is string to echo
string="$2"
local dots
local progress
dots=""
while [[ -d /proc/$1 ]]; do
dots="${dots}."
progress="$dots"
if [[ ${#dots} -gt "10" ]]; then
dots=""
progress=" "
fi
echo -ne " ${2}$progress\r"; sleep 0.3
done
}
progstatus(){
# $1 is return status of process
# $2 is string to echo
# $3 line number function was called from
local tracestring
local pad
tracestring="${FUNCNAME[0]} called from ${FUNCNAME[1]} $3"
pad=$(printf -- ' %.0s' {1..80})
[ "$trace" == "yes" ] && printf '%.*s' 80 "${tracestring}${pad}" && echo ""
if [[ $1 == "0" ]]; then
echo -e "$2 "
elif grep "Failed to query package list from server" /tmp/installcm.txt >/dev/null; then
ding
echo -e "${Error}ERROR${Off} Failed to query package list from server!"
install_from_server_failed="yes"
else
ding
echo -e "Line ${LINENO}: ${Error}ERROR${Off} $2 failed!"
echo "$tracestring"
[ -f /tmp/installcm.txt ] && xargs echo < /tmp/installcm.txt && echo ""
if [[ $exitonerror != "no" ]]; then
restore_unique
exit 1 # Skip exit if exitonerror != no
fi
fi
exitonerror=""
#echo "return: $1" # debug
}
# shellcheck disable=SC2143
package_status(){
# $1 is package name
[ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}"
local code
/usr/syno/bin/synopkg status "${1}" >/dev/null
code="$?"
# DSM 7.2 0 = started, 17 = stopped, 255 = not_installed, 150 = broken
# DSM 6 to 7.1 0 = started, 3 = stopped, 4 = not_installed, 150 = broken
if [[ $code == "0" ]]; then
#echo -e "$1 is started\n" >&2 # debug
return 0
elif [[ $code == "17" ]] || [[ $code == "3" ]]; then
#echo -e "$1 is stopped\n" >&2 # debug
return 1
elif [[ $code == "255" ]] || [[ $code == "4" ]]; then
echo -e "$1 is not installed\n" >&2 # debug
return 255
elif [[ $code == "150" ]]; then
echo -e "$1 is broken\n" >&2 # debug
return 150
else
#echo "$code" >&2 # debug
return "$code"
fi
}
wait_status(){
# Wait for package to finish stopping or starting
# $1 is package
# $2 is start or stop
[ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}"
local num
if [[ $2 == "start" ]]; then
state="0"
elif [[ $2 == "stop" ]]; then
state="1"
fi
if [[ $state == "0" ]] || [[ $state == "1" ]]; then
num="0"
package_status "$1"
code="$?"
if [[ $code == "255" ]] || [[ $code == "150" ]]; then
restore_unique
exit "$code"
fi
while [[ $code != "$state" ]]; do
sleep 1
num=$((num +1))
if [[ $num -gt "20" ]]; then
break
fi
package_status "$1"
done
fi
}
package_stop(){
# $1 is package name
# $2 is package display name
[ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}"
timeout 5m /usr/syno/bin/synopkg stop "$1" >/dev/null &
pid=$!
string="Stopping ${Cyan}${2}${Off}"
progbar "$pid" "$string"
wait "$pid"
progstatus "$?" "$string" "line ${LINENO}"
# Allow package processes to finish stopping
wait_status "$1" stop
#sleep 1
}
package_start(){
# $1 is package name
# $2 is package display name
[ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}"
timeout 5m /usr/syno/bin/synopkg start "$1" >/dev/null &
pid=$!
string="Starting ${Cyan}${2}${Off}"
progbar "$pid" "$string"
wait "$pid"
progstatus "$?" "$string" "line ${LINENO}"
# Allow package processes to finish starting
wait_status "$1" start
}
# shellcheck disable=SC2317 # Don't warn about unreachable commands in this function
package_uninstall(){
# $1 is package name
# $2 is package display name
[ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}"
#/usr/syno/bin/synopkg uninstall "$1" >/dev/null &
/usr/syno/bin/synopkg uninstall "$1" >/tmp/installcm.txt &
pid=$!
string="Uninstalling ${Cyan}${2}${Off}"
progbar "$pid" "$string"
wait "$pid"
progstatus "$?" "$string" "line ${LINENO}"
}
# shellcheck disable=SC2317 # Don't warn about unreachable commands in this function
package_install(){
# $1 is package name
# $2 is /volume2 etc
# $3 is package display name
[ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}"
#/usr/syno/bin/synopkg install_from_server "$1" "$2" >/dev/null &
/usr/syno/bin/synopkg install_from_server "$1" "$2" >/tmp/installcm.txt &
pid=$!
string="Installing ${Cyan}${3}${Off} on ${Cyan}$2${Off}"
progbar "$pid" "$string"
wait "$pid"
progstatus "$?" "$string" "line ${LINENO}"
}
do_manual_install(){
echo -e "\nDo ${Error}NOT${Off} exit the script or close this window.\n"
echo -e "Please do a manual install:\n"
echo -e " 1. Download the latest ContainerManager-${Cyan}armv8${Off} spk file from:"
echo " https://archive.synology.com/download/Package/ContainerManager"
echo -e " 2. Open Package Center."
echo -e " 3. Click on the Manual Install button."
echo -e " 4. Click on the Browse button."
echo -e " 5. Browse to where you saved the ContainerManager spk file."
echo -e " 6. Select the spk file and click Open."
echo -e " 7. Click Next and install Container Manager."
echo -e " 8. Close Package Center."
echo -e " 9. Return to this window so the script can restore the correct model number."
echo -e " 10. Type ${Cyan}yes${Off} after you have manually installed Container Manager."
read -r answer
if [[ ${answer,,} != "yes" ]]; then
restore_unique
exit
fi
manual_install="yes"
echo ""
}
# Check if Container Manager already installed
package_status ContainerManager >/dev/null
code="$?"
#if [[ $(package_status ContainerManager) != "255" ]]; then
if [[ $code != "255" ]]; then
# Container Manager is installed
target=$(readlink "/var/packages/ContainerManager/target")
targetvol="/$(printf %s "${target:?}" | cut -d'/' -f2 )"
#targetvol="$(printf %s "${target:?}" | cut -d'/' -f2 )"
# Check if newer version available
archive_url="https://archive.synology.com/download/Package/ContainerManager"
latest_version="$(curl --silent "$archive_url" |\
grep 'href="/download/Package/ContainerManager' |\
cut -d">" -f2 | cut -d"<" -f1 | head -n 1)"
installed_version="$(synogetkeyvalue /var/packages/ContainerManager/INFO version)"
new_build="$(echo "$latest_version" | cut -d"-" -f2)"
old_build="$(echo "$installed_version" | cut -d"-" -f2)"
if [[ $new_build -gt "$old_build" ]]; then
echo "New Container Manager version available:"
echo " Latest version is: $latest_version"
echo " Installed version: $installed_version"
echo -e "Do you want to update to $latest_version [y/n]"
read -r reply
if [[ ${reply,,} == "y" ]]; then
upgrade="yes"
else
# User did not answer yes
exit 1 # User answered no to upgrading Container Manager
fi
echo ""
else
echo "Container Manager already installed on $targetvol"
echo -e "No new version available\n"
exit 1 # Container Manager already installed
fi
fi
# Backup synoinfo.conf if needed
synoinfo="/etc.defaults/synoinfo.conf"
if [[ ! -f ${synoinfo}.bak ]]; then
if cp "$synoinfo" "$synoinfo.bak"; then
echo -e "Backed up synoinfo.conf\n"
chmod 755 "$synoinfo.bak"
else
ding
echo -e "\n${Error}ERROR 5${Off} Failed to backup synoinfo.conf!"
exit 1 # Backup failed
fi
fi
# Select volume if there's more than 1
if [[ -z $target ]]; then
if [[ $upgrade != "yes" ]]; then
# Get list of available volumes
volumes=( )
for v in /volume*; do
# Ignore /volumeUSB# and /volume0
if [[ $v =~ /volume[1-9][0-9]?$ ]]; then
# Ignore unmounted volumes
if df -h | grep "$v" >/dev/null ; then
volumes+=("$v")
fi
fi
done
# Select volume to install Container Manager on
if [[ ${#volumes[@]} -gt 1 ]]; then
PS3="Select the volume to install Container Manager on: "
select targetvol in "${volumes[@]}"; do
if [[ $targetvol ]]; then
if [[ -d $targetvol ]]; then
echo -e "You selected ${Cyan}${targetvol}${Off}\n"
break
else
ding
echo -e "${Error}ERROR${Off} $targetvol not found!"
exit 1 # Target volume not found
fi
else
echo "Invalid choice!"
fi
done
elif [[ ${#volumes[@]} -eq 1 ]]; then
targetvol="${volumes[0]}"
fi
else
link="$(readlink /var/packages/ContainerManager/target | cut -d"/" -f2)"
if [[ $link ]]; then
targetvol="/$link"
fi
fi
fi
#exit # debug
#targetvol=/volume1 # debug
# Change unique to a supported model
echo -e "Editing synoinfo.conf\n"
synosetkeyvalue /etc/synoinfo.conf unique synology_rtd1619b_ds423
synosetkeyvalue /etc.defaults/synoinfo.conf unique synology_rtd1619b_ds423
# Uninstall Container Manager if upgrading
if [[ $upgrade == "yes" ]]; then
echo "Upgrading Container Manager"
package_uninstall ContainerManager "Container Manager"
fi
# ? Download https://global.synologydownload.com/download/Package/spk/ContainerManager/20.10.23-1437/ContainerManager-armv8-20.10.23-1437.spk
# ? Do a Manual Install in Package Center of the .spk file you downloaded.
#
# Install Container Manager
package_install ContainerManager "$targetvol" "Container Manager"
if [[ $install_from_server_failed == "yes" ]]; then
do_manual_install
fi
# Allow package processes to finish starting
#wait_status ContainerManager start
# Stop Container Manager
package_stop ContainerManager "Container Manager"
# Allow package processes to finish stopping
wait_status ContainerManager stop
# Edit /var/packages/ContainerManager/INFO to delete the "exclude_model=..." line
if [[ $manual_install == "yes" ]]; then echo ""; fi
echo -e "Editing ContainerManager INFO\n"
sed -i "/exclude_model=*/d" /var/packages/ContainerManager/INFO
# Restore unique to original model
echo -e "Restoring synoinfo.conf\n"
synosetkeyvalue /etc/synoinfo.conf unique "$current_unique"
synosetkeyvalue /etc.defaults/synoinfo.conf unique "$current_unique"
# Start Container Manager
package_start ContainerManager "Container Manager"
echo -e "\nFinished\n"
if [[ $upgrade == "yes" ]]; then
echo -e "You will need to start your containers\n"
fi
echo -e "If Package Center is already open close it and re-open it.\n"
echo "You need to prevent Container Manager from auto updating:"
echo " 1. Go to 'Package Center > Settings > Auto-update'"
echo " 2. Select 'Only packages below'"
echo " 3. Untick Container Manager"
echo -e " 4. Click OK\n"
| 15,615 | install_container_manager | sh | en | shell | code | {"qsc_code_num_words": 1996, "qsc_code_num_chars": 15615.0, "qsc_code_mean_word_length": 4.62675351, "qsc_code_frac_words_unique": 0.18336673, "qsc_code_frac_chars_top_2grams": 0.02165674, "qsc_code_frac_chars_top_3grams": 0.01407688, "qsc_code_frac_chars_top_4grams": 0.01645912, "qsc_code_frac_chars_dupe_5grams": 0.30990796, "qsc_code_frac_chars_dupe_6grams": 0.24493774, "qsc_code_frac_chars_dupe_7grams": 0.21570114, "qsc_code_frac_chars_dupe_8grams": 0.15181375, "qsc_code_frac_chars_dupe_9grams": 0.13102328, "qsc_code_frac_chars_dupe_10grams": 0.12073633, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03261701, "qsc_code_frac_chars_whitespace": 0.24604547, "qsc_code_size_file_byte": 15615.0, "qsc_code_num_lines": 471.0, "qsc_code_num_chars_line_max": 142.0, "qsc_code_num_chars_line_mean": 33.15286624, "qsc_code_frac_chars_alphabet": 0.75180498, "qsc_code_frac_chars_comments": 0.25622799, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.30434783, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.3454749, "qsc_code_frac_chars_long_word_length": 0.04004133, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0} |
007gzs/meeting | miniprogram/utils/apiviewws.js |
"use strict";
const httpCookie = require('./http-cookie.js')
let app = getApp()
const TASK_STATUS = {
INIT: -1, // 初始化
ERROR: -2, // 连接错误
CLOSE: -3, // 连接关闭
CLOSEING: -4, // 请求连接关闭中
OK: 0, // 连接成功
CONNECTING: 1, // 连接中
RECONNECTING: 3, // 请求重连中
}
const ApiViewWS = function (ws_path, common_listener) {
this.listenerList = {}
this.common_listener = common_listener
this.gen_reqid = function () {
return "apiview_" + parseInt(Math.random() * 9000000000 + 1000000000)
}
this.ws_path = ws_path
this.task_status = TASK_STATUS.INIT
this.connects = []
this.last_msg_time = null
this._proc_data = (data) => {
let reqid = data['reqid']
if (reqid === undefined) {
if (typeof this.common_listener === "function") {
this.common_listener(data)
}
return
}
if (app === undefined) {
app = getApp()
}
let server_time = new Date(data["server_time"])
if (!isNaN(server_time)) {
this.last_msg_time = server_time
app.globalData.timeDifference = server_time.getTime() - new Date().getTime()
}
let listener = this.listenerList[reqid]
delete this.listenerList[reqid]
if (typeof listener === "function") {
listener(data["status_code"] == 200, data)
}
}
this._failall = () => {
for (let reqid in this.listenerList) {
if (typeof this.listenerList[reqid] === "function") {
this.listenerList[reqid](false, {status_code: -1})
}
}
}
this._connects_callback = (index, data) => {
while(this.connects.length > 0){
let connect = this.connects.pop()
connect[index](data)
}
}
this._new_task = () => {
this.showLoading = true
wx.showLoading({
title: '加载中',
})
let header = {
'Cookie': httpCookie.getCookieForReq()
}
this.task_status = TASK_STATUS.CONNECTING
this.task = wx.connectSocket({
url: this.ws_path,
header: header,
tcpNoDelay: false,
protocols: ["apiview"],
method: "GET",
success: res => {
},
fail: res => {
this._connects_callback(1, "网络错误")
if (this.showLoading){
this.showLoading = false
wx.hideLoading()
}
}
})
this.task.onClose(res => {
this._failall()
if (this.task_status === TASK_STATUS.RECONNECTING) {
//this._new_task()
} else if (this.task_status === TASK_STATUS.CLOSEING){
this.task_status = TASK_STATUS.CLOSE
this._connects_callback(1, "网络错误")
}
})
this.task.onError(res => {
this.task_status = TASK_STATUS.ERROR
if (this.showLoading) {
this.showLoading = false
wx.hideLoading()
}
this._failall()
this._connects_callback(1, "网络错误")
})
this.task.onMessage(res => {
this._proc_data(JSON.parse(res.data))
})
this.task.onOpen(res => {
this.task_status = TASK_STATUS.OK
if (this.showLoading) {
this.showLoading = false
wx.hideLoading()
}
this._connects_callback(0, this)
})
}
this.connect = () => {
return new Promise((resolve, reject) => {
if (this.task_status === TASK_STATUS.OK){
if (this.task.readyState === 1){
resolve(this)
return
}else{
this.task_status = TASK_STATUS.ERROR
}
}
this.connects.push([resolve, reject])
if (this.task_status < 0){
this._new_task()
}
})
}
this.close = () => {
this.task_status = TASK_STATUS.CLOSEING
if(this.task){
this.task.close()
}
}
this.reconnect = () => {
this.task_status = TASK_STATUS.RECONNECTING
if(this.task){
this.task.close()
}
this._new_task()
}
this.check_and_reconnect = (check_time) => {
if (this.task_status > 0 || !app){
return
}
if (this.task_status === TASK_STATUS.OK && this.last_msg_time && (app.nowDate() - this.last_msg_time) < (check_time * 1000)){
return
}
this.reconnect()
}
this.req = (path, data, listener) => {
let reqid = this.gen_reqid()
while (this.listenerList.hasOwnProperty(reqid)) {
reqid = this.gen_reqid()
}
this.listenerList[reqid] = listener
const req_data = { path: path, reqid: reqid, data: data }
this.task.send({
data: JSON.stringify(req_data),
success: res => {
},
fail: res => {
listener(false, {})
}
})
}
return this
}
module.exports = ApiViewWS | 4,493 | apiviewws | js | en | javascript | code | {"qsc_code_num_words": 498, "qsc_code_num_chars": 4493.0, "qsc_code_mean_word_length": 5.0502008, "qsc_code_frac_words_unique": 0.24096386, "qsc_code_frac_chars_top_2grams": 0.10735586, "qsc_code_frac_chars_top_3grams": 0.07793241, "qsc_code_frac_chars_top_4grams": 0.08588469, "qsc_code_frac_chars_dupe_5grams": 0.29065606, "qsc_code_frac_chars_dupe_6grams": 0.24493042, "qsc_code_frac_chars_dupe_7grams": 0.1471173, "qsc_code_frac_chars_dupe_8grams": 0.08747515, "qsc_code_frac_chars_dupe_9grams": 0.06441352, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01321451, "qsc_code_frac_chars_whitespace": 0.2757623, "qsc_code_size_file_byte": 4493.0, "qsc_code_num_lines": 171.0, "qsc_code_num_chars_line_max": 130.0, "qsc_code_num_chars_line_mean": 26.2748538, "qsc_code_frac_chars_alphabet": 0.75968039, "qsc_code_frac_chars_comments": 0.01535722, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.22619048, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.02622061, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.00595238, "qsc_codejavascript_num_statement_line": 0.03571429, "qsc_codejavascript_score_lines_no_logic": 0.03571429, "qsc_codejavascript_frac_words_legal_var_name": 0.72727273, "qsc_codejavascript_frac_words_legal_func_name": 1.0, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0} |
007gzs/meeting | miniprogram/utils/request.js |
"use strict";
const USE_WEBSOCKET = true
const httpCookie = require('./http-cookie.js')
const ApiViewWS = require('./apiviewws.js')
let app = getApp()
let apiViewWSs = {}
const reconnectApiViews = (check_time) => {
if(!USE_WEBSOCKET){
return
}
for(let i in apiViewWSs){
apiViewWSs[i].check_and_reconnect(check_time)
}
}
const getApiViewWS = (server, need_connect) => {
const ws_path = "ws" + server.substring(4) + "/wsapi"
return new Promise((resolve, reject) => {
if (!apiViewWSs.hasOwnProperty(ws_path)) {
apiViewWSs[ws_path] = new ApiViewWS(ws_path)
}
if (!need_connect){
resolve(apiViewWSs[ws_path])
return
}
apiViewWSs[ws_path].connect().then(res => {
resolve(apiViewWSs[ws_path])
}).catch(res => {
reject(res)
})
})
}
const check_res = function (res, server, path, data, method, header, resolve, reject, check_login) {
if (app === undefined) {
app = getApp()
}
if (check_login && res.data.code == app.api.ERROR_CODE.ERR_WECHAT_LOGIN) {
app.login().then(res => {
req(server, path, data, method, header, resolve, reject, false)
}).catch(res => {
resolve(res.data)
})
} else if (res.data.code != app.api.ERROR_CODE.SUCCESS) {
reject(res.data.message)
} else {
resolve(res.data.data)
}
}
const ws_request = function (server, path, data, method, header, resolve, reject, check_login) {
if (!USE_WEBSOCKET || path === '/api/wechat/login') {
wx_request(server, path, data, method, header, resolve, reject, check_login)
return
}
getApiViewWS(server, true).then(conn => {
conn.req(path, data, (succ, res) => {
if (!succ) {
reject("网络错误")
} else {
check_res(res, server, path, data, method, header, resolve, reject, check_login)
}
})
}).catch(res => {
wx_request(server, path, data, method, header, resolve, reject, check_login)
})
}
const wx_request = function (server, path, data, method, header, resolve, reject, check_login){
const url = server + path
header['Cookie'] = httpCookie.getCookieForReq()
const reqid = "req_" + parseInt(Math.random() * 9000000000 + 1000000000)
wx.request({
url: url,
data: data,
method: method,
header: header,
success(res) {
httpCookie.setCookieByHead(res.header)
if(app === undefined){
app = getApp()
}
let server_time = new Date(res.header["Date"])
if (!isNaN(server_time)){
app.globalData.timeDifference = server_time.getTime() - new Date().getTime()
}
if(USE_WEBSOCKET){
getApiViewWS(server, false).then(conn => {
conn.reconnect()
check_res(res, server, path, data, method, header, resolve, reject, check_login)
}).catch(res => {
check_res(res, server, path, data, method, header, resolve, reject, check_login)
})
}else{
check_res(res, server, path, data, method, header, resolve, reject, check_login)
}
},
fail(res) {
reject("网络错误")
},
complete() {
}
})
}
const req = function (server, path, data, method, header, resolve, reject, check_login){
return ws_request(server, path, data, method, header, resolve, reject, check_login)
}
const request = function({server, path, data, method, header} = {}){
for (let key in data) {
if(data[key] === undefined){
delete data[key]
}
}
return new Promise((resolve, reject) => {
wx.showNavigationBarLoading()
let resolve_callback = res => {
wx.hideNavigationBarLoading()
resolve(res)
}
let reject_callback = res => {
wx.hideNavigationBarLoading()
wx.showToast({
icon: 'none',
title: res
})
reject(res)
}
req(server, path, data, method, header, resolve_callback, reject_callback, true)
})
}
module.exports = request
module.exports.reconnectApiViews = reconnectApiViews
| 3,921 | request | js | en | javascript | code | {"qsc_code_num_words": 452, "qsc_code_num_chars": 3921.0, "qsc_code_mean_word_length": 5.30752212, "qsc_code_frac_words_unique": 0.19911504, "qsc_code_frac_chars_top_2grams": 0.06252605, "qsc_code_frac_chars_top_3grams": 0.08170071, "qsc_code_frac_chars_top_4grams": 0.1167153, "qsc_code_frac_chars_dupe_5grams": 0.40975406, "qsc_code_frac_chars_dupe_6grams": 0.36723635, "qsc_code_frac_chars_dupe_7grams": 0.36723635, "qsc_code_frac_chars_dupe_8grams": 0.32596915, "qsc_code_frac_chars_dupe_9grams": 0.29345561, "qsc_code_frac_chars_dupe_10grams": 0.29345561, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00695134, "qsc_code_frac_chars_whitespace": 0.22953328, "qsc_code_size_file_byte": 3921.0, "qsc_code_num_lines": 129.0, "qsc_code_num_chars_line_max": 101.0, "qsc_code_num_chars_line_mean": 30.39534884, "qsc_code_frac_chars_alphabet": 0.78715657, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.3046875, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.02321429, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.0390625, "qsc_codejavascript_num_statement_line": 0.1171875, "qsc_codejavascript_score_lines_no_logic": 0.09375, "qsc_codejavascript_frac_words_legal_var_name": 0.625, "qsc_codejavascript_frac_words_legal_func_name": 0.4, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0} |
007revad/Seagate_lowCurrentSpinup | seagate_lowcurrentspinup.sh | #!/usr/bin/env bash
#------------------------------------------------------------------------------
# Some Synology NAS and Expansion Units do not have enough power to spin-up
# multiple Seagate's 20TB and larger drives during boot-up.
#
# This script uses Seagate's openSeaChest to set your 20TB and larger
# Seagate HDDs to stagger their spin-up and enables lowCurrentSpinup.
#
# Power-Up in Standby (PUIS):
# PUIS ensures that drives remain in standby mode during system startup and only spin up when accessed.
#
# Low Current Spin-Up:
# This feature reduces the power draw during spin-up by starting the drives more gradually.
#
# Github: https://github.com/007revad/Seagate_lowCurrentSpinup
# Script verified at https://www.shellcheck.net/
#
# Run in a shell with sudo (replace /volume1/scripts/ with path to script):
# sudo -s /volume1/scripts/enable_segate_puis.sh
#
# To disable PUIS and lowCurrentSpinup
# sudo -s /volume1/scripts/enable_segate_puis.sh disable
#
# https://www.perplexity.ai/search/my-synology-1821-wont-start-up-DCEWq2y5TvO4WoUsFli_sw
#------------------------------------------------------------------------------
if [[ $1 == "disable" ]]; then
disable="yes"
fi
archive=openSeaChest-v24.08.1-linux-x86_64-portable
# shellcheck disable=SC2317 # Don't warn about unreachable commands in this function
# shellcheck disable=SC2329 # Don't warn about This function is never invoked.
pause(){
# When debugging insert pause command where needed
read -s -r -n 1 -p "Press any key to continue..."
read -r -t 0.1 -s -e -- # Silently consume all input
stty echo echok # Ensure read didn't disable echoing user input
echo -e "\n"
}
# Download openSeaChest portable if needed
if [[ ! -f /opt/openSeaChest_PowerControl ]] || [[ ! -f /opt/openSeaChest_Configure ]]; then
if [[ ! -f "/tmp/${archive}.tar.xz" ]]; then
echo -e "\nDownloading openSeaChest portable from Seagate"
wget -P /tmp/ https://github.com/Seagate/openSeaChest/releases/download/v24.08.1/"${archive:?}".tar.xz &>/dev/null
fi
fi
# Extract openSeaChest_PowerControl to /tmp if needed
if [[ ! -d "/tmp/${archive:?}" ]] && [[ -f "/tmp/${archive}.tar.xz" ]]; then
echo -e "\nExtracting openSeaChest archive"
tar -xf "/tmp/${archive}.tar.xz" -C /tmp
# Delete downloaded archive
rm "/tmp/${archive}.tar.xz"
echo
fi
# Create /opt if needed
if [[ ! -d /opt ]]; then
if mkdir /opt; then
chown root:root /opt
chmod 711 /opt
else
echo -e "ERROR Failed to create /opt !"
exit 1
fi
fi
# Copy openSeaChest_PowerControl to /opt if needed
if [[ ! -f /opt/openSeaChest_PowerControl ]]; then
if cp /tmp/"${archive:?}"/openSeaChest_PowerControl /opt/openSeaChest_PowerControl; then
# openSeaChest/releases/download/v24.08.1 needs owner:group set
chown root:root /opt/openSeaChest_PowerControl
chmod 755 /opt/openSeaChest_PowerControl
else
echo -e "ERROR Failed to copy openSeaChest_PowerControl to /opt !"
exit 1
fi
fi
# Copy openSeaChest_Configure to /opt if needed
if [[ ! -f /opt/openSeaChest_Configure ]]; then
if cp /tmp/"${archive:?}"/openSeaChest_Configure /opt/openSeaChest_Configure; then
# openSeaChest/releases/download/v24.08.1 needs owner:group set
chown root:root /opt/openSeaChest_Configure
chmod 755 /opt/openSeaChest_Configure
else
echo -e "ERROR Failed to copy openSeaChest_Configure to /opt !"
exit 1
fi
fi
# Delete tmp extracted archive directory
if [[ ! -d "/tmp/${archive:?}" ]]; then
rm -rf "/tmp/${archive:?}"
fi
set_puis(){
# Set Power Up In Standby
#--------------------------------------------------------------------------
# --puisFeature [ info | spinup | enable | disable ] (SATA Only)
# Use this option to enable or disable the power up in standby (PUIS) feature on SATA drives.
# Arguments:
# info - display information about the PUIS support on the device
# spinup - issue the PUIS spinup set features command to spin up the device to active/idle state.
# enable - enable the PUIS feature using setfeatures command
# disable - disable the PUIS feature using setfeatures command
# Note: Not all products support this feature.
#--------------------------------------------------------------------------
# Check if PUIS is supported
if ! /opt/openSeaChest_PowerControl -d "$sg" --puisFeature info | grep -q 'PUIS is supported'; then
/opt/openSeaChest_PowerControl -d "$sg" --puisFeature info | tail +9
else
if [[ $disable == "yes" ]]; then
# Disable PUIS
/opt/openSeaChest_PowerControl -d "$sg" --puisFeature disable | tail +9 | head -n -1
else
# Enable PUIS
/opt/openSeaChest_PowerControl -d "$sg" --puisFeature enable | tail +9 | head -n -1
fi
fi
}
set_lcs(){
# Set lowCurrentSpinup
#--------------------------------------------------------------------------
# --lowCurrentSpinup [ low | ultra | disable ] (SATA Only) (Seagate Only)
# Use this option to set the state of the low current spinup feature on Seagate SATA drives.
# When this setting is enabled for low or ultra low mode,
# the drive will take longer to spinup and become ready.
# Note: This feature is not available on every drive.
# Note: Some products will support low, but not the ultra low current spinup mode.
#--------------------------------------------------------------------------
if [[ $disable == "yes" ]]; then
/opt/openSeaChest_Configure -d "$sg" --lowCurrentSpinup disable | tail +11
else
/opt/openSeaChest_Configure -d "$sg" --lowCurrentSpinup low | tail +11
fi
}
# Process SATA Seagate HDDs larger than 18TB
IFS=$'\n' read -r -d '' -a array < <(/opt/openSeaChest_PowerControl --scan |\
# Only Seagate SATA drives support PUIS
grep -E '^ATA.*ST[1-4][0-9][0]{3,}NT') # All Seagate Exos drives
#grep -E '^ATA.*ST[2-4][0,9][0]{3,}') # All Seagate 20TB and larger drives
#grep -E '^ATA.*ST[1-4][0-9][0]{3,}') # debug with smaller Seagate Ironwolf drives
IFS=
if [[ "${#array[@]}" -gt "0" ]]; then
if [[ $disable == "yes" ]]; then
echo -e "Disabling 'Enable Power-Up in Standby' and 'Low Current Spin-up'\n"
else
echo -e "Enabling 'Enable Power-Up in Standby' and 'Low Current Spin-up'\n"
fi
for drive in "${array[@]}"; do
#echo "$drive" | awk '{print $3, $4}' # debug
sg=$(echo "$drive" | awk '{print $2}')
# /opt/openSeaChest_PowerControl -d "$sg" --puisFeature enable
# PUIS info
# /opt/openSeaChest_PowerControl -d "$sg" --puisFeature info | tail +9
#echo
set_puis
set_lcs
done
fi
exit
| 6,956 | seagate_lowcurrentspinup | sh | en | shell | code | {"qsc_code_num_words": 888, "qsc_code_num_chars": 6956.0, "qsc_code_mean_word_length": 4.69256757, "qsc_code_frac_words_unique": 0.28153153, "qsc_code_frac_chars_top_2grams": 0.06839453, "qsc_code_frac_chars_top_3grams": 0.07775378, "qsc_code_frac_chars_top_4grams": 0.04031677, "qsc_code_frac_chars_dupe_5grams": 0.34581234, "qsc_code_frac_chars_dupe_6grams": 0.30525558, "qsc_code_frac_chars_dupe_7grams": 0.22558195, "qsc_code_frac_chars_dupe_8grams": 0.1550276, "qsc_code_frac_chars_dupe_9grams": 0.09215263, "qsc_code_frac_chars_dupe_10grams": 0.06815455, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01869678, "qsc_code_frac_chars_whitespace": 0.22340426, "qsc_code_size_file_byte": 6956.0, "qsc_code_num_lines": 178.0, "qsc_code_num_chars_line_max": 123.0, "qsc_code_num_chars_line_mean": 39.07865169, "qsc_code_frac_chars_alphabet": 0.75268419, "qsc_code_frac_chars_comments": 0.54528465, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.34939759, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.21442125, "qsc_code_frac_chars_long_word_length": 0.0512334, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0} |
007gzs/dingtalk-sdk | dingtalk/crypto/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import time
import base64
import json
from dingtalk.core.exceptions import InvalidSignatureException, InvalidCorpIdOrSuiteKeyException
from dingtalk.core.utils import to_text, to_binary, DingTalkSigner, random_string
from dingtalk.crypto.base import BasePrpCrypto
def _get_signature(token, timestamp, nonce, encrypt):
signer = DingTalkSigner()
signer.add_data(token, timestamp, nonce, encrypt)
return signer.signature
class PrpCrypto(BasePrpCrypto):
def encrypt(self, text, _id):
return self._encrypt(text, _id)
def decrypt(self, text, _id):
return self._decrypt(text, _id, InvalidCorpIdOrSuiteKeyException)
class BaseDingTalkCrypto(object):
def __init__(self, token, encoding_aes_key, _id):
if encoding_aes_key:
encoding_aes_key = to_binary(encoding_aes_key + '=')
self.key = base64.b64decode(encoding_aes_key)
assert len(self.key) == 32
else:
self.key = None
self.token = token
self._id = _id
def _decrypt_encrypt_str(self,
signature,
timestamp,
nonce,
encrypt_str,
crypto_class=None):
_signature = _get_signature(self.token, timestamp, nonce, encrypt_str)
if _signature != signature:
raise InvalidSignatureException()
assert self.key is not None
pc = crypto_class(self.key)
return pc.decrypt(encrypt_str, self._id)
def _encrypt_message(self,
msg,
nonce=None,
timestamp=None,
crypto_class=None):
timestamp = timestamp or int(time.time() * 1000)
timestamp = to_text(timestamp)
if nonce is None:
nonce = random_string()
assert self.key is not None
pc = crypto_class(self.key)
encrypt = to_text(pc.encrypt(msg, self._id))
signature = _get_signature(self.token, timestamp, nonce, encrypt)
result = dict()
result['msg_signature'] = signature
result['encrypt'] = encrypt
result['timeStamp'] = timestamp
result['nonce'] = nonce
return result
def _decrypt_message(self,
msg,
signature,
timestamp,
nonce,
crypto_class=None):
if not isinstance(msg, dict):
msg = json.loads(to_text(msg))
encrypt = msg['encrypt']
return self._decrypt_encrypt_str(signature, timestamp, nonce, encrypt, crypto_class)
class DingTalkCrypto(BaseDingTalkCrypto):
def __init__(self, token, encoding_aes_key, corpid_or_suitekey):
super(DingTalkCrypto, self).__init__(token, encoding_aes_key, corpid_or_suitekey)
def decrypt_encrypt_str(self, signature, timestamp, nonce, encrypt_str):
return self._decrypt_encrypt_str(signature, timestamp, nonce, encrypt_str, PrpCrypto)
def encrypt_message(self, msg, nonce=None, timestamp=None):
return self._encrypt_message(msg, nonce, timestamp, PrpCrypto)
def decrypt_message(self, msg, signature, timestamp, nonce):
return self._decrypt_message(
msg,
signature,
timestamp,
nonce,
PrpCrypto
)
| 3,522 | __init__ | py | en | python | code | {"qsc_code_num_words": 363, "qsc_code_num_chars": 3522.0, "qsc_code_mean_word_length": 5.6446281, "qsc_code_frac_words_unique": 0.20385675, "qsc_code_frac_chars_top_2grams": 0.07515861, "qsc_code_frac_chars_top_3grams": 0.08199122, "qsc_code_frac_chars_top_4grams": 0.05075647, "qsc_code_frac_chars_dupe_5grams": 0.36798438, "qsc_code_frac_chars_dupe_6grams": 0.34699854, "qsc_code_frac_chars_dupe_7grams": 0.34699854, "qsc_code_frac_chars_dupe_8grams": 0.29282577, "qsc_code_frac_chars_dupe_9grams": 0.19716935, "qsc_code_frac_chars_dupe_10grams": 0.0966325, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00535862, "qsc_code_frac_chars_whitespace": 0.31118683, "qsc_code_size_file_byte": 3522.0, "qsc_code_num_lines": 105.0, "qsc_code_num_chars_line_max": 97.0, "qsc_code_num_chars_line_mean": 33.54285714, "qsc_code_frac_chars_alphabet": 0.83924155, "qsc_code_frac_chars_comments": 0.00596252, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.23170732, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01200343, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.03658537, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.13414634, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.08536585, "qsc_codepython_frac_lines_simplefunc": 0.06097560975609756, "qsc_codepython_score_lines_no_logic": 0.36585366, "qsc_codepython_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
007gzs/dingtalk-sdk | dingtalk/crypto/base.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import struct
import socket
import base64
from dingtalk.core.utils import to_text, to_binary, random_string, byte2int
from dingtalk.crypto.pkcs7 import PKCS7Encoder
try:
from dingtalk.crypto.cryptography import DingTalkCipher
except ImportError:
try:
from dingtalk.crypto.pycrypto import DingTalkCipher
except ImportError:
raise Exception('You must install either cryptography or PyCrypto!')
class BasePrpCrypto(object):
def __init__(self, key):
self.cipher = DingTalkCipher(key)
def get_random_string(self):
return random_string(16)
def _encrypt(self, text, _id):
text = to_binary(text)
tmp_list = []
tmp_list.append(to_binary(self.get_random_string()))
length = struct.pack(b'I', socket.htonl(len(text)))
tmp_list.append(length)
tmp_list.append(text)
tmp_list.append(to_binary(_id))
text = b''.join(tmp_list)
text = PKCS7Encoder.encode(text)
ciphertext = to_binary(self.cipher.encrypt(text))
return base64.b64encode(ciphertext)
def _decrypt(self, text, _id, exception=None):
text = to_binary(text)
plain_text = self.cipher.decrypt(base64.b64decode(text))
padding = byte2int(plain_text[-1])
content = plain_text[16:-padding]
xml_length = socket.ntohl(struct.unpack(b'I', content[:4])[0])
xml_content = to_text(content[4:xml_length + 4])
from_id = to_text(content[xml_length + 4:])
if from_id != _id:
exception = exception or Exception
raise exception()
return xml_content
| 1,707 | base | py | en | python | code | {"qsc_code_num_words": 214, "qsc_code_num_chars": 1707.0, "qsc_code_mean_word_length": 5.14485981, "qsc_code_frac_words_unique": 0.35514019, "qsc_code_frac_chars_top_2grams": 0.04359673, "qsc_code_frac_chars_top_3grams": 0.04722979, "qsc_code_frac_chars_top_4grams": 0.03814714, "qsc_code_frac_chars_dupe_5grams": 0.03814714, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01969697, "qsc_code_frac_chars_whitespace": 0.22671353, "qsc_code_size_file_byte": 1707.0, "qsc_code_num_lines": 52.0, "qsc_code_num_chars_line_max": 77.0, "qsc_code_num_chars_line_mean": 32.82692308, "qsc_code_frac_chars_alphabet": 0.81439394, "qsc_code_frac_chars_comments": 0.01230228, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.14285714, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.03028504, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.0952381, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.23809524, "qsc_codepython_frac_lines_simplefunc": 0.023809523809523808, "qsc_codepython_score_lines_no_logic": 0.42857143, "qsc_codepython_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
007revad/Seagate_lowCurrentSpinup | README.md | # Seagate Low Current Spinup
<a href="https://github.com/007revad/Seagate_lowCurrentSpinup/releases"><img src="https://img.shields.io/github/release/007revad/Seagate_lowCurrentSpinup.svg"></a>

[](https://www.paypal.com/paypalme/007revad)
[](https://github.com/sponsors/007revad)
[](https://user-badge.committers.top/australia/007revad)
### Description
Some Synology NAS and Expansion Units do not have enough power to spin-up multiple Seagate large Exos drives during boot-up.
This script avoids the need to buy and install a higher wattage power supply.
It uses Seagate's openSeaChest v24.08.1 to set your Seagate Exos SATA HDDs to stagger their spin-up (PUIS) and enables lowCurrentSpinup.
Power-Up in Standby (PUIS):
PUIS ensures that drives remain in standby mode during system startup and only spin up when accessed
Low Current Spin-Up:
This feature reduces the power draw during spin-up by starting the drives more gradually
**NOTE:** After running the script you will need to reboot.
### Download the script
1. Download the latest version _Source code (zip)_ from https://github.com/007revad/Seagate_lowCurrentSpinup/releases
2. Save the download zip file to a folder on the Synology.
3. Unzip the zip file.
### To run the script via task scheduler
See [How to run from task scheduler](https://github.com/007revad/Seagate_lowCurrentSpinup/blob/main/how_to_run_from_scheduler.md)
### To run the script via SSH
[How to enable SSH and login to DSM via SSH](https://kb.synology.com/en-global/DSM/tutorial/How_to_login_to_DSM_with_root_permission_via_SSH_Telnet)
```YAML
sudo -s /volume1/scripts/seagate_lowcurrentspinup.sh
```
If you want to change the drives' settings back run the script with the disable option:
```YAML
sudo -s /volume1/scripts/seagate_lowcurrentspinup.sh disable
```
**Note:** Replace /volume1/scripts/ with the path to where the script is located.
### Troubleshooting
If the script won't run check the following:
1. Make sure you download the zip file and unzipped it to a folder on your Synology (not on your computer).
2. If the path to the script contains any spaces you need to enclose the path/scriptname in double quotes:
```YAML
sudo -s "/volume1/my scripts/seagate_lowcurrentspinup.sh"
```
3. Make sure you unpacked the zip or rar file that you downloaded and are trying to run the seagate_lowcurrentspinup.sh file.
4. Set the script file as executable:
```YAML
sudo chmod +x "/volume1/scripts/seagate_lowcurrentspinup.sh"
```
### Screenshots
<p align="center">Enabling PUIS and Low Power Spinup</p>
<p align="center"><img src="/images/enable.png"></p>
<br>
<p align="center">Disabling PUIS and Low Power Spinup</p>
<p align="center"><img src="/images/disable.png"></p>
| 3,201 | README | md | en | markdown | text | {"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.1878453, "qsc_doc_num_sentences": 57.0, "qsc_doc_num_words": 504, "qsc_doc_num_chars": 3201.0, "qsc_doc_num_lines": 74.0, "qsc_doc_mean_word_length": 4.80555556, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.42857143, "qsc_doc_entropy_unigram": 4.94641041, "qsc_doc_frac_words_all_caps": 0.03038674, "qsc_doc_frac_lines_dupe_lines": 0.16326531, "qsc_doc_frac_chars_dupe_lines": 0.01294917, "qsc_doc_frac_chars_top_2grams": 0.08546656, "qsc_doc_frac_chars_top_3grams": 0.05161024, "qsc_doc_frac_chars_top_4grams": 0.05284889, "qsc_doc_frac_chars_dupe_5grams": 0.20644096, "qsc_doc_frac_chars_dupe_6grams": 0.17630058, "qsc_doc_frac_chars_dupe_7grams": 0.15772089, "qsc_doc_frac_chars_dupe_8grams": 0.0776218, "qsc_doc_frac_chars_dupe_9grams": 0.03798514, "qsc_doc_frac_chars_dupe_10grams": 0.03798514, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 23.44274809, "qsc_doc_frac_chars_hyperlink_html_tag": 0.32521087, "qsc_doc_frac_chars_alphabet": 0.83927299, "qsc_doc_frac_chars_digital": 0.02387741, "qsc_doc_frac_chars_whitespace": 0.12339894, "qsc_doc_frac_chars_hex_words": 0.0} | 1 | {"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0} |
007revad/Seagate_lowCurrentSpinup | how_to_run_from_scheduler.md | # How to run a script in Synology Task Scheduler
To run a script from Task Scheduler follow these steps:
**Note:** You can setup a schedule task and leave it disabled, so it only runs when you select the task in the Task Scheduler and click on the Run button.
1. Go to **Control Panel** > **Task Scheduler** > click **Create** > and select **Scheduled Task**.
2. Select **User-defined script**.
3. Enter a task name.
4. Select **root** as the user (The script needs to run as root).
5. Untick **Enable** so it does **not** run on a schedule.
6. Click **Task Settings**.
7. In the box under **User-defined script** type the path to the script.
- e.g. If you saved the script to a shared folder on volume 1 called "scripts" you'd type: **/volume1/scripts/seagate_lowcurrentspinup.sh**
8. Click **OK** to save the settings.
9. Click on the task - but **don't** enable it - then click **Run**.
10. Once the script has run you can delete the task, or keep in case you need it again.
**Here's some screenshots showing what needs to be set:**
<p align="center">Step 1</p>
<p align="center"><img src="images/schedule-1.png"></p>
<p align="center">Step 2</p>
<p align="center"><img src="images/schedule-2.png"></p>
<p align="center">Step 3</p>
<p align="center"><img src="images/schedule-3.png"></p>
<p align="center">Step 4</p>
<p align="center"><img src="images/schedule-4.png"></p>
| 1,389 | how_to_run_from_scheduler | md | en | markdown | text | {"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.24274406, "qsc_doc_num_sentences": 29.0, "qsc_doc_num_words": 251, "qsc_doc_num_chars": 1389.0, "qsc_doc_num_lines": 31.0, "qsc_doc_mean_word_length": 3.81673307, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.42231076, "qsc_doc_entropy_unigram": 4.24621219, "qsc_doc_frac_words_all_caps": 0.00263852, "qsc_doc_frac_lines_dupe_lines": 0.0, "qsc_doc_frac_chars_dupe_lines": 0.0, "qsc_doc_frac_chars_top_2grams": 0.05010438, "qsc_doc_frac_chars_top_3grams": 0.10020877, "qsc_doc_frac_chars_top_4grams": 0.09498956, "qsc_doc_frac_chars_dupe_5grams": 0.20041754, "qsc_doc_frac_chars_dupe_6grams": 0.20041754, "qsc_doc_frac_chars_dupe_7grams": 0.13778706, "qsc_doc_frac_chars_dupe_8grams": 0.13778706, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 22.16666667, "qsc_doc_frac_chars_hyperlink_html_tag": 0.22174226, "qsc_doc_frac_chars_alphabet": 0.80222603, "qsc_doc_frac_chars_digital": 0.01797945, "qsc_doc_frac_chars_whitespace": 0.15910727, "qsc_doc_frac_chars_hex_words": 0.0} | 1 | {"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0} |
007gzs/dingtalk-sdk | dingtalk/core/exceptions.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import six
from dingtalk.core.utils import to_binary, to_text
class DingTalkException(Exception):
def __init__(self, errcode, errmsg):
"""
:param errcode: Error code
:param errmsg: Error message
"""
self.errcode = errcode
self.errmsg = errmsg
def __str__(self):
_repr = 'Error code: {code}, message: {msg}'.format(
code=self.errcode,
msg=self.errmsg
)
if six.PY2:
return to_binary(_repr)
else:
return to_text(_repr)
def __repr__(self):
_repr = '{klass}({code}, {msg})'.format(
klass=self.__class__.__name__,
code=self.errcode,
msg=self.errmsg
)
if six.PY2:
return to_binary(_repr)
else:
return to_text(_repr)
class DingTalkClientException(DingTalkException):
"""WeChat API client exception class"""
def __init__(self, errcode, errmsg, client=None,
request=None, response=None):
super(DingTalkClientException, self).__init__(errcode, errmsg)
self.client = client
self.request = request
self.response = response
class InvalidSignatureException(DingTalkException):
"""Invalid signature exception class"""
def __init__(self, errcode=-40001, errmsg='Invalid signature'):
super(InvalidSignatureException, self).__init__(errcode, errmsg)
class InvalidCorpIdOrSuiteKeyException(DingTalkException):
"""Invalid app_id exception class"""
def __init__(self, errcode=-40005, errmsg='Invalid CorpIdOrSuiteKey'):
super(InvalidCorpIdOrSuiteKeyException, self).__init__(errcode, errmsg)
| 1,788 | exceptions | py | en | python | code | {"qsc_code_num_words": 178, "qsc_code_num_chars": 1788.0, "qsc_code_mean_word_length": 6.0505618, "qsc_code_frac_words_unique": 0.30898876, "qsc_code_frac_chars_top_2grams": 0.07149489, "qsc_code_frac_chars_top_3grams": 0.04085422, "qsc_code_frac_chars_top_4grams": 0.06685237, "qsc_code_frac_chars_dupe_5grams": 0.2544104, "qsc_code_frac_chars_dupe_6grams": 0.22655525, "qsc_code_frac_chars_dupe_7grams": 0.13741876, "qsc_code_frac_chars_dupe_8grams": 0.13741876, "qsc_code_frac_chars_dupe_9grams": 0.13741876, "qsc_code_frac_chars_dupe_10grams": 0.13741876, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00983359, "qsc_code_frac_chars_whitespace": 0.2606264, "qsc_code_size_file_byte": 1788.0, "qsc_code_num_lines": 63.0, "qsc_code_num_chars_line_max": 80.0, "qsc_code_num_chars_line_mean": 28.38095238, "qsc_code_frac_chars_alphabet": 0.80484115, "qsc_code_frac_chars_comments": 0.09899329, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.30769231, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.06202046, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.15384615, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.07692308, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.43589744, "qsc_codepython_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
007gzs/dingtalk-sdk | dingtalk/core/utils.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import hashlib
import json
import random
import string
import six
class ObjectDict(dict):
"""Makes a dictionary behave like an object, with attribute-style access.
"""
def __getattr__(self, key):
if key in self:
return self[key]
return None
def __setattr__(self, key, value):
self[key] = value
class DingTalkSigner(object):
"""DingTalk data signer"""
def __init__(self, delimiter=b''):
self._data = []
self._delimiter = to_binary(delimiter)
def add_data(self, *args):
"""Add data to signer"""
for data in args:
self._data.append(to_binary(data))
@property
def signature(self):
"""Get data signature"""
self._data.sort()
str_to_sign = self._delimiter.join(self._data)
return hashlib.sha1(str_to_sign).hexdigest()
def to_text(value, encoding='utf-8'):
"""Convert value to unicode, default encoding is utf-8
:param value: Value to be converted
:param encoding: Desired encoding
"""
if not value:
return ''
if isinstance(value, six.text_type):
return value
if isinstance(value, six.binary_type):
return value.decode(encoding)
return six.text_type(value)
def to_binary(value, encoding='utf-8'):
"""Convert value to binary string, default encoding is utf-8
:param value: Value to be converted
:param encoding: Desired encoding
"""
if not value:
return b''
if isinstance(value, six.binary_type):
return value
if isinstance(value, six.text_type):
return value.encode(encoding)
return to_text(value).encode(encoding)
def random_string(length=16):
rule = string.ascii_letters + string.digits
rand_list = random.sample(rule, length)
return ''.join(rand_list)
def byte2int(c):
if six.PY2:
return ord(c)
return c
def json_loads(s, object_hook=ObjectDict, **kwargs):
return json.loads(s, object_hook=object_hook, **kwargs)
| 2,105 | utils | py | en | python | code | {"qsc_code_num_words": 275, "qsc_code_num_chars": 2105.0, "qsc_code_mean_word_length": 4.8, "qsc_code_frac_words_unique": 0.33090909, "qsc_code_frac_chars_top_2grams": 0.01515152, "qsc_code_frac_chars_top_3grams": 0.05151515, "qsc_code_frac_chars_top_4grams": 0.06060606, "qsc_code_frac_chars_dupe_5grams": 0.33939394, "qsc_code_frac_chars_dupe_6grams": 0.30909091, "qsc_code_frac_chars_dupe_7grams": 0.30909091, "qsc_code_frac_chars_dupe_8grams": 0.26212121, "qsc_code_frac_chars_dupe_9grams": 0.14090909, "qsc_code_frac_chars_dupe_10grams": 0.14090909, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00627746, "qsc_code_frac_chars_whitespace": 0.2432304, "qsc_code_size_file_byte": 2105.0, "qsc_code_num_lines": 88.0, "qsc_code_num_chars_line_max": 78.0, "qsc_code_num_chars_line_mean": 23.92045455, "qsc_code_frac_chars_alphabet": 0.82234777, "qsc_code_frac_chars_comments": 0.19429929, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.15686275, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00610128, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.19607843, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.11764706, "qsc_codepython_frac_lines_simplefunc": 0.0196078431372549, "qsc_codepython_score_lines_no_logic": 0.64705882, "qsc_codepython_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
007gzs/dingtalk-sdk | dingtalk/model/message.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from dingtalk.core.utils import to_text
class BodyBase(object):
_msgtype = None
def __init__(self, **kwargs):
for k, v in kwargs.items():
if callable(v):
v = v()
setattr(self, k, v)
def get_dict(self):
assert self._msgtype
return {'msgtype': self._msgtype, self._msgtype: self.get_data()}
def get_data(self):
ret = {}
for k in dir(self):
if k.startswith('_'):
continue
v = getattr(self, k, None)
if v is None or hasattr(v, '__call__'):
continue
if v is not None:
if isinstance(v, BodyBase):
v = v.get_data()
ret[k] = v
return ret
class TextBody(BodyBase):
_msgtype = 'text'
content = None
def __init__(self, content, **kwargs):
"""
文本消息
:param content: 消息内容
:param kwargs:
"""
super(TextBody, self).__init__(content=content, **kwargs)
class FileBody(BodyBase):
_msgtype = 'file'
media_id = None
def __init__(self, media_id, **kwargs):
"""
文件消息
:param media_id: 媒体文件id,可以调用上传媒体文件接口获取。10MB
:param kwargs:
"""
super(FileBody, self).__init__(media_id=media_id, **kwargs)
class ImageBody(FileBody):
_msgtype = 'image'
def __init__(self, media_id, **kwargs):
"""
图片消息
:param media_id: 图片媒体文件id,可以调用上传媒体文件接口获取。建议宽600像素 x 400像素,宽高比3:2
:param kwargs:
"""
super(FileBody, self).__init__(media_id=media_id, **kwargs)
class VoiceBody(FileBody):
_msgtype = 'voice'
duration = None
def __init__(self, media_id, duration=None, **kwargs):
"""
语音消息
:param media_id: 语音媒体文件id,可以调用上传媒体文件接口获取。2MB,播放长度不超过60s,AMR格式
:param duration: 正整数,小于60,表示音频时长
:param kwargs:
"""
super(VoiceBody, self).__init__(media_id=media_id, duration=duration, **kwargs)
class LinkBody(BodyBase):
_msgtype = 'link'
messageUrl = None
title = None
text = None
picUrl = None
def __init__(self, message_url, pic_url, title, text, **kwargs):
"""
超链接消息
:param message_url: 消息点击链接地址
:param pic_url: 图片媒体文件id,可以调用上传媒体文件接口获取
:param title: 消息标题
:param text: 消息描述
"""
super(LinkBody, self).__init__(messageUrl=message_url, picUrl=pic_url, title=title, text=text, **kwargs)
class MarkdownBody(BodyBase):
_msgtype = "markdown"
title = None
text = None
def __init__(self, title, text, **kwargs):
"""
markdown消息
:param title: 首屏会话透出的展示内容
:param text: markdown格式的消息
:param kwargs:
"""
super(MarkdownBody, self).__init__(title=title, text=text, **kwargs)
class OaBodyContent(BodyBase):
title = None
_forms = None
rich = None
content = None
image = None
file_count = None
author = None
def __init__(self, title=None, content=None, author=None, image=None, file_count=None, forms=dict,
rich_num=None, rish_unit=None, **kwargs):
"""
OA消息 消息体
:param title: 消息体的标题
:param content: 消息体的内容,最多显示3行
:param author: 自定义的作者名字
:param image: 消息体中的图片media_id
:param file_count: 自定义的附件数目。此数字仅供显示,钉钉不作验证
:param forms: 消息体的表单
:param rich_num: 单行富文本信息的数目
:param rish_unit: 单行富文本信息的单位
:param kwargs:
"""
rich = None
if rich_num is not None or rish_unit is not None:
rich = {'num': rich_num, 'unit': rish_unit}
super(OaBodyContent, self).__init__(title=title, content=content, author=author, image=image,
file_count=file_count, _forms=forms, rich=rich, **kwargs)
@property
def form(self):
if not self._forms:
return None
ret = []
for k, v in self._forms.items():
ret.append({"key": k, "value": v})
return ret
class OaBody(BodyBase):
_msgtype = 'oa'
message_url = None
pc_message_url = None
head = None
body = None
def __init__(self, message_url, head_bgcolor, head_text, body, pc_message_url=None, **kwargs):
"""
OA消息
:param message_url: 客户端点击消息时跳转到的H5地址
:param head_bgcolor: 消息头部的背景颜色。长度限制为8个英文字符,其中前2为表示透明度,后6位表示颜色值。不要添加0x
:param head_text: 消息的头部标题(向普通会话发送时有效,向企业会话发送时会被替换为微应用的名字),长度限制为最多10个字符
:param body: OaBodyContent OA消息 消息体
:param pc_message_url: PC端点击消息时跳转到的H5地址
:param kwargs:
"""
super(OaBody, self).__init__(message_url=message_url, head={"bgcolor": head_bgcolor, "text": head_text},
body=body, pc_message_url=pc_message_url, **kwargs)
class ActionCardBody(BodyBase):
_msgtype = 'action_card'
title = None
markdown = None
def __init__(self, title, markdown, **kwargs):
super(ActionCardBody, self).__init__(title=title, markdown=markdown, **kwargs)
class SingleActionCardBody(ActionCardBody):
single_title = None
single_url = None
def __init__(self, title, markdown, single_title, single_url, **kwargs):
"""
整体跳转ActionCard消息
:param title: 透出到会话列表和通知的文案
:param markdown: 消息内容,支持markdown
:param single_title: 标题
:param single_url: 链接url
:param kwargs:
"""
super(SingleActionCardBody, self).__init__(title=title, markdown=markdown,
single_title=single_title, single_url=single_url, **kwargs)
class BtnActionCardBody(ActionCardBody):
btn_orientation = None
btn_json_list = None
def __init__(self, title, markdown, btn_orientation, btn_list=(), **kwargs):
"""
独立跳转ActionCard消息
:param title: 透出到会话列表和通知的文案
:param markdown: 消息内容,支持markdown
:param btn_orientation: 按钮排列方式,竖直排列(0),横向排列(1)
:param btn_json_list: 按钮列表
:param kwargs:
"""
btn_orientation = to_text(btn_orientation)
assert btn_orientation in ('0', '1')
super(BtnActionCardBody, self).__init__(title=title, markdown=markdown,
btn_orientation=btn_orientation, btn_json_list=list(btn_list), **kwargs)
def add_btn(self, title, action_url):
"""
添加按钮
:param title: 标题
:param action_url: 链接url
:return:
"""
assert isinstance(self.btn_json_list, list)
self.btn_json_list.append({'title': title, 'action_url': action_url})
| 6,776 | message | py | en | python | code | {"qsc_code_num_words": 740, "qsc_code_num_chars": 6776.0, "qsc_code_mean_word_length": 5.13783784, "qsc_code_frac_words_unique": 0.22297297, "qsc_code_frac_chars_top_2grams": 0.02393477, "qsc_code_frac_chars_top_3grams": 0.03471857, "qsc_code_frac_chars_top_4grams": 0.04339821, "qsc_code_frac_chars_dupe_5grams": 0.19621252, "qsc_code_frac_chars_dupe_6grams": 0.17517096, "qsc_code_frac_chars_dupe_7grams": 0.05891636, "qsc_code_frac_chars_dupe_8grams": 0.05891636, "qsc_code_frac_chars_dupe_9grams": 0.02998422, "qsc_code_frac_chars_dupe_10grams": 0.02998422, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00613887, "qsc_code_frac_chars_whitespace": 0.30283353, "qsc_code_size_file_byte": 6776.0, "qsc_code_num_lines": 244.0, "qsc_code_num_chars_line_max": 121.0, "qsc_code_num_chars_line_mean": 27.7704918, "qsc_code_frac_chars_alphabet": 0.79868755, "qsc_code_frac_chars_comments": 0.20941558, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.15929204, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.02146916, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.02654867, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.14159292, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.01769912, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.61061947, "qsc_codepython_frac_lines_print": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 1, "qsc_codepython_frac_lines_print": 0} |
007gzs/meeting | server/meeting/urls.py | # encoding: utf-8
from __future__ import absolute_import, unicode_literals
from django.conf.urls.static import static
"""meeting URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/dev/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.urls import include, path
from django.contrib import admin
from core.utils import get_api_js
api_patterns = [
path('wechat/', include("apps.wechat.views")),
path('meeting/', include("apps.meetings.views")),
]
urlpatterns = [
path('cool/', include('cool.urls')),
path('sysadmin/', admin.site.urls),
path('api/', include(api_patterns)),
]
if settings.DEBUG:
urlpatterns.append(path('api.js', get_api_js))
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| 1,317 | urls | py | en | python | code | {"qsc_code_num_words": 192, "qsc_code_num_chars": 1317.0, "qsc_code_mean_word_length": 4.828125, "qsc_code_frac_words_unique": 0.41145833, "qsc_code_frac_chars_top_2grams": 0.05393743, "qsc_code_frac_chars_top_3grams": 0.04530744, "qsc_code_frac_chars_top_4grams": 0.02588997, "qsc_code_frac_chars_dupe_5grams": 0.12621359, "qsc_code_frac_chars_dupe_6grams": 0.12621359, "qsc_code_frac_chars_dupe_7grams": 0.08090615, "qsc_code_frac_chars_dupe_8grams": 0.08090615, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00626679, "qsc_code_frac_chars_whitespace": 0.15186029, "qsc_code_size_file_byte": 1317.0, "qsc_code_num_lines": 40.0, "qsc_code_num_chars_line_max": 81.0, "qsc_code_num_chars_line_mean": 32.925, "qsc_code_frac_chars_alphabet": 0.82363474, "qsc_code_frac_chars_comments": 0.01138952, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.12708018, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.0, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.33333333, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.33333333, "qsc_codepython_frac_lines_print": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 1, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
007gzs/meeting | server/meeting/celery.py | # encoding: utf-8
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery, signals
from django.utils.log import configure_logging
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'meeting.settings')
def configure_logger(conf=None, **kwargs):
from django.conf import settings
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
signals.worker_process_init.connect(configure_logger)
signals.beat_init.connect(configure_logger)
app = Celery('meeting')
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
@app.task(bind=True)
def _async_call(self, func, args, kwargs):
return func(*args, **kwargs)
def async_call(func, *args, **kwargs):
return _async_call.apply_async((func, args, kwargs), time_limit=3600, soft_time_limit=3600)
| 1,181 | celery | py | en | python | code | {"qsc_code_num_words": 164, "qsc_code_num_chars": 1181.0, "qsc_code_mean_word_length": 5.46341463, "qsc_code_frac_words_unique": 0.48170732, "qsc_code_frac_chars_top_2grams": 0.03571429, "qsc_code_frac_chars_top_3grams": 0.0625, "qsc_code_frac_chars_top_4grams": 0.05803571, "qsc_code_frac_chars_dupe_5grams": 0.0, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00866218, "qsc_code_frac_chars_whitespace": 0.12023709, "qsc_code_size_file_byte": 1181.0, "qsc_code_num_lines": 38.0, "qsc_code_num_chars_line_max": 96.0, "qsc_code_num_chars_line_mean": 31.07894737, "qsc_code_frac_chars_alphabet": 0.85370549, "qsc_code_frac_chars_comments": 0.29212532, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.08574879, "qsc_code_frac_chars_long_word_length": 0.02657005, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.16666667, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.27777778, "qsc_codepython_frac_lines_simplefunc": 0.1111111111111111, "qsc_codepython_score_lines_no_logic": 0.55555556, "qsc_codepython_frac_lines_print": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 1, "qsc_codepython_score_lines_no_logic": 1, "qsc_codepython_frac_lines_print": 0} |
007gzs/meeting | server/meeting/settings.py | # encoding: utf-8
from __future__ import absolute_import, unicode_literals
"""
Django settings for meeting project.
Generated by 'django-admin startproject' using Django 1.11.22.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import os
from django.conf import global_settings
from kombu import Exchange, Queue
from rest_framework import ISO_8601
from . import local_settings as ls
from .local_settings import * # NOQA
from .constance import CONSTANCE_CONFIG # NOQA
from .celery_annotations import celery_annotations_dict
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: SECRET_KEY is in local_settings
DEBUG = os.environ.get('IS_DEBUG', '1') != '0'
ALLOWED_HOSTS = ['*', ]
REDIS_CACHE_URL = 'redis://%s%s@%s:%s/%d' % (
':' if ls.REDIS_PASSWORD else '',
ls.REDIS_PASSWORD,
ls.REDIS_HOST,
ls.REDIS_PORT,
ls.REDIS_CACHE_DB)
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',
'rest_framework',
'constance',
'cool',
'apps.wechat',
'apps.meetings',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
SESSION_ENGINE = "redis_sessions.session"
SESSION_REDIS = {
'host': ls.REDIS_HOST,
'port': ls.REDIS_PORT,
'db': ls.REDIS_SESSION_DB,
'password': ls.REDIS_PASSWORD,
'prefix': 'session',
'socket_timeout': 1
}
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': [
'%s:%s' % (ls.REDIS_HOST, ls.REDIS_PORT),
],
'OPTIONS': {
'DB': ls.REDIS_CACHE_DB,
'PASSWORD': ls.REDIS_PASSWORD,
'PARSER_CLASS': 'redis.connection.HiredisParser',
'CONNECTION_POOL_CLASS': 'redis.BlockingConnectionPool',
'CONNECTION_POOL_CLASS_KWARGS': {
'max_connections': 50,
'timeout': 20,
},
'MAX_CONNECTIONS': 1000,
'PICKLE_VERSION': -1,
},
},
}
WSGI_APPLICATION = 'meeting.wsgi.application'
ASGI_APPLICATION = "meeting.routing.application"
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [
'redis://%s%s@%s:%s/%d' % (
':' if ls.REDIS_PASSWORD else '',
ls.REDIS_PASSWORD,
ls.REDIS_HOST,
ls.REDIS_PORT,
ls.REDIS_CHANNEL_DB
)
]
}
},
}
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': ls.MYSQL_DBNAME,
'USER': ls.MYSQL_USERNAME,
'PASSWORD': ls.MYSQL_PASSWORD,
'HOST': ls.MYSQL_HOST,
'PORT': ls.MYSQL_PORT,
'TEST_CHARSET': "utf8mb4",
'TEST_COLLATION': "utf8mb4_unicode_ci",
'STORAGE_ENGINE': 'INNODB',
'OPTIONS': {
'charset': 'utf8mb4',
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}
# Password validation
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'apps.wechat.backends.WechatBackend',
)
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
CONSTANCE_BACKEND = 'constance.backends.redisd.RedisBackend'
CONSTANCE_REDIS_PREFIX = 'constance:'
CONSTANCE_REDIS_CONNECTION = {
'host': ls.REDIS_HOST,
'port': ls.REDIS_PORT,
'db': ls.REDIS_CONSTANCE_DB,
'password': ls.REDIS_PASSWORD,
}
DATE_FORMAT = '%Y-%m-%d'
TIME_FORMAT = '%H:%M:%S'
DATETIME_FORMAT = DATE_FORMAT + ' ' + TIME_FORMAT
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'core.authentication.SessionAuthenticationWithOutCSRF',
),
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser',
'rest_framework.parsers.JSONParser',
'core.parsers.RawParser',
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
],
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),
'DATE_FORMAT': DATE_FORMAT,
'DATE_INPUT_FORMATS': [ISO_8601] + global_settings.DATE_INPUT_FORMATS,
'DATETIME_FORMAT': DATETIME_FORMAT,
'DATETIME_INPUT_FORMATS': [ISO_8601] + global_settings.DATETIME_INPUT_FORMATS,
'TIME_FORMAT': TIME_FORMAT,
'TIME_INPUT_FORMATS': [ISO_8601] + global_settings.TIME_INPUT_FORMATS,
}
if DEBUG:
REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'].append('rest_framework.renderers.BrowsableAPIRenderer')
EMAIL_SUBJECT_PREFIX = '[meeting]'
ROOT_URLCONF = 'meeting.urls'
DEFAULT_FILE_STORAGE = 'core.storages.EnableUrlFileSystemStorage'
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates/')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.static',
],
},
},
]
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '%(asctime)s %(process)s.%(thread)s %(levelname)s %(module)s.%(funcName)s %(message)s',
'datefmt': "%y/%m/%d %H:%M:%S",
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'include_html': True,
'formatter': 'standard'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'standard',
},
},
'loggers': {
'daphne': {
'handlers': ['console', ],
'level': 'DEBUG',
'propagate': True
},
'django': {
'handlers': ['console', ],
'level': 'INFO',
'propagate': True
},
'django.db': {
'handlers': ['console', ],
'level': 'DEBUG',
'propagate': False,
},
'django.request': {
'handlers': ['console', 'mail_admins', ],
'level': 'ERROR',
'propagate': False,
},
'exception': {
'handlers': ['console', 'mail_admins'],
'level': 'ERROR',
'propagate': False
},
'': {
'handlers': ['console', ],
'level': 'DEBUG',
'propagate': True
}
},
'root': {
'handlers': ['console', ],
'level': 'DEBUG',
'propagate': True
}
}
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'upload')
STATIC_ROOT = os.path.join(BASE_DIR, 'www_static')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/'),
)
# celery settings
CELERY_BROKER_URL = 'redis://%s%s@%s:%s/%d' % (
':' if ls.REDIS_PASSWORD else '',
ls.REDIS_PASSWORD,
ls.REDIS_HOST,
ls.REDIS_PORT,
ls.REDIS_CELERY_DB)
CELERY_RESULT_BACKEND = CELERY_BROKER_URL
CELERY_WORKER_HIJACK_ROOT_LOGGER = False
# 任务执行最长时间20分钟
CELERY_TASK_SOFT_TIME_LIMIT = 1200
CELERY_TASK_TIME_LIMIT = 1200
CELERY_TIMEZONE = TIME_ZONE
CELERY_TASK_DEFAULT_QUEUE = 'default'
CELERY_TASK_SERIALIZER = 'pickle'
CELERY_RESULT_SERIALIZER = 'pickle'
CELERY_ACCEPT_CONTENT = ['pickle', 'json']
# 定义执行队列
CELERY_TASK_QUEUES = (
Queue('default', Exchange('default'), routing_key='default'),
Queue('crontab', Exchange('crontab'), routing_key='crontab'),
Queue('async', Exchange('async'), routing_key='async')
)
# 制定特定任务路由到特定执行队列
CELERY_TASK_ROUTES = {
'meeting.celery._async_call': {'queue': 'async', 'routing_key': 'async'},
}
CELERY_TASK_ANNOTATIONS = {'*': celery_annotations_dict}
DJANGO_COOL = {
'API_WS_REQ_ID_NAME': 'reqid',
'API_EXCEPTION_DEFAULT_STATUS_CODE': 200,
'API_PARAM_ERROR_STATUS_CODE': 200,
'API_SYSTEM_ERROR_STATUS_CODE': 200,
'API_ERROR_CODES': (
('ERR_WECHAT_LOGIN', (10001, '需要登录')),
('ERR_MEETING_ROOM_TIMEOVER', (20001, '时间已过')),
('ERR_MEETING_ROOM_INUSE', (20002, '时间冲突')),
('ERR_MEETING_ROOM_NOT_FOUND', (20003, '会议室未找到')),
('ERR_MEETING_NOT_FOUND', (20004, '会议未找到')),
('ERR_MEETING_FINISHED', (20005, '会议已结束')),
)
}
| 10,217 | settings | py | en | python | code | {"qsc_code_num_words": 1051, "qsc_code_num_chars": 10217.0, "qsc_code_mean_word_length": 5.80780209, "qsc_code_frac_words_unique": 0.31969553, "qsc_code_frac_chars_top_2grams": 0.0309633, "qsc_code_frac_chars_top_3grams": 0.02211664, "qsc_code_frac_chars_top_4grams": 0.02866972, "qsc_code_frac_chars_dupe_5grams": 0.22083879, "qsc_code_frac_chars_dupe_6grams": 0.18250328, "qsc_code_frac_chars_dupe_7grams": 0.11156619, "qsc_code_frac_chars_dupe_8grams": 0.08682831, "qsc_code_frac_chars_dupe_9grams": 0.05062254, "qsc_code_frac_chars_dupe_10grams": 0.05062254, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01223865, "qsc_code_frac_chars_whitespace": 0.23225996, "qsc_code_size_file_byte": 10217.0, "qsc_code_num_lines": 375.0, "qsc_code_num_chars_line_max": 110.0, "qsc_code_num_chars_line_mean": 27.24533333, "qsc_code_frac_chars_alphabet": 0.76593575, "qsc_code_frac_chars_comments": 0.067143, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.16083916, "qsc_code_cate_autogen": 1.0, "qsc_code_frac_lines_long_string": 0.0034965, "qsc_code_frac_chars_string_length": 0.3948913, "qsc_code_frac_chars_long_word_length": 0.2398913, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.0, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.05244755, "qsc_codepython_frac_lines_import": 0.03146853, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.03146853, "qsc_codepython_frac_lines_print": 0.0} | 0 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 1, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 1, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
007gzs/meeting | server/core/utils.py | # encoding: utf-8
from __future__ import absolute_import, unicode_literals
import logging
import os
import tempfile
import hashlib
from django import forms
from django.db import models
from django.contrib.auth import models as auth_models
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes
from rest_framework import fields
from rest_framework.response import Response
from cool import model, admin
from cool.views import CoolBFFAPIView, serializer, ErrorCode, CoolAPIException, ResponseData, get_api_doc
from . import constants, renderers
exception_logging = logging.getLogger('exception')
class DeletedManager(models.Manager):
def get_queryset(self):
queryset = super(DeletedManager, self).get_queryset()
return queryset.filter(delete_status=constants.DeleteCode.NORMAL.code)
def get_all_queryset(self):
return super(DeletedManager, self).get_queryset()
class BaseModel(model.BaseModel):
id = models.BigAutoField('主键ID', primary_key=True)
create_time = models.DateTimeField('创建时间', auto_now_add=True, db_index=True, editable=False)
modify_time = models.DateTimeField('修改时间', auto_now=True, db_index=True, editable=False)
delete_status = models.BooleanField('删除状态', choices=constants.DeleteCode.get_choices_list(),
default=constants.DeleteCode.NORMAL.code, null=False, db_index=True)
remark = models.TextField('备注说明', null=True, blank=True, default='')
default_manager = models.Manager()
objects = DeletedManager()
def __str__(self):
if hasattr(self, 'name'):
return self.name
else:
return super(BaseModel, self).__str__()
class Meta:
abstract = True
@classmethod
def ex_search_fields(cls):
ret = set()
for field in cls._meta.fields:
if field.name == 'name' and isinstance(field, models.CharField):
ret.add(field.name)
return ret
@classmethod
def get_search_fields(cls):
ret = super(BaseModel, cls).get_search_fields()
return ret.union(cls.ex_search_fields())
def delete(self, using=None, keep_parents=False):
if self.delete_status == constants.DeleteCode.DELETED.code:
return
self.delete_status = constants.DeleteCode.DELETED.code
return self.save(using=using, force_update=True, update_fields=['delete_status', ])
# return super(BaseModel, self).delete(using=using, keep_parents=keep_parents)
def un_delete(self, using=None):
if self.delete_status == constants.DeleteCode.NORMAL.code:
return
self.delete_status = constants.DeleteCode.NORMAL.code
return self.save(using=using, force_update=True, update_fields=['delete_status', ])
class ChangeLogBase(BaseModel):
status = models.IntegerField('状态', choices=constants.ChangeLogStatusCode.get_choices_list(),
default=constants.ChangeLogStatusCode.PROCESSING.code, null=False, db_index=True)
reason = models.CharField('原因', max_length=255, null=False, blank=True, default='')
reason_type = models.CharField('关联表类型', max_length=32, null=False, blank=True, default='')
reason_id = models.BigIntegerField('关联表ID', null=False, blank=True, default=0)
change_value = models.DecimalField('变化数值', max_digits=12, decimal_places=2,
null=False, default=0, help_text='正加负减')
class Meta:
index_together = ('reason_id', 'reason_type')
abstract = True
class ForeignKey(model.ForeignKey):
def __init__(self, to, on_delete=models.DO_NOTHING, **kwargs):
kwargs.setdefault('db_constraint', False)
super().__init__(to, on_delete, **kwargs)
class BaseAdmin(admin.BaseModelAdmin):
extend_normal_fields = True
exclude_list_display = ['remark', 'modify_time']
list_display = []
heads = ['id']
tails = ['create_time', 'delete_status', 'remark']
readonly_fields = ['create_time', 'modify_time']
change_view_readonly_fields = []
editable_fields = forms.ALL_FIELDS
list_filter = ['create_time', ]
limits = None
advanced_filter_fields = []
def __init__(self, *args, **kwargs):
super(BaseAdmin, self).__init__(*args, **kwargs)
def formfield_for_manytomany(self, db_field, request, **kwargs):
db_field.remote_field.through._meta.auto_created = True
return super(BaseAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
def delete_queryset(self, request, queryset):
# 单独调用每个model的delete,可以同时清空缓存
for obj in queryset:
self.delete_model(request, obj)
def handle_options(dismiss_create_time=False, **options):
if 'list_filter' in options and not dismiss_create_time and 'create_time' not in options['list_filter']:
options['list_filter'] = ['create_time', ] + list(options['list_filter'])
return options
def site_register(model_or_iterable, admin_class=BaseAdmin, site=None, dismiss_create_time=False, **options):
options = handle_options(dismiss_create_time=dismiss_create_time, **options)
admin.site_register(model_or_iterable, admin_class, site, **options)
def admin_register(func=None, *, admin_class=BaseAdmin, site=None, dismiss_create_time=False, **options):
options = handle_options(dismiss_create_time=dismiss_create_time, **options)
return admin.admin_register(func=func, admin_class=admin_class, site=site, **options)
class DateField(fields.DateField):
def validate_empty_values(self, data):
(is_empty_value, data) = super().validate_empty_values(data)
if not is_empty_value and data == '':
is_empty_value = True
data = self.get_default()
return is_empty_value, data
class APIBase(CoolBFFAPIView):
def get_context(self, request, *args, **kwargs):
raise NotImplementedError
@staticmethod
def get_req_body(request):
return request.body if request.method == 'POST' else None
@staticmethod
def get_appid(request):
host = request.get_host()
if not host.startswith("wx"):
return None
return host[:host.find('.')]
def log_exception(self, request, exc, context):
super().log_exception(request, exc, context)
exception_logging.exception(str(exc), exc_info=exc, extra={'request': request})
class Meta:
path = '/'
param_fields = (
('channel', fields.CharField(label='渠道码', required=False)),
('version', fields.CharField(label='版本号', required=False)),
)
class AdminApi(APIBase):
need_superuser = True
def get_context(self, request, *args, **kwargs):
raise NotImplementedError
def check_api_permissions(self, request, *args, **kwargs):
if not isinstance(request.user, auth_models.AbstractUser):
raise CoolAPIException(ErrorCode.ERR_AUTH_NOLOGIN)
if not request.user.is_active or not request.user.is_staff:
raise CoolAPIException(ErrorCode.ERR_AUTH_PERMISSION)
if self.need_superuser:
if not request.user.is_superuser:
raise CoolAPIException(ErrorCode.ERR_AUTH_PERMISSION)
class Meta:
path = '/'
class TextApiView(APIBase):
def __init__(self, *args, **kwargs):
super(TextApiView, self).__init__(*args, **kwargs)
self.renderer_classes = (renderers.PlainTextRenderer, )
def get_response(self, context):
status_code = 200
if isinstance(context, HttpResponse):
return context
elif isinstance(context, ResponseData):
status_code = context.status_code
if context.code != ErrorCode.SUCCESS:
context = 'error: %d %s' % (context.code, context.message)
else:
context = context.data
return Response(context, status=status_code)
def get_context(self, request, *args, **kwargs):
raise NotImplementedError
class Meta:
path = '/'
class HtmlApiView(APIBase):
error_template = 'error.html'
def __init__(self, *args, **kwargs):
super(HtmlApiView, self).__init__(*args, **kwargs)
self.renderer_classes = (renderers.PlainHtmlRenderer, )
def get_context(self, request, *args, **kwargs):
raise NotImplementedError
def get_response(self, context):
status_code = 200
if isinstance(context, HttpResponse):
return context
elif isinstance(context, ResponseData):
status_code = context.status_code
if context.code != ErrorCode.SUCCESS:
if self.error_template:
context = render_to_string(self.request, self.error_template, context)
else:
context = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>出错了</title>
</head>
<body>
{message}
</body>
</html>
""".format(message=context.message)
else:
context = context.data
return Response(context, status=status_code)
class Meta:
path = '/'
class BaseSerializer(serializer.BaseSerializer):
pass
def get_temp_file(content):
content = force_bytes(content)
m = hashlib.md5()
m.update(content)
filename = "%s.tmp" % m.hexdigest()
filename = os.path.join(tempfile.gettempdir(), filename)
if not os.path.exists(filename):
with open(filename, 'wb') as f:
f.write(content)
return filename
def get_api_js(
request,
*args,
base_view=APIBase,
exclude_params=(),
exclude_base_view_params=True,
exclude_views=(),
**kwargs
):
return HttpResponse(get_api_doc(
request=request,
template_name='cool/views/api.js',
base_view=base_view,
exclude_params=exclude_params,
exclude_base_view_params=exclude_base_view_params,
exclude_views=exclude_views
), 'application/javascript; charset=utf-8', 200)
| 10,126 | utils | py | en | python | code | {"qsc_code_num_words": 1177, "qsc_code_num_chars": 10126.0, "qsc_code_mean_word_length": 5.56839422, "qsc_code_frac_words_unique": 0.23704333, "qsc_code_frac_chars_top_2grams": 0.021361, "qsc_code_frac_chars_top_3grams": 0.02075069, "qsc_code_frac_chars_top_4grams": 0.02364968, "qsc_code_frac_chars_dupe_5grams": 0.3326213, "qsc_code_frac_chars_dupe_6grams": 0.29173024, "qsc_code_frac_chars_dupe_7grams": 0.2186451, "qsc_code_frac_chars_dupe_8grams": 0.20888007, "qsc_code_frac_chars_dupe_9grams": 0.19484284, "qsc_code_frac_chars_dupe_10grams": 0.14876411, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00290808, "qsc_code_frac_chars_whitespace": 0.21894134, "qsc_code_size_file_byte": 10126.0, "qsc_code_num_lines": 303.0, "qsc_code_num_chars_line_max": 115.0, "qsc_code_num_chars_line_mean": 33.41914191, "qsc_code_frac_chars_alphabet": 0.82576811, "qsc_code_frac_chars_comments": 0.01185068, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.2489083, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.05238952, "qsc_code_frac_chars_long_word_length": 0.00229954, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.12663755, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.00436681, "qsc_codepython_frac_lines_import": 0.069869, "qsc_codepython_frac_lines_simplefunc": 0.013100436681222707, "qsc_codepython_score_lines_no_logic": 0.48034934, "qsc_codepython_frac_lines_print": 0.0} | 1 | {"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.