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
000haoji/deep-student
src/components/archived/BackendTest.tsx
import React, { useState, useEffect } from 'react'; import { invoke } from '@tauri-apps/api/core'; interface TestResult { name: string; status: 'pending' | 'success' | 'error'; message: string; duration?: number; } interface ApiTest { name: string; command: string; params?: any; description: string; } const BackendTest: React.FC = () => { const [testResults, setTestResults] = useState<TestResult[]>([]); const [isRunning, setIsRunning] = useState(false); const [isTauriAvailable, setIsTauriAvailable] = useState(false); const [testContext, setTestContext] = useState<{ tempId?: string; mistakeId?: string; reviewId?: string; }>({}); // 定义所有API测试 const apiTests: ApiTest[] = [ // 基础API测试 { name: '获取支持的科目', command: 'get_supported_subjects', description: '测试获取系统支持的科目列表' }, { name: '获取统计信息', command: 'get_statistics', description: '测试获取错题统计数据' }, // 设置管理API { name: '保存设置', command: 'save_setting', params: { key: 'test_key', value: 'test_value_' + Date.now() }, description: '测试保存设置功能' }, { name: '获取设置', command: 'get_setting', params: { key: 'test_key' }, description: '测试获取设置功能' }, { name: '测试API连接', command: 'test_api_connection', params: { apiKey: 'test-key', apiBase: 'https://api.openai.com/v1' }, description: '测试外部AI API连接' }, // 错题库管理API { name: '获取错题列表(无筛选)', command: 'get_mistakes', params: {}, description: '测试获取错题列表(无筛选条件)' }, { name: '获取错题列表(按科目筛选)', command: 'get_mistakes', params: { subject: '数学' }, description: '测试按科目筛选错题列表' }, { name: '获取错题详情', command: 'get_mistake_details', params: { id: 'test-mistake-id' }, description: '测试获取单个错题的详细信息' }, { name: '更新错题', command: 'update_mistake', params: { mistake: { id: 'test-mistake-id', subject: '数学', created_at: new Date().toISOString(), updated_at: new Date().toISOString(), question_images: [], analysis_images: [], user_question: '更新后的问题', ocr_text: '更新后的OCR文本', tags: ['测试标签'], mistake_type: '计算题', status: 'completed', chat_history: [] } }, description: '测试更新错题信息' }, { name: '删除错题', command: 'delete_mistake', params: { id: 'test-mistake-id' }, description: '测试删除错题及关联文件' }, // 分析相关API { name: '分析新错题', command: 'analyze_new_mistake', params: { request: { subject: '数学', question_image_files: ['data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAv/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCdABmX/9k='], analysis_image_files: [], user_question: '这是一个测试问题' } }, description: '测试分析新错题功能' }, { name: '继续对话(临时会话)', command: 'continue_chat', params: { request: { temp_id: 'test-temp-id', chat_history: [ { role: 'user', content: '请详细解释一下这道题', timestamp: new Date().toISOString() } ] } }, description: '测试在分析过程中继续对话' }, { name: '保存分析结果到错题库', command: 'save_mistake_from_analysis', params: { request: { temp_id: 'test-temp-id', final_chat_history: [ { role: 'assistant', content: '这是AI的回答', timestamp: new Date().toISOString() } ] } }, description: '测试将分析结果保存到错题库' }, { name: '继续错题对话', command: 'continue_mistake_chat', params: { mistakeId: 'test-mistake-id', chatHistory: [ { role: 'user', content: '我还有疑问', timestamp: new Date().toISOString() } ] }, description: '测试在错题详情页继续对话' }, // 回顾分析API (流式版本) { name: '回顾分析', command: 'analyze_review_session_stream', params: { subject: '数学', mistake_ids: ['mistake-1', 'mistake-2', 'mistake-3'] }, description: '测试对多个错题进行关联分析(流式)' }, // 文件管理API { name: '获取图片(base64)', command: 'get_image_as_base64', params: { relativePath: 'test-image.jpg' }, description: '测试读取图片文件为base64格式' }, { name: '清理孤立图片', command: 'cleanup_orphaned_images', description: '测试清理孤立图片文件' } ]; useEffect(() => { // 检查Tauri环境 - 尝试多种检测方式 const checkTauriEnvironment = async () => { try { // 方法1: 检查全局变量 if (typeof (window as any).__TAURI__ !== 'undefined') { setIsTauriAvailable(true); return; } // 方法2: 检查Tauri API if (typeof (window as any).__TAURI_INTERNALS__ !== 'undefined') { setIsTauriAvailable(true); return; } // 方法3: 尝试调用一个简单的Tauri命令 await invoke('get_supported_subjects'); setIsTauriAvailable(true); } catch (error) { console.log('Tauri环境检测失败:', error); setIsTauriAvailable(false); } }; checkTauriEnvironment(); }, []); const runSingleTest = async (test: ApiTest): Promise<TestResult> => { const startTime = Date.now(); try { console.log(`开始测试: ${test.name}`); // 动态替换参数中的测试上下文 let params = test.params || {}; if (params) { params = JSON.parse(JSON.stringify(params)); // 深拷贝 // 替换temp_id if (params.request?.temp_id === 'test-temp-id' && testContext.tempId) { params.request.temp_id = testContext.tempId; } // 替换mistake_id if (params.mistakeId === 'test-mistake-id' && testContext.mistakeId) { params.mistakeId = testContext.mistakeId; } if (params.id === 'test-mistake-id' && testContext.mistakeId) { params.id = testContext.mistakeId; } if (params.mistake?.id === 'test-mistake-id' && testContext.mistakeId) { params.mistake.id = testContext.mistakeId; } // 替换review_id if (params.review_id === 'test-review-id' && testContext.reviewId) { params.review_id = testContext.reviewId; } } const result = await invoke(test.command, params); const duration = Date.now() - startTime; console.log(`测试成功: ${test.name}`, result); // 更新测试上下文 if (test.command === 'analyze_new_mistake' && (result as any)?.temp_id) { setTestContext(prev => ({ ...prev, tempId: (result as any).temp_id })); } if (test.command === 'save_mistake_from_analysis' && (result as any)?.mistake_item?.id) { setTestContext(prev => ({ ...prev, mistakeId: (result as any).mistake_item.id })); } if (test.command === 'analyze_review_session' && (result as any)?.review_id) { setTestContext(prev => ({ ...prev, reviewId: (result as any).review_id })); } return { name: test.name, status: 'success', message: `成功 - 响应: ${JSON.stringify(result).substring(0, 100)}${JSON.stringify(result).length > 100 ? '...' : ''}`, duration }; } catch (error: any) { const duration = Date.now() - startTime; console.error(`测试失败: ${test.name}`, error); return { name: test.name, status: 'error', message: `失败 - ${error.message || error}`, duration }; } }; const runAllTests = async () => { if (!isTauriAvailable) { alert('Tauri环境不可用,请在Tauri应用中运行测试'); return; } setIsRunning(true); setTestResults([]); for (const test of apiTests) { // 添加pending状态 setTestResults(prev => [...prev, { name: test.name, status: 'pending', message: '测试中...' }]); const result = await runSingleTest(test); // 更新结果 setTestResults(prev => prev.map(r => r.name === test.name ? result : r) ); // 短暂延迟,避免过快的请求 await new Promise(resolve => setTimeout(resolve, 500)); } setIsRunning(false); }; const runSingleTestById = async (testIndex: number) => { if (!isTauriAvailable) { alert('Tauri环境不可用,请在Tauri应用中运行测试'); return; } const test = apiTests[testIndex]; // 更新或添加pending状态 setTestResults(prev => { const existing = prev.find(r => r.name === test.name); if (existing) { return prev.map(r => r.name === test.name ? { ...r, status: 'pending' as const, message: '测试中...' } : r ); } else { return [...prev, { name: test.name, status: 'pending' as const, message: '测试中...' }]; } }); const result = await runSingleTest(test); // 更新结果 setTestResults(prev => prev.map(r => r.name === test.name ? result : r) ); }; const clearResults = () => { setTestResults([]); setTestContext({}); }; const getStatusIcon = (status: TestResult['status']) => { switch (status) { case 'pending': return '⏳'; case 'success': return '✅'; case 'error': return '❌'; default: return '⚪'; } }; const getStatusColor = (status: TestResult['status']) => { switch (status) { case 'pending': return '#fbbf24'; case 'success': return '#10b981'; case 'error': return '#ef4444'; default: return '#6b7280'; } }; // 渲染测试卡片的函数 const renderTestCard = (test: ApiTest, index: number, result?: TestResult) => { return ( <div key={test.name} style={{ border: '1px solid #e5e7eb', borderRadius: '8px', padding: '15px', backgroundColor: '#f9fafb' }} > <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}> <div style={{ flex: 1 }}> <h4 style={{ margin: '0 0 5px 0', color: '#1f2937' }}> {test.name} </h4> <p style={{ margin: '0 0 10px 0', fontSize: '14px', color: '#6b7280' }}> {test.description} </p> <div style={{ fontSize: '12px', color: '#9ca3af' }}> 命令: <code>{test.command}</code> {test.params && ( <div>参数: <code>{JSON.stringify(test.params)}</code></div> )} </div> </div> <div style={{ marginLeft: '15px', textAlign: 'right' }}> <button onClick={() => runSingleTestById(index)} disabled={isRunning || !isTauriAvailable} style={{ padding: '5px 10px', backgroundColor: '#10b981', color: 'white', border: 'none', borderRadius: '4px', cursor: isRunning ? 'not-allowed' : 'pointer', fontSize: '12px' }} > 单独测试 </button> </div> </div> {result && ( <div style={{ marginTop: '10px', padding: '10px', backgroundColor: 'white', borderRadius: '4px', border: `1px solid ${getStatusColor(result.status)}` }}> <div style={{ display: 'flex', alignItems: 'center', marginBottom: '5px' }}> <span style={{ marginRight: '8px', fontSize: '16px' }}> {getStatusIcon(result.status)} </span> <span style={{ fontWeight: 'bold', color: getStatusColor(result.status) }}> {result.status === 'pending' ? '测试中' : result.status === 'success' ? '成功' : '失败'} </span> {result.duration && ( <span style={{ marginLeft: '10px', fontSize: '12px', color: '#6b7280' }}> ({result.duration}ms) </span> )} </div> <div style={{ fontSize: '14px', color: '#374151' }}> {result.message} </div> </div> )} </div> ); }; return ( <div style={{ padding: '20px', maxWidth: '1000px', margin: '0 auto' }}> <h2>🔧 后端API测试</h2> {/* 环境状态 */} <div style={{ marginBottom: '20px', padding: '15px', backgroundColor: isTauriAvailable ? '#dcfce7' : '#fef2f2', borderRadius: '8px', border: `1px solid ${isTauriAvailable ? '#16a34a' : '#dc2626'}` }}> <h3>环境状态</h3> <p> Tauri环境: {isTauriAvailable ? '✅ 可用' : '❌ 不可用'} </p> {!isTauriAvailable && ( <p style={{ color: '#dc2626', fontSize: '14px' }}> 请在Tauri桌面应用中运行此测试,浏览器环境无法调用后端API </p> )} </div> {/* 测试上下文 */} {(testContext.tempId || testContext.mistakeId || testContext.reviewId) && ( <div style={{ marginBottom: '20px', padding: '15px', backgroundColor: '#f0f9ff', borderRadius: '8px', border: '1px solid #0ea5e9' }}> <h3>测试上下文</h3> <div style={{ fontSize: '14px', fontFamily: 'monospace' }}> {testContext.tempId && <div>临时会话ID: {testContext.tempId}</div>} {testContext.mistakeId && <div>错题ID: {testContext.mistakeId}</div>} {testContext.reviewId && <div>回顾ID: {testContext.reviewId}</div>} </div> <p style={{ fontSize: '12px', color: '#6b7280', marginTop: '8px' }}> 这些ID会自动用于相关的API测试中 </p> </div> )} {/* 控制按钮 */} <div style={{ marginBottom: '20px' }}> <button onClick={runAllTests} disabled={isRunning || !isTauriAvailable} style={{ padding: '10px 20px', marginRight: '10px', backgroundColor: isRunning ? '#9ca3af' : '#3b82f6', color: 'white', border: 'none', borderRadius: '6px', cursor: isRunning ? 'not-allowed' : 'pointer' }} > {isRunning ? '测试进行中...' : '运行所有测试'} </button> <button onClick={clearResults} disabled={isRunning} style={{ padding: '10px 20px', backgroundColor: '#6b7280', color: 'white', border: 'none', borderRadius: '6px', cursor: isRunning ? 'not-allowed' : 'pointer' }} > 清空结果 </button> {(testContext.tempId || testContext.mistakeId || testContext.reviewId) && ( <button onClick={() => setTestContext({})} disabled={isRunning} style={{ padding: '10px 20px', marginLeft: '10px', backgroundColor: '#f59e0b', color: 'white', border: 'none', borderRadius: '6px', cursor: isRunning ? 'not-allowed' : 'pointer' }} > 清空上下文 </button> )} </div> {/* API测试列表 */} <div style={{ display: 'grid', gap: '20px' }}> {/* 基础API测试 */} <div> <h3 style={{ marginBottom: '15px', color: '#1f2937' }}>📊 基础API测试</h3> <div style={{ display: 'grid', gap: '15px' }}> {apiTests.slice(0, 2).map((test, index) => { const result = testResults.find(r => r.name === test.name); return renderTestCard(test, index, result); })} </div> </div> {/* 设置管理API */} <div> <h3 style={{ marginBottom: '15px', color: '#1f2937' }}>⚙️ 设置管理API</h3> <div style={{ display: 'grid', gap: '15px' }}> {apiTests.slice(2, 5).map((test, index) => { const result = testResults.find(r => r.name === test.name); return renderTestCard(test, index + 2, result); })} </div> </div> {/* 错题库管理API */} <div> <h3 style={{ marginBottom: '15px', color: '#1f2937' }}>📚 错题库管理API</h3> <div style={{ display: 'grid', gap: '15px' }}> {apiTests.slice(5, 10).map((test, index) => { const result = testResults.find(r => r.name === test.name); return renderTestCard(test, index + 5, result); })} </div> </div> {/* 分析相关API */} <div> <h3 style={{ marginBottom: '15px', color: '#1f2937' }}>🔍 分析相关API</h3> <div style={{ display: 'grid', gap: '15px' }}> {apiTests.slice(10, 15).map((test, index) => { const result = testResults.find(r => r.name === test.name); return renderTestCard(test, index + 10, result); })} </div> </div> {/* 回顾分析API */} <div> <h3 style={{ marginBottom: '15px', color: '#1f2937' }}>📈 回顾分析API</h3> <div style={{ display: 'grid', gap: '15px' }}> {apiTests.slice(15, 16).map((test, index) => { const result = testResults.find(r => r.name === test.name); return renderTestCard(test, index + 15, result); })} </div> </div> {/* 文件管理API */} <div> <h3 style={{ marginBottom: '15px', color: '#1f2937' }}>📁 文件管理API</h3> <div style={{ display: 'grid', gap: '15px' }}> {apiTests.slice(16).map((test, index) => { const result = testResults.find(r => r.name === test.name); return renderTestCard(test, index + 16, result); })} </div> </div> </div> {/* 测试统计 */} {testResults.length > 0 && ( <div style={{ marginTop: '20px', padding: '15px', backgroundColor: '#f3f4f6', borderRadius: '8px' }}> <h3>测试统计</h3> <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))', gap: '10px' }}> <div> 总数: <strong>{testResults.length}</strong> </div> <div style={{ color: '#10b981' }}> 成功: <strong>{testResults.filter(r => r.status === 'success').length}</strong> </div> <div style={{ color: '#ef4444' }}> 失败: <strong>{testResults.filter(r => r.status === 'error').length}</strong> </div> <div style={{ color: '#fbbf24' }}> 进行中: <strong>{testResults.filter(r => r.status === 'pending').length}</strong> </div> </div> </div> )} </div> ); }; export default BackendTest;
19,440
BackendTest
tsx
en
tsx
code
{"qsc_code_num_words": 1598, "qsc_code_num_chars": 19440.0, "qsc_code_mean_word_length": 5.94993742, "qsc_code_frac_words_unique": 0.24030038, "qsc_code_frac_chars_top_2grams": 0.02019352, "qsc_code_frac_chars_top_3grams": 0.01766933, "qsc_code_frac_chars_top_4grams": 0.01051746, "qsc_code_frac_chars_dupe_5grams": 0.34444678, "qsc_code_frac_chars_dupe_6grams": 0.27671435, "qsc_code_frac_chars_dupe_7grams": 0.18268826, "qsc_code_frac_chars_dupe_8grams": 0.12883887, "qsc_code_frac_chars_dupe_9grams": 0.11811106, "qsc_code_frac_chars_dupe_10grams": 0.09223812, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0267963, "qsc_code_frac_chars_whitespace": 0.3492284, "qsc_code_size_file_byte": 19440.0, "qsc_code_num_lines": 666.0, "qsc_code_num_chars_line_max": 445.0, "qsc_code_num_chars_line_mean": 29.18918919, "qsc_code_frac_chars_alphabet": 0.72365821, "qsc_code_frac_chars_comments": 0.02253086, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.39115646, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00170068, "qsc_code_frac_chars_string_length": 0.13145985, "qsc_code_frac_chars_long_word_length": 0.03410167, "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/archived/README.md
# 归档组件说明 本目录包含被统一组件 `UnifiedAnalysisView` 替换的原有组件备份。 ## 归档时间 2024年6月5日 ## 归档原因 为了提高代码复用性和可维护性,将三个功能相似的分析组件统一为一个通用组件,并新增了图片追问功能。 ## 归档的组件 ### 1. MistakeDetail.tsx - **原用途**: 单条错题的详细分析和追问 - **替换为**: `UnifiedAnalysisView` 组件,使用 `analysisType="singleMistake"` - **主要功能**: - 错题信息编辑 - 图片查看 - AI分析对话 - 错题删除 ### 2. BatchTaskDetailView.tsx - **原用途**: 批量分析任务中单个条目的详情展示和追问 - **替换为**: `UnifiedAnalysisView` 组件,使用 `analysisType="batchDetail"` - **主要功能**: - 批量任务状态展示 - OCR结果显示 - AI解答对话 - 保存到错题库 ### 3. ReviewAnalysisDetailView.tsx - **原用途**: 回顾分析会话的详情展示和追问 - **替换为**: `UnifiedAnalysisView` 组件,使用 `analysisType="reviewDetail"` - **主要功能**: - 回顾会话信息展示 - 自动开始分析 - AI分析对话 - 保存到分析库 ## 新增功能 统一组件新增了以下功能: - 图片追问:用户可以上传图片与文字一同发送给AI - 多模态内容渲染:支持文本和图片混合显示 - 统一的流式处理逻辑 - 更好的错误处理和状态管理 ## 恢复说明 原始组件文件已通过git提交保存在版本控制中。如果需要恢复,可以: 1. 使用 `git checkout` 恢复特定版本的文件 2. 恢复相应的导入语句 3. 恢复原有的组件使用方式 **注意**: 为避免编译错误,tsx文件已从此目录移除,但可以通过git历史恢复。 ## 兼容性说明 - 新的统一组件完全兼容原有的功能 - API调用方式保持不变 - 数据结构保持向后兼容 - 原有的样式类名大部分保留 ## 迁移映射 | 原组件属性 | 统一组件属性 | 备注 | |----------|------------|------| | `mistake` | `initialData` | 数据对象 | | `taskData` | `initialData` | 数据对象 | | `sessionData` | `initialData` | 数据对象 | | `onBack` | `onBack` | 仅 singleMistake | | `onUpdate` | `onMistakeUpdate` | 仅 singleMistake | | `onDelete` | `onMistakeDelete` | 仅 singleMistake | | `onSaveRequested` | `onRequestSaveBatchItemAsMistake` 或 `onSaveReviewSession` | 根据类型 | | `onChatHistoryUpdated` | `onBatchChatUpdate` 或 `onReviewChatUpdate` | 根据类型 | | `isPageView` | `isPageView` | 保持不变 | ## 注意事项 - 这些组件的备份仅用于紧急恢复,不建议在新开发中使用 - 如有问题,请优先修复统一组件而不是回退到旧组件 - 统一组件的功能会持续迭代和优化
1,627
README
md
zh
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 14.0, "qsc_doc_num_words": 368, "qsc_doc_num_chars": 1627.0, "qsc_doc_num_lines": 78.0, "qsc_doc_mean_word_length": 3.0326087, "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.5326087, "qsc_doc_entropy_unigram": 4.93999451, "qsc_doc_frac_words_all_caps": 0.00998336, "qsc_doc_frac_lines_dupe_lines": 0.078125, "qsc_doc_frac_chars_dupe_lines": 0.03217334, "qsc_doc_frac_chars_top_2grams": 0.02150538, "qsc_doc_frac_chars_top_3grams": 0.01612903, "qsc_doc_frac_chars_top_4grams": 0.01612903, "qsc_doc_frac_chars_dupe_5grams": 0.11738351, "qsc_doc_frac_chars_dupe_6grams": 0.11738351, "qsc_doc_frac_chars_dupe_7grams": 0.11738351, "qsc_doc_frac_chars_dupe_8grams": 0.11738351, "qsc_doc_frac_chars_dupe_9grams": 0.08064516, "qsc_doc_frac_chars_dupe_10grams": 0.08064516, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 17.71264368, "qsc_doc_frac_chars_hyperlink_html_tag": 0.0, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.00864553, "qsc_doc_frac_chars_whitespace": 0.14689613, "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/components/shared/UnifiedSubjectSelector.css
.unified-subject-selector { position: relative; display: inline-block; } /* 现代圆角下拉框样式 */ .unified-subject-selector .custom-select { position: relative; width: 100%; } .unified-subject-selector .select-selected { background-color: #ffffff; border-radius: 12px; border: 1px solid #e0e0e0; padding: 12px 16px; cursor: pointer; display: flex; justify-content: space-between; align-items: center; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); box-shadow: 0 2px 8px rgba(0,0,0,0.08); min-width: 120px; position: relative; z-index: 10; } .unified-subject-selector .select-selected:hover { border-color: #c7c7c7; box-shadow: 0 3px 10px rgba(0,0,0,0.12); } .unified-subject-selector .select-selected:focus { background-color: #edf2f7; color: #4a5568; outline: none; } .unified-subject-selector .select-selected.disabled { background-color: #f7fafc; color: #a0aec0; cursor: not-allowed; opacity: 0.6; } .unified-subject-selector .selected-value { color: #1a1a1a; font-size: 14px; font-weight: 500; letter-spacing: 0.2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; pointer-events: none; } .unified-subject-selector .select-arrow { color: #666; font-size: 16px; transform: rotate(0deg); transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); flex-shrink: 0; margin-left: 8px; pointer-events: none; } .unified-subject-selector .select-items { position: absolute; top: 100%; left: 0; right: 0; background-color: #fff; border-radius: 12px; border: 1px solid #e0e0e0; margin-top: 8px; max-height: 0; overflow: hidden; transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.2s ease; opacity: 0; box-shadow: 0 6px 16px rgba(0,0,0,0.12); z-index: 9999; visibility: hidden; pointer-events: auto; -webkit-overflow-scrolling: touch; } .unified-subject-selector .select-items.show { max-height: 500px; opacity: 1; visibility: visible; pointer-events: auto; overflow-y: auto; } /* 自定义滚动条样式 */ .unified-subject-selector .select-items::-webkit-scrollbar { width: 6px; } .unified-subject-selector .select-items::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 3px; } .unified-subject-selector .select-items::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 3px; } .unified-subject-selector .select-items::-webkit-scrollbar-thumb:hover { background: #a8a8a8; } .unified-subject-selector .select-item { padding: 12px 16px; cursor: pointer; color: #333; font-size: 14px; font-weight: 400; transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); border: none; background: none; width: 100%; text-align: left; user-select: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; white-space: nowrap; min-height: 44px; display: flex; align-items: center; } .unified-subject-selector .select-item:hover { background-color: #f7f7f7; } .unified-subject-selector .select-item.selected { background-color: #f0f7ff; color: #1a73e8; font-weight: 500; } .unified-subject-selector .select-item.disabled-option { color: #a0aec0 !important; cursor: not-allowed !important; background-color: transparent !important; pointer-events: none !important; } .unified-subject-selector .select-item:first-child { border-top-left-radius: 12px; border-top-right-radius: 12px; } .unified-subject-selector .select-item:last-child { border-bottom-left-radius: 12px; border-bottom-right-radius: 12px; } .unified-subject-selector.loading .select-selected { background-color: #f7fafc; color: #a0aec0; } /* 头部科目选择器样式 */ .header-subject-selector { position: relative; margin-right: 1rem; } .header-subject-selector .custom-select { width: auto; min-width: 120px; } .header-subject-selector .select-selected { background-color: #f7fafc; border: none; font-size: 13px; padding: 8px 12px; border-radius: 8px; box-shadow: none; z-index: 1000; color: #718096; transition: all 0.2s ease; } .header-subject-selector .select-selected:hover { background-color: #edf2f7; color: #4a5568; transform: scale(1.05); } .header-subject-selector .select-selected:focus { background-color: #edf2f7; color: #4a5568; outline: none; } .header-subject-selector .selected-value { font-size: 13px; color: inherit; } .header-subject-selector .select-arrow { font-size: 14px; color: inherit; } /* 头部选择器的下拉选项 */ .header-subject-selector .select-items { margin-top: 4px; border-radius: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); z-index: 9999; max-height: min(60vh, 400px); } .header-subject-selector .select-items.show { max-height: min(60vh, 400px); overflow-y: auto; } .header-subject-selector .select-item { padding: 10px 12px; font-size: 13px; min-height: 36px; } /* 紧凑模式 */ .unified-subject-selector.compact .select-selected { padding: 8px 12px; background-color: #f7fafc; border: none; border-radius: 8px; box-shadow: none; color: #718096; transition: all 0.2s ease; } .unified-subject-selector.compact .selected-value { font-size: 13px; color: inherit; } .unified-subject-selector.compact .select-arrow { font-size: 14px; color: inherit; } .unified-subject-selector.compact .select-item { padding: 10px 12px; font-size: 13px; min-height: 36px; } .unified-subject-selector.compact .select-items.show { max-height: 400px; } .unified-subject-selector.compact .select-selected:hover { background-color: #edf2f7; color: #4a5568; transform: scale(1.05); } .unified-subject-selector.compact .select-selected:focus { background-color: #edf2f7; color: #4a5568; outline: none; } /* 确保在content-header环境中的适配 */ .content-header-left .unified-subject-selector { z-index: 1000; position: relative; transform: translateZ(0); } .content-header-left .unified-subject-selector .select-items { z-index: 9999; border-radius: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); background-color: #fff; border: 1px solid #e0e0e0; } /* 当下拉框打开时,临时修改父容器的overflow */ .content-header:has(.unified-subject-selector .select-items.show) { overflow: visible !important; } /* 如果浏览器不支持:has(),使用这个fallback */ .content-header.dropdown-open { overflow: visible !important; } /* 更强力的fallback - 确保content-header不会裁剪下拉框 */ .content-header { position: relative; } .content-header.dropdown-open, .content-header:has(.select-items.show) { overflow: visible !important; z-index: 1000; } /* 修复在不同环境下的显示问题 */ .unified-subject-selector .select-items { pointer-events: auto; -webkit-overflow-scrolling: touch; } .unified-subject-selector .select-items.show { pointer-events: auto; } /* 确保下拉框不被父容器裁剪 */ .unified-subject-selector { isolation: isolate; } /* 动态调整下拉框位置,避免超出视口 */ .unified-subject-selector .select-items { max-height: min(400px, calc(100vh - var(--select-top, 100px) - 20px)); } /* 确保选项完全可见 */ .unified-subject-selector .select-item:last-child { border-bottom-left-radius: 12px; border-bottom-right-radius: 12px; margin-bottom: 0; } /* 为可能很长的选项列表提供更好的视觉提示 */ .unified-subject-selector .select-items.show { border-top: 1px solid #e0e0e0; border-bottom: 1px solid #e0e0e0; } /* 为header环境中的fixed定位下拉框设置正确的样式 */ .content-header-left .unified-subject-selector .select-items.show { /* JavaScript会动态设置这些属性,不要在CSS中覆盖 */ /* position: fixed !important; */ /* left: auto; */ /* top: auto; */ /* width: auto; */ min-width: 120px; white-space: nowrap; max-height: min(60vh, 400px); overflow-y: auto; } /* 确保在所有环境下都有足够的空间 */ @media (max-height: 600px) { .unified-subject-selector .select-items.show, .header-subject-selector .select-items.show, .unified-subject-selector.compact .select-items.show { max-height: 40vh; } } @media (max-height: 400px) { .unified-subject-selector .select-items.show, .header-subject-selector .select-items.show, .unified-subject-selector.compact .select-items.show { max-height: 30vh; } }
8,018
UnifiedSubjectSelector
css
en
css
data
{"qsc_code_num_words": 1014, "qsc_code_num_chars": 8018.0, "qsc_code_mean_word_length": 5.51972387, "qsc_code_frac_words_unique": 0.18934911, "qsc_code_frac_chars_top_2grams": 0.14472039, "qsc_code_frac_chars_top_3grams": 0.16508844, "qsc_code_frac_chars_top_4grams": 0.13507236, "qsc_code_frac_chars_dupe_5grams": 0.59746293, "qsc_code_frac_chars_dupe_6grams": 0.47239593, "qsc_code_frac_chars_dupe_7grams": 0.38181168, "qsc_code_frac_chars_dupe_8grams": 0.28157942, "qsc_code_frac_chars_dupe_9grams": 0.248526, "qsc_code_frac_chars_dupe_10grams": 0.23905664, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.05636896, "qsc_code_frac_chars_whitespace": 0.14816663, "qsc_code_size_file_byte": 8018.0, "qsc_code_num_lines": 372.0, "qsc_code_num_chars_line_max": 79.0, "qsc_code_num_chars_line_mean": 21.55376344, "qsc_code_frac_chars_alphabet": 0.76310395, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.41875, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "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/shared/UnifiedSubjectSelector.tsx
import React, { useEffect, useState, useRef } from 'react'; import { useSubject } from '../../contexts/SubjectContext'; import './UnifiedSubjectSelector.css'; interface UnifiedSubjectSelectorProps { mode?: 'enabled' | 'all' | 'existing'; includeAllOption?: boolean; placeholder?: string; disabled?: boolean; className?: string; value?: string; onChange?: (subject: string) => void; existingSubjects?: string[]; // 用于'existing'模式 } const UnifiedSubjectSelector: React.FC<UnifiedSubjectSelectorProps> = ({ mode = 'enabled', includeAllOption = false, placeholder = '选择科目', disabled = false, className = '', value, onChange, existingSubjects = [] }) => { const { currentSubject, setCurrentSubject, getEnabledSubjects, getAllSubjects, loading } = useSubject(); // 自定义下拉框的状态 const [isOpen, setIsOpen] = useState(false); const selectRef = useRef<HTMLDivElement>(null); const itemsRef = useRef<HTMLDivElement>(null); // 确定使用的值和onChange处理器 const selectedValue = value !== undefined ? value : currentSubject; const handleChange = onChange !== undefined ? onChange : setCurrentSubject; // 根据模式获取科目选项 const getSubjectOptions = (): string[] => { switch (mode) { case 'enabled': return getEnabledSubjects(); case 'all': return getAllSubjects(); case 'existing': return existingSubjects; default: return getEnabledSubjects(); } }; const subjectOptions = getSubjectOptions(); // 构建完整的选项列表 const allOptions = [ ...(includeAllOption ? ['全部科目'] : []), ...subjectOptions ]; // 检查是否在content-header环境中 const isInContentHeader = className.includes('header-subject-selector'); // 计算下拉框的最佳位置 const calculateDropdownPosition = () => { if (!selectRef.current || !itemsRef.current) return; const selectRect = selectRef.current.getBoundingClientRect(); const itemsHeight = Math.min(500, allOptions.length * (isInContentHeader ? 36 : 44) + 20); const viewportHeight = window.innerHeight; const spaceBelow = viewportHeight - selectRect.bottom; const spaceAbove = selectRect.top; console.log('🎯 计算下拉框位置:', { selectRect, itemsHeight, spaceBelow, spaceAbove, isInContentHeader }); // 设置CSS变量用于动态计算 selectRef.current.style.setProperty('--select-top', `${selectRect.bottom}px`); // 先尝试使用相对定位,避免fixed定位的复杂问题 itemsRef.current.style.position = 'absolute'; itemsRef.current.style.left = '0'; itemsRef.current.style.right = '0'; itemsRef.current.style.width = 'auto'; itemsRef.current.style.zIndex = '9999'; if (isInContentHeader) { // 临时添加类名到content-header以修改overflow const contentHeader = selectRef.current.closest('.content-header'); if (contentHeader) { contentHeader.classList.add('dropdown-open'); } } // 如果下方空间不够且上方空间更多,则向上展开 if (spaceBelow < itemsHeight && spaceAbove > spaceBelow) { itemsRef.current.style.top = 'auto'; itemsRef.current.style.bottom = '100%'; itemsRef.current.style.marginTop = '0'; itemsRef.current.style.marginBottom = '8px'; } else { itemsRef.current.style.top = '100%'; itemsRef.current.style.bottom = 'auto'; itemsRef.current.style.marginTop = '8px'; itemsRef.current.style.marginBottom = '0'; } // 重置可能影响定位的样式 itemsRef.current.style.transform = 'none'; }; // 清理header的overflow样式 const cleanupHeaderOverflow = () => { if (isInContentHeader && selectRef.current) { const contentHeader = selectRef.current.closest('.content-header'); if (contentHeader) { contentHeader.classList.remove('dropdown-open'); } } }; // 监听科目状态变化 useEffect(() => { console.log('🎯 科目选择器状态监听:', { currentSubject, selectedValue, subjectOptions, loading, mode }); }, [currentSubject, selectedValue, subjectOptions.length, loading, mode]); // 处理选项点击 const handleOptionClick = (event: React.MouseEvent, optionValue: string) => { event.preventDefault(); event.stopPropagation(); console.log('🎯 科目选择器变更:', { oldValue: selectedValue, newValue: optionValue, mode, handleChangeFunction: handleChange.name || 'anonymous' }); handleChange(optionValue); setIsOpen(false); cleanupHeaderOverflow(); }; // 处理选择器主体点击 const handleSelectClick = (event: React.MouseEvent) => { event.preventDefault(); event.stopPropagation(); if (!disabled) { const newOpenState = !isOpen; setIsOpen(newOpenState); if (newOpenState) { // 在下一帧计算位置,确保DOM已更新 requestAnimationFrame(() => { calculateDropdownPosition(); }); } else { cleanupHeaderOverflow(); } } }; // 处理点击外部关闭 useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (selectRef.current && !selectRef.current.contains(event.target as Node)) { setIsOpen(false); cleanupHeaderOverflow(); } }; const handleResize = () => { if (isOpen) { calculateDropdownPosition(); } }; const handleScroll = () => { if (isOpen && isInContentHeader) { // 对于header中的下拉框,在滚动时重新计算位置 calculateDropdownPosition(); } }; if (isOpen) { document.addEventListener('mousedown', handleClickOutside); window.addEventListener('resize', handleResize); window.addEventListener('scroll', handleScroll, true); } return () => { document.removeEventListener('mousedown', handleClickOutside); window.removeEventListener('resize', handleResize); window.removeEventListener('scroll', handleScroll, true); }; }, [isOpen, isInContentHeader]); // 组件卸载时清理 useEffect(() => { return () => { cleanupHeaderOverflow(); }; }, []); // 获取显示的文本 const getDisplayText = () => { if (loading) return '加载中...'; if (!selectedValue) return placeholder; return selectedValue; }; if (loading) { return ( <div className={`unified-subject-selector loading ${className}`}> <div className="custom-select"> <div className="select-selected disabled"> <span className="selected-value">加载中...</span> <span className="select-arrow">⌵</span> </div> </div> </div> ); } return ( <div className={`unified-subject-selector ${className}`} ref={selectRef}> <div className="custom-select"> <div className={`select-selected ${disabled ? 'disabled' : ''}`} onClick={handleSelectClick} onMouseDown={(e) => e.stopPropagation()} > <span className="selected-value">{getDisplayText()}</span> <span className="select-arrow" style={{ transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)' }} > ⌵ </span> </div> {isOpen && !disabled && ( <div className="select-items show" ref={itemsRef}> {!selectedValue && ( <div className="select-item disabled-option" style={{ color: '#a0aec0', cursor: 'not-allowed' }} > {placeholder} </div> )} {allOptions.map(option => ( <div key={option} className={`select-item ${option === selectedValue ? 'selected' : ''}`} onClick={(e) => handleOptionClick(e, option)} onMouseDown={(e) => e.stopPropagation()} > {option} </div> ))} </div> )} </div> </div> ); }; export { UnifiedSubjectSelector }; export default UnifiedSubjectSelector;
7,910
UnifiedSubjectSelector
tsx
en
tsx
code
{"qsc_code_num_words": 595, "qsc_code_num_chars": 7910.0, "qsc_code_mean_word_length": 7.95462185, "qsc_code_frac_words_unique": 0.33109244, "qsc_code_frac_chars_top_2grams": 0.04753856, "qsc_code_frac_chars_top_3grams": 0.0591591, "qsc_code_frac_chars_top_4grams": 0.0133108, "qsc_code_frac_chars_dupe_5grams": 0.0916966, "qsc_code_frac_chars_dupe_6grams": 0.07986478, "qsc_code_frac_chars_dupe_7grams": 0.06296218, "qsc_code_frac_chars_dupe_8grams": 0.06296218, "qsc_code_frac_chars_dupe_9grams": 0.06296218, "qsc_code_frac_chars_dupe_10grams": 0.03845341, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00532006, "qsc_code_frac_chars_whitespace": 0.26333755, "qsc_code_size_file_byte": 7910.0, "qsc_code_num_lines": 287.0, "qsc_code_num_chars_line_max": 95.0, "qsc_code_num_chars_line_mean": 27.56097561, "qsc_code_frac_chars_alphabet": 0.80607517, "qsc_code_frac_chars_comments": 0.04563843, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.29184549, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.07218543, "qsc_code_frac_chars_long_word_length": 0.01059603, "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}
0015/T-Glass-Applications
image_capture_app/main/include/t_glass.h
#pragma once #include "jd9613.h" #include "driver/gpio.h" #include "lvgl.h" #include "esp_lvgl_port.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 lv_gui_ble_status(bool isOn); void update_canvas_with_rgb565(uint8_t *data, size_t len);
1,328
t_glass
h
en
c
code
{"qsc_code_num_words": 205, "qsc_code_num_chars": 1328.0, "qsc_code_mean_word_length": 4.14146341, "qsc_code_frac_words_unique": 0.47804878, "qsc_code_frac_chars_top_2grams": 0.31095406, "qsc_code_frac_chars_top_3grams": 0.12367491, "qsc_code_frac_chars_top_4grams": 0.03297998, "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.06423778, "qsc_code_frac_chars_whitespace": 0.21460843, "qsc_code_size_file_byte": 1328.0, "qsc_code_num_lines": 50.0, "qsc_code_num_chars_line_max": 58.0, "qsc_code_num_chars_line_mean": 26.56, "qsc_code_frac_chars_alphabet": 0.74976031, "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.03160271, "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.075, "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.175, "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/T-Glass-Applications
ancs_app/main/ble_ancs.c
/* * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Unlicense OR CC0-1.0 */ #include <stdlib.h> #include <string.h> #include <inttypes.h> #include "esp_log.h" #include "ble_ancs.h" #define BLE_ANCS_TAG "BLE_ANCS" /* | EventID(1 Byte) | EventFlags(1 Byte) | CategoryID(1 Byte) | CategoryCount(1 Byte) | NotificationUID(4 Bytes) | A GATT notification delivered through the Notification Source characteristic contains the following information: * EventID: This field informs the accessory whether the given iOS notification was added, modified, or removed. The enumerated values for this field are defined in EventID Values. * EventFlags: A bitmask whose set bits inform an NC of specificities with the iOS notification. For example, if an iOS notification is considered “important”, the NC may want to display a more aggressive user interface (UI) to make sure the user is properly alerted. The enumerated bits for this field are defined in EventFlags. * CategoryID: A numerical value providing a category in which the iOS notification can be classified. The NP will make a best effort to provide an accurate category for each iOS notification. The enumerated values for this field are defined in CategoryID Values. * CategoryCount: The current number of active iOS notifications in the given category. For example, if two unread emails are sitting in a user’s email inbox, and a new email is pushed to the user’s iOS device, the value of CategoryCount is 3. * NotificationUID: A 32-bit numerical value that is the unique identifier (UID) for the iOS notification. This value can be used as a handle in commands sent to the Control Point characteristic to interact with the iOS notification. */ char *EventID_to_String(uint8_t EventID) { char *str = NULL; switch (EventID) { case EventIDNotificationAdded: str = "New message"; break; case EventIDNotificationModified: str = "Modified message"; break; case EventIDNotificationRemoved: str = "Removed message"; break; default: str = "unknown EventID"; break; } return str; } char *CategoryID_to_String(uint8_t CategoryID) { char *Cidstr = NULL; switch (CategoryID) { case CategoryIDOther: Cidstr = "Other"; break; case CategoryIDIncomingCall: Cidstr = "IncomingCall"; break; case CategoryIDMissedCall: Cidstr = "MissedCall"; break; case CategoryIDVoicemail: Cidstr = "Voicemail"; break; case CategoryIDSocial: Cidstr = "Social"; break; case CategoryIDSchedule: Cidstr = "Schedule"; break; case CategoryIDEmail: Cidstr = "Email"; break; case CategoryIDNews: Cidstr = "News"; break; case CategoryIDHealthAndFitness: Cidstr = "HealthAndFitness"; break; case CategoryIDBusinessAndFinance: Cidstr = "BusinessAndFinance"; break; case CategoryIDLocation: Cidstr = "Location"; break; case CategoryIDEntertainment: Cidstr = "Entertainment"; break; default: Cidstr = "Unknown CategoryID"; break; } return Cidstr; } /* | EventID(1 Byte) | EventFlags(1 Byte) | CategoryID(1 Byte) | CategoryCount(1 Byte) | NotificationUID(4 Bytes) | */ void esp_receive_apple_notification_source(uint8_t *message, uint16_t message_len) { if (!message || message_len < 5) { return; } uint8_t EventID = message[0]; char *EventIDS = EventID_to_String(EventID); uint8_t EventFlags = message[1]; uint8_t CategoryID = message[2]; char *Cidstr = CategoryID_to_String(CategoryID); uint8_t CategoryCount = message[3]; uint32_t NotificationUID = (message[4]) | (message[5] << 8) | (message[6] << 16) | (message[7] << 24); ESP_LOGI(BLE_ANCS_TAG, "EventID:%s EventFlags:0x%x CategoryID:%s CategoryCount:%d NotificationUID:%" PRIu32, EventIDS, EventFlags, Cidstr, CategoryCount, NotificationUID); } void esp_receive_apple_data_source(uint8_t *message, uint16_t message_len) { // esp_log_buffer_hex("data source", message, message_len); if (!message || message_len == 0) { return; } uint8_t Command_id = message[0]; switch (Command_id) { case CommandIDGetNotificationAttributes: { uint32_t NotificationUID = (message[1]) | (message[2] << 8) | (message[3] << 16) | (message[4] << 24); uint32_t remian_attr_len = message_len - 5; uint8_t *attrs = &message[5]; ESP_LOGI(BLE_ANCS_TAG, "recevice Notification Attributes response Command_id %d NotificationUID %" PRIu32, Command_id, NotificationUID); while (remian_attr_len > 0) { uint8_t AttributeID = attrs[0]; uint16_t len = attrs[1] | (attrs[2] << 8); if (len > (remian_attr_len - 3)) { ESP_LOGE(BLE_ANCS_TAG, "data error"); break; } switch (AttributeID) { case NotificationAttributeIDAppIdentifier: esp_log_buffer_char("Identifier", &attrs[3], len); break; case NotificationAttributeIDTitle: esp_log_buffer_char("Title", &attrs[3], len); break; case NotificationAttributeIDSubtitle: esp_log_buffer_char("Subtitle", &attrs[3], len); break; case NotificationAttributeIDMessage: esp_log_buffer_char("Message", &attrs[3], len); break; case NotificationAttributeIDMessageSize: esp_log_buffer_char("MessageSize", &attrs[3], len); break; case NotificationAttributeIDDate: // yyyyMMdd'T'HHmmSS esp_log_buffer_char("Date", &attrs[3], len); break; case NotificationAttributeIDPositiveActionLabel: esp_log_buffer_hex("PActionLabel", &attrs[3], len); break; case NotificationAttributeIDNegativeActionLabel: esp_log_buffer_hex("NActionLabel", &attrs[3], len); break; default: esp_log_buffer_hex("unknownAttributeID", &attrs[3], len); break; } attrs += (1 + 2 + len); remian_attr_len -= (1 + 2 + len); } break; } case CommandIDGetAppAttributes: ESP_LOGI(BLE_ANCS_TAG, "recevice APP Attributes response"); break; case CommandIDPerformNotificationAction: ESP_LOGI(BLE_ANCS_TAG, "recevice Perform Notification Action"); break; default: ESP_LOGI(BLE_ANCS_TAG, "unknown Command ID"); break; } } char *Errcode_to_String(uint16_t status) { char *Errstr = NULL; switch (status) { case Unknown_command: Errstr = "Unknown_command"; break; case Invalid_command: Errstr = "Invalid_command"; break; case Invalid_parameter: Errstr = "Invalid_parameter"; break; case Action_failed: Errstr = "Action_failed"; break; default: Errstr = "unknown_failed"; break; } return Errstr; }
7,451
ble_ancs
c
en
c
code
{"qsc_code_num_words": 800, "qsc_code_num_chars": 7451.0, "qsc_code_mean_word_length": 5.695, "qsc_code_frac_words_unique": 0.29625, "qsc_code_frac_chars_top_2grams": 0.04938543, "qsc_code_frac_chars_top_3grams": 0.02633889, "qsc_code_frac_chars_top_4grams": 0.02765584, "qsc_code_frac_chars_dupe_5grams": 0.13762072, "qsc_code_frac_chars_dupe_6grams": 0.10250219, "qsc_code_frac_chars_dupe_7grams": 0.07023705, "qsc_code_frac_chars_dupe_8grams": 0.07023705, "qsc_code_frac_chars_dupe_9grams": 0.05443371, "qsc_code_frac_chars_dupe_10grams": 0.03555751, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0187864, "qsc_code_frac_chars_whitespace": 0.28559925, "qsc_code_size_file_byte": 7451.0, "qsc_code_num_lines": 219.0, "qsc_code_num_chars_line_max": 176.0, "qsc_code_num_chars_line_mean": 34.02283105, "qsc_code_frac_chars_alphabet": 0.83712192, "qsc_code_frac_chars_comments": 0.25499933, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.23756906, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.11187173, "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.02762431, "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.08287293, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": 0.03314917}
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/vector/vmatrix.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 "vmatrix.h" #include <vglobal.h> #include <cassert> #include <cmath> V_BEGIN_NAMESPACE /* m11 m21 mtx * m12 m22 mty * m13 m23 m33 */ inline float VMatrix::determinant() const { return m11 * (m33 * m22 - mty * m23) - m21 * (m33 * m12 - mty * m13) + mtx * (m23 * m12 - m22 * m13); } bool VMatrix::isAffine() const { return type() < MatrixType::Project; } bool VMatrix::isIdentity() const { return type() == MatrixType::None; } bool VMatrix::isInvertible() const { return !vIsZero(determinant()); } bool VMatrix::isScaling() const { return type() >= MatrixType::Scale; } bool VMatrix::isRotating() const { return type() >= MatrixType::Rotate; } bool VMatrix::isTranslating() const { return type() >= MatrixType::Translate; } VMatrix &VMatrix::operator*=(float num) { if (num == 1.) return *this; m11 *= num; m12 *= num; m13 *= num; m21 *= num; m22 *= num; m23 *= num; mtx *= num; mty *= num; m33 *= num; if (dirty < MatrixType::Scale) dirty = MatrixType::Scale; return *this; } VMatrix &VMatrix::operator/=(float div) { if (div == 0) return *this; div = 1 / div; return operator*=(div); } VMatrix::MatrixType VMatrix::type() const { if (dirty == MatrixType::None || dirty < mType) return mType; switch (dirty) { case MatrixType::Project: if (!vIsZero(m13) || !vIsZero(m23) || !vIsZero(m33 - 1)) { mType = MatrixType::Project; break; } VECTOR_FALLTHROUGH case MatrixType::Shear: case MatrixType::Rotate: if (!vIsZero(m12) || !vIsZero(m21)) { const float dot = m11 * m12 + m21 * m22; if (vIsZero(dot)) mType = MatrixType::Rotate; else mType = MatrixType::Shear; break; } VECTOR_FALLTHROUGH case MatrixType::Scale: if (!vIsZero(m11 - 1) || !vIsZero(m22 - 1)) { mType = MatrixType::Scale; break; } VECTOR_FALLTHROUGH case MatrixType::Translate: if (!vIsZero(mtx) || !vIsZero(mty)) { mType = MatrixType::Translate; break; } VECTOR_FALLTHROUGH case MatrixType::None: mType = MatrixType::None; break; } dirty = MatrixType::None; return mType; } VMatrix &VMatrix::translate(float dx, float dy) { if (dx == 0 && dy == 0) return *this; switch (type()) { case MatrixType::None: mtx = dx; mty = dy; break; case MatrixType::Translate: mtx += dx; mty += dy; break; case MatrixType::Scale: mtx += dx * m11; mty += dy * m22; break; case MatrixType::Project: m33 += dx * m13 + dy * m23; VECTOR_FALLTHROUGH case MatrixType::Shear: case MatrixType::Rotate: mtx += dx * m11 + dy * m21; mty += dy * m22 + dx * m12; break; } if (dirty < MatrixType::Translate) dirty = MatrixType::Translate; return *this; } VMatrix &VMatrix::scale(float sx, float sy) { if (sx == 1 && sy == 1) return *this; switch (type()) { case MatrixType::None: case MatrixType::Translate: m11 = sx; m22 = sy; break; case MatrixType::Project: m13 *= sx; m23 *= sy; VECTOR_FALLTHROUGH case MatrixType::Rotate: case MatrixType::Shear: m12 *= sx; m21 *= sy; VECTOR_FALLTHROUGH case MatrixType::Scale: m11 *= sx; m22 *= sy; break; } if (dirty < MatrixType::Scale) dirty = MatrixType::Scale; return *this; } VMatrix &VMatrix::shear(float sh, float sv) { if (sh == 0 && sv == 0) return *this; switch (type()) { case MatrixType::None: case MatrixType::Translate: m12 = sv; m21 = sh; break; case MatrixType::Scale: m12 = sv * m22; m21 = sh * m11; break; case MatrixType::Project: { float tm13 = sv * m23; float tm23 = sh * m13; m13 += tm13; m23 += tm23; VECTOR_FALLTHROUGH } case MatrixType::Rotate: case MatrixType::Shear: { float tm11 = sv * m21; float tm22 = sh * m12; float tm12 = sv * m22; float tm21 = sh * m11; m11 += tm11; m12 += tm12; m21 += tm21; m22 += tm22; break; } } if (dirty < MatrixType::Shear) dirty = MatrixType::Shear; return *this; } static const float deg2rad = float(0.017453292519943295769); // pi/180 static const float inv_dist_to_plane = 1. / 1024.; VMatrix &VMatrix::rotate(float a, Axis axis) { if (a == 0) return *this; float sina = 0; float cosa = 0; if (a == 90. || a == -270.) sina = 1.; else if (a == 270. || a == -90.) sina = -1.; else if (a == 180.) cosa = -1.; else { float b = deg2rad * a; // convert to radians sina = std::sin(b); // fast and convenient cosa = std::cos(b); } if (axis == Axis::Z) { switch (type()) { case MatrixType::None: case MatrixType::Translate: m11 = cosa; m12 = sina; m21 = -sina; m22 = cosa; break; case MatrixType::Scale: { float tm11 = cosa * m11; float tm12 = sina * m22; float tm21 = -sina * m11; float tm22 = cosa * m22; m11 = tm11; m12 = tm12; m21 = tm21; m22 = tm22; break; } case MatrixType::Project: { float tm13 = cosa * m13 + sina * m23; float tm23 = -sina * m13 + cosa * m23; m13 = tm13; m23 = tm23; VECTOR_FALLTHROUGH } case MatrixType::Rotate: case MatrixType::Shear: { float tm11 = cosa * m11 + sina * m21; float tm12 = cosa * m12 + sina * m22; float tm21 = -sina * m11 + cosa * m21; float tm22 = -sina * m12 + cosa * m22; m11 = tm11; m12 = tm12; m21 = tm21; m22 = tm22; break; } } if (dirty < MatrixType::Rotate) dirty = MatrixType::Rotate; } else { VMatrix result; if (axis == Axis::Y) { result.m11 = cosa; result.m13 = -sina * inv_dist_to_plane; } else { result.m22 = cosa; result.m23 = -sina * inv_dist_to_plane; } result.mType = MatrixType::Project; *this = result * *this; } return *this; } VMatrix VMatrix::operator*(const VMatrix &m) const { const MatrixType otherType = m.type(); if (otherType == MatrixType::None) return *this; const MatrixType thisType = type(); if (thisType == MatrixType::None) return m; VMatrix t; MatrixType type = vMax(thisType, otherType); switch (type) { case MatrixType::None: break; case MatrixType::Translate: t.mtx = mtx + m.mtx; t.mty += mty + m.mty; break; case MatrixType::Scale: { float m11v = m11 * m.m11; float m22v = m22 * m.m22; float m31v = mtx * m.m11 + m.mtx; float m32v = mty * m.m22 + m.mty; t.m11 = m11v; t.m22 = m22v; t.mtx = m31v; t.mty = m32v; break; } case MatrixType::Rotate: case MatrixType::Shear: { float m11v = m11 * m.m11 + m12 * m.m21; float m12v = m11 * m.m12 + m12 * m.m22; float m21v = m21 * m.m11 + m22 * m.m21; float m22v = m21 * m.m12 + m22 * m.m22; float m31v = mtx * m.m11 + mty * m.m21 + m.mtx; float m32v = mtx * m.m12 + mty * m.m22 + m.mty; t.m11 = m11v; t.m12 = m12v; t.m21 = m21v; t.m22 = m22v; t.mtx = m31v; t.mty = m32v; break; } case MatrixType::Project: { float m11v = m11 * m.m11 + m12 * m.m21 + m13 * m.mtx; float m12v = m11 * m.m12 + m12 * m.m22 + m13 * m.mty; float m13v = m11 * m.m13 + m12 * m.m23 + m13 * m.m33; float m21v = m21 * m.m11 + m22 * m.m21 + m23 * m.mtx; float m22v = m21 * m.m12 + m22 * m.m22 + m23 * m.mty; float m23v = m21 * m.m13 + m22 * m.m23 + m23 * m.m33; float m31v = mtx * m.m11 + mty * m.m21 + m33 * m.mtx; float m32v = mtx * m.m12 + mty * m.m22 + m33 * m.mty; float m33v = mtx * m.m13 + mty * m.m23 + m33 * m.m33; t.m11 = m11v; t.m12 = m12v; t.m13 = m13v; t.m21 = m21v; t.m22 = m22v; t.m23 = m23v; t.mtx = m31v; t.mty = m32v; t.m33 = m33v; } } t.dirty = type; t.mType = type; return t; } VMatrix &VMatrix::operator*=(const VMatrix &o) { const MatrixType otherType = o.type(); if (otherType == MatrixType::None) return *this; const MatrixType thisType = type(); if (thisType == MatrixType::None) return operator=(o); MatrixType t = vMax(thisType, otherType); switch (t) { case MatrixType::None: break; case MatrixType::Translate: mtx += o.mtx; mty += o.mty; break; case MatrixType::Scale: { float m11v = m11 * o.m11; float m22v = m22 * o.m22; float m31v = mtx * o.m11 + o.mtx; float m32v = mty * o.m22 + o.mty; m11 = m11v; m22 = m22v; mtx = m31v; mty = m32v; break; } case MatrixType::Rotate: case MatrixType::Shear: { float m11v = m11 * o.m11 + m12 * o.m21; float m12v = m11 * o.m12 + m12 * o.m22; float m21v = m21 * o.m11 + m22 * o.m21; float m22v = m21 * o.m12 + m22 * o.m22; float m31v = mtx * o.m11 + mty * o.m21 + o.mtx; float m32v = mtx * o.m12 + mty * o.m22 + o.mty; m11 = m11v; m12 = m12v; m21 = m21v; m22 = m22v; mtx = m31v; mty = m32v; break; } case MatrixType::Project: { float m11v = m11 * o.m11 + m12 * o.m21 + m13 * o.mtx; float m12v = m11 * o.m12 + m12 * o.m22 + m13 * o.mty; float m13v = m11 * o.m13 + m12 * o.m23 + m13 * o.m33; float m21v = m21 * o.m11 + m22 * o.m21 + m23 * o.mtx; float m22v = m21 * o.m12 + m22 * o.m22 + m23 * o.mty; float m23v = m21 * o.m13 + m22 * o.m23 + m23 * o.m33; float m31v = mtx * o.m11 + mty * o.m21 + m33 * o.mtx; float m32v = mtx * o.m12 + mty * o.m22 + m33 * o.mty; float m33v = mtx * o.m13 + mty * o.m23 + m33 * o.m33; m11 = m11v; m12 = m12v; m13 = m13v; m21 = m21v; m22 = m22v; m23 = m23v; mtx = m31v; mty = m32v; m33 = m33v; } } dirty = t; mType = t; return *this; } VMatrix VMatrix::adjoint() const { float h11, h12, h13, h21, h22, h23, h31, h32, h33; h11 = m22 * m33 - m23 * mty; h21 = m23 * mtx - m21 * m33; h31 = m21 * mty - m22 * mtx; h12 = m13 * mty - m12 * m33; h22 = m11 * m33 - m13 * mtx; h32 = m12 * mtx - m11 * mty; h13 = m12 * m23 - m13 * m22; h23 = m13 * m21 - m11 * m23; h33 = m11 * m22 - m12 * m21; VMatrix res; res.m11 = h11; res.m12 = h12; res.m13 = h13; res.m21 = h21; res.m22 = h22; res.m23 = h23; res.mtx = h31; res.mty = h32; res.m33 = h33; res.mType = MatrixType::None; res.dirty = MatrixType::Project; return res; } VMatrix VMatrix::inverted(bool *invertible) const { VMatrix invert; bool inv = true; switch (type()) { case MatrixType::None: break; case MatrixType::Translate: invert.mtx = -mtx; invert.mty = -mty; break; case MatrixType::Scale: inv = !vIsZero(m11); inv &= !vIsZero(m22); if (inv) { invert.m11 = 1.0f / m11; invert.m22 = 1.0f / m22; invert.mtx = -mtx * invert.m11; invert.mty = -mty * invert.m22; } break; default: // general case float det = determinant(); inv = !vIsZero(det); if (inv) invert = (adjoint() /= det); // TODO Test above line break; } if (invertible) *invertible = inv; if (inv) { // inverting doesn't change the type invert.mType = mType; invert.dirty = dirty; } return invert; } bool VMatrix::operator==(const VMatrix &o) const { return fuzzyCompare(o); } bool VMatrix::operator!=(const VMatrix &o) const { return !operator==(o); } bool VMatrix::fuzzyCompare(const VMatrix &o) const { return vCompare(m11, o.m11) && vCompare(m12, o.m12) && vCompare(m21, o.m21) && vCompare(m22, o.m22) && vCompare(mtx, o.mtx) && vCompare(mty, o.mty); } #define V_NEAR_CLIP 0.000001f #ifdef MAP #undef MAP #endif #define MAP(x, y, nx, ny) \ do { \ float FX_ = x; \ float FY_ = y; \ switch (t) { \ case MatrixType::None: \ nx = FX_; \ ny = FY_; \ break; \ case MatrixType::Translate: \ nx = FX_ + mtx; \ ny = FY_ + mty; \ break; \ case MatrixType::Scale: \ nx = m11 * FX_ + mtx; \ ny = m22 * FY_ + mty; \ break; \ case MatrixType::Rotate: \ case MatrixType::Shear: \ case MatrixType::Project: \ nx = m11 * FX_ + m21 * FY_ + mtx; \ ny = m12 * FX_ + m22 * FY_ + mty; \ if (t == MatrixType::Project) { \ float w = (m13 * FX_ + m23 * FY_ + m33); \ if (w < V_NEAR_CLIP) w = V_NEAR_CLIP; \ w = 1. / w; \ nx *= w; \ ny *= w; \ } \ } \ } while (0) VRect VMatrix::map(const VRect &rect) const { VMatrix::MatrixType t = type(); if (t <= MatrixType::Translate) return rect.translated(std::lround(mtx), std::lround(mty)); if (t <= MatrixType::Scale) { int x = std::lround(m11 * rect.x() + mtx); int y = std::lround(m22 * rect.y() + mty); int w = std::lround(m11 * rect.width()); int h = std::lround(m22 * rect.height()); if (w < 0) { w = -w; x -= w; } if (h < 0) { h = -h; y -= h; } return {x, y, w, h}; } else if (t < MatrixType::Project) { // see mapToPolygon for explanations of the algorithm. float x = 0, y = 0; MAP(rect.left(), rect.top(), x, y); float xmin = x; float ymin = y; float xmax = x; float ymax = y; MAP(rect.right() + 1, rect.top(), x, y); xmin = vMin(xmin, x); ymin = vMin(ymin, y); xmax = vMax(xmax, x); ymax = vMax(ymax, y); MAP(rect.right() + 1, rect.bottom() + 1, x, y); xmin = vMin(xmin, x); ymin = vMin(ymin, y); xmax = vMax(xmax, x); ymax = vMax(ymax, y); MAP(rect.left(), rect.bottom() + 1, x, y); xmin = vMin(xmin, x); ymin = vMin(ymin, y); xmax = vMax(xmax, x); ymax = vMax(ymax, y); return VRect(std::lround(xmin), std::lround(ymin), std::lround(xmax) - std::lround(xmin), std::lround(ymax) - std::lround(ymin)); } else { // Not supported assert(0); return {}; } } VPointF VMatrix::map(const VPointF &p) const { float fx = p.x(); float fy = p.y(); float x = 0, y = 0; VMatrix::MatrixType t = type(); switch (t) { case MatrixType::None: x = fx; y = fy; break; case MatrixType::Translate: x = fx + mtx; y = fy + mty; break; case MatrixType::Scale: x = m11 * fx + mtx; y = m22 * fy + mty; break; case MatrixType::Rotate: case MatrixType::Shear: case MatrixType::Project: x = m11 * fx + m21 * fy + mtx; y = m12 * fx + m22 * fy + mty; if (t == MatrixType::Project) { float w = 1.0f / (m13 * fx + m23 * fy + m33); x *= w; y *= w; } } return {x, y}; } V_END_NAMESPACE
18,367
vmatrix
cpp
en
cpp
code
{"qsc_code_num_words": 2144, "qsc_code_num_chars": 18367.0, "qsc_code_mean_word_length": 4.11333955, "qsc_code_frac_words_unique": 0.12639925, "qsc_code_frac_chars_top_2grams": 0.09048645, "qsc_code_frac_chars_top_3grams": 0.05170654, "qsc_code_frac_chars_top_4grams": 0.03163624, "qsc_code_frac_chars_dupe_5grams": 0.41660052, "qsc_code_frac_chars_dupe_6grams": 0.34221567, "qsc_code_frac_chars_dupe_7grams": 0.31749631, "qsc_code_frac_chars_dupe_8grams": 0.29368409, "qsc_code_frac_chars_dupe_9grams": 0.19956911, "qsc_code_frac_chars_dupe_10grams": 0.16634539, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.09338695, "qsc_code_frac_chars_whitespace": 0.39075516, "qsc_code_size_file_byte": 18367.0, "qsc_code_num_lines": 684.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 26.85233918, "qsc_code_frac_chars_alphabet": 0.69472744, "qsc_code_frac_chars_comments": 0.07671367, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.30569948, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00053072, "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.00146199, "qsc_code_frac_lines_assert": 0.00345423, "qsc_codecpp_frac_lines_preprocessor_directives": 0.01554404, "qsc_codecpp_frac_lines_func_ratio": 0.01554404, "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.02936097, "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/vrle.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 VRLE_H #define VRLE_H #include <vector> #include "vcowptr.h" #include "vglobal.h" #include "vpoint.h" #include "vrect.h" V_BEGIN_NAMESPACE class VRle { public: struct Span { short x{0}; short y{0}; uint16_t len{0}; uint8_t coverage{0}; }; using VRleSpanCb = void (*)(size_t count, const VRle::Span *spans, void *userData); bool empty() const { return d->empty(); } VRect boundingRect() const { return d->bbox(); } void setBoundingRect(const VRect &bbox) { d->setBbox(bbox); } void addSpan(const VRle::Span *span, size_t count) { d.write().addSpan(span, count); } void reset() { d.write().reset(); } void translate(const VPoint &p) { d.write().translate(p); } void operator*=(uint8_t alpha) { d.write() *= alpha; } void intersect(const VRect &r, VRleSpanCb cb, void *userData) const; void intersect(const VRle &rle, VRleSpanCb cb, void *userData) const; void operator&=(const VRle &o); VRle operator&(const VRle &o) const; VRle operator-(const VRle &o) const; VRle operator+(const VRle &o) const { return opGeneric(o, Data::Op::Add); } VRle operator^(const VRle &o) const { return opGeneric(o, Data::Op::Xor); } friend VRle operator-(const VRect &rect, const VRle &o); friend VRle operator&(const VRect &rect, const VRle &o); bool unique() const { return d.unique(); } size_t refCount() const { return d.refCount(); } void clone(const VRle &o) { d.write().clone(o.d.read()); } public: struct View { Span * _data; size_t _size; View(const Span *data, size_t sz) : _data((Span *)data), _size(sz) {} Span * data() { return _data; } size_t size() { return _size; } }; struct Data { enum class Op { Add, Xor, Substract }; VRle::View view() const { return VRle::View(mSpans.data(), mSpans.size()); } bool empty() const { return mSpans.empty(); } void addSpan(const VRle::Span *span, size_t count); void updateBbox() const; VRect bbox() const; void setBbox(const VRect &bbox) const; void reset(); void translate(const VPoint &p); void operator*=(uint8_t alpha); void opGeneric(const VRle::Data &, const VRle::Data &, Op code); void opSubstract(const VRle::Data &, const VRle::Data &); void opIntersect(VRle::View a, VRle::View b); void opIntersect(const VRect &, VRle::VRleSpanCb, void *) const; void addRect(const VRect &rect); void clone(const VRle::Data &); std::vector<VRle::Span> mSpans; VPoint mOffset; mutable VRect mBbox; mutable bool mBboxDirty = true; }; private: VRle opGeneric(const VRle &o, Data::Op opcode) const; vcow_ptr<Data> d; }; inline void VRle::intersect(const VRect &r, VRleSpanCb cb, void *userData) const { d->opIntersect(r, cb, userData); } V_END_NAMESPACE #endif // VRLE_H
4,252
vrle
h
en
c
code
{"qsc_code_num_words": 568, "qsc_code_num_chars": 4252.0, "qsc_code_mean_word_length": 4.72887324, "qsc_code_frac_words_unique": 0.32922535, "qsc_code_frac_chars_top_2grams": 0.06701415, "qsc_code_frac_chars_top_3grams": 0.03350707, "qsc_code_frac_chars_top_4grams": 0.03350707, "qsc_code_frac_chars_dupe_5grams": 0.24274013, "qsc_code_frac_chars_dupe_6grams": 0.2256143, "qsc_code_frac_chars_dupe_7grams": 0.15264334, "qsc_code_frac_chars_dupe_8grams": 0.15264334, "qsc_code_frac_chars_dupe_9grams": 0.15264334, "qsc_code_frac_chars_dupe_10grams": 0.05658972, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00407268, "qsc_code_frac_chars_whitespace": 0.24929445, "qsc_code_size_file_byte": 4252.0, "qsc_code_num_lines": 121.0, "qsc_code_num_chars_line_max": 81.0, "qsc_code_num_chars_line_mean": 35.14049587, "qsc_code_frac_chars_alphabet": 0.83740602, "qsc_code_frac_chars_comments": 0.27234243, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.07228916, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0106658, "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.36144578, "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.43373494, "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/vector/vstackallocator.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 VSTACK_ALLOCATOR_H #define VSTACK_ALLOCATOR_H #include <cstddef> #include <cassert> template <std::size_t N, std::size_t alignment = alignof(std::max_align_t)> class arena { alignas(alignment) char buf_[N]; char* ptr_; public: ~arena() {ptr_ = nullptr;} arena() noexcept : ptr_(buf_) {} arena(const arena&) = delete; arena& operator=(const arena&) = delete; template <std::size_t ReqAlign> char* allocate(std::size_t n); void deallocate(char* p, std::size_t n) noexcept; static constexpr std::size_t size() noexcept {return N;} std::size_t used() const noexcept {return static_cast<std::size_t>(ptr_ - buf_);} void reset() noexcept {ptr_ = buf_;} private: static std::size_t align_up(std::size_t n) noexcept {return (n + (alignment-1)) & ~(alignment-1);} bool pointer_in_buffer(char* p) noexcept {return buf_ <= p && p <= buf_ + N;} }; template <std::size_t N, std::size_t alignment> template <std::size_t ReqAlign> char* arena<N, alignment>::allocate(std::size_t n) { static_assert(ReqAlign <= alignment, "alignment is too small for this arena"); assert(pointer_in_buffer(ptr_) && "stack_alloc has outlived arena"); auto const aligned_n = align_up(n); if (static_cast<decltype(aligned_n)>(buf_ + N - ptr_) >= aligned_n) { char* r = ptr_; ptr_ += aligned_n; return r; } static_assert(alignment <= alignof(std::max_align_t), "you've chosen an " "alignment that is larger than alignof(std::max_align_t), and " "cannot be guaranteed by normal operator new"); return static_cast<char*>(::operator new(n)); } template <std::size_t N, std::size_t alignment> void arena<N, alignment>::deallocate(char* p, std::size_t n) noexcept { assert(pointer_in_buffer(ptr_) && "stack_alloc has outlived arena"); if (pointer_in_buffer(p)) { n = align_up(n); if (p + n == ptr_) ptr_ = p; } else ::operator delete(p); } template <class T, std::size_t N, std::size_t Align = alignof(std::max_align_t)> class stack_alloc { public: using value_type = T; static auto constexpr alignment = Align; static auto constexpr size = N; using arena_type = arena<size, alignment>; private: arena_type& a_; public: stack_alloc(const stack_alloc&) = default; stack_alloc& operator=(const stack_alloc&) = delete; stack_alloc(arena_type& a) noexcept : a_(a) { static_assert(size % alignment == 0, "size N needs to be a multiple of alignment Align"); } template <class U> stack_alloc(const stack_alloc<U, N, alignment>& a) noexcept : a_(a.a_) {} template <class _Up> struct rebind {using other = stack_alloc<_Up, N, alignment>;}; T* allocate(std::size_t n) { return reinterpret_cast<T*>(a_.template allocate<alignof(T)>(n*sizeof(T))); } void deallocate(T* p, std::size_t n) noexcept { a_.deallocate(reinterpret_cast<char*>(p), n*sizeof(T)); } template <class T1, std::size_t N1, std::size_t A1, class U, std::size_t M, std::size_t A2> friend bool operator==(const stack_alloc<T1, N1, A1>& x, const stack_alloc<U, M, A2>& y) noexcept; template <class U, std::size_t M, std::size_t A> friend class stack_alloc; }; template <class T, std::size_t N, std::size_t A1, class U, std::size_t M, std::size_t A2> inline bool operator==(const stack_alloc<T, N, A1>& x, const stack_alloc<U, M, A2>& y) noexcept { return N == M && A1 == A2 && &x.a_ == &y.a_; } template <class T, std::size_t N, std::size_t A1, class U, std::size_t M, std::size_t A2> inline bool operator!=(const stack_alloc<T, N, A1>& x, const stack_alloc<U, M, A2>& y) noexcept { return !(x == y); } #endif // VSTACK_ALLOCATOR_H
5,031
vstackallocator
h
en
c
code
{"qsc_code_num_words": 754, "qsc_code_num_chars": 5031.0, "qsc_code_mean_word_length": 4.27586207, "qsc_code_frac_words_unique": 0.25198939, "qsc_code_frac_chars_top_2grams": 0.07599256, "qsc_code_frac_chars_top_3grams": 0.08684864, "qsc_code_frac_chars_top_4grams": 0.03629032, "qsc_code_frac_chars_dupe_5grams": 0.30521092, "qsc_code_frac_chars_dupe_6grams": 0.24751861, "qsc_code_frac_chars_dupe_7grams": 0.20099256, "qsc_code_frac_chars_dupe_8grams": 0.20099256, "qsc_code_frac_chars_dupe_9grams": 0.18114144, "qsc_code_frac_chars_dupe_10grams": 0.16346154, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00633232, "qsc_code_frac_chars_whitespace": 0.21526535, "qsc_code_size_file_byte": 5031.0, "qsc_code_num_lines": 156.0, "qsc_code_num_chars_line_max": 91.0, "qsc_code_num_chars_line_mean": 32.25, "qsc_code_frac_chars_alphabet": 0.81028369, "qsc_code_frac_chars_comments": 0.23255814, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.16814159, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.06889407, "qsc_code_frac_chars_long_word_length": 0.00673401, "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.05309735, "qsc_codec_frac_lines_func_ratio": 0.10619469, "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.15044248, "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/T-Glass-Applications
ancs_app/main/battery_measurement.c
#include "battery_measurement.h" #include "esp_adc/adc_oneshot.h" #include "esp_adc/adc_cali.h" #include "esp_adc/adc_cali_scheme.h" #define ADC_CHANNEL ADC_CHANNEL_2 #define ADC_UNIT ADC_UNIT_2 #define ADC_ATTEN ADC_ATTEN_DB_12 #define ADC_BITWIDTH ADC_BITWIDTH_12 #define REF_VOLTAGE 1100 // Reference voltage in mV (adjust based on ESP32's factory calibration) #define DIVIDER_RATIO 2.0 // Resistor divider ratio (adjust based on your resistor values) static const char *TAG = "BATTERY_MEASUREMENT"; static adc_oneshot_unit_handle_t adc_handle = NULL; static adc_cali_handle_t cali_handle = NULL; static bool calibration_enabled = false; // Battery voltage-to-percentage lookup table typedef struct { float voltage; // Battery voltage in volts int percentage; // Corresponding battery percentage } battery_level_t; // Battery voltage-to-percentage lookup table const battery_level_t battery_curve[] = { {4.20, 100}, {4.00, 90}, {3.85, 75}, {3.70, 50}, {3.60, 25}, {3.50, 10}, {3.30, 0}, }; #define NUM_POINTS (sizeof(battery_curve) / sizeof(battery_curve[0])) // Helper function to get battery percentage from voltage int battery_voltage_to_percentage(float voltage) { if (voltage >= battery_curve[0].voltage) { return 100; // Above the max voltage, assume full charge } if (voltage <= battery_curve[NUM_POINTS - 1].voltage) { return 0; // Below the minimum voltage, assume empty } // Linear interpolation between points for (int i = 0; i < NUM_POINTS - 1; i++) { if (voltage <= battery_curve[i].voltage && voltage > battery_curve[i + 1].voltage) { float v1 = battery_curve[i].voltage; float v2 = battery_curve[i + 1].voltage; int p1 = battery_curve[i].percentage; int p2 = battery_curve[i + 1].percentage; // Linear interpolation formula return p1 + (voltage - v1) * (p2 - p1) / (v2 - v1); } } return 0; // Default, should never reach here } esp_err_t battery_measurement_init(void) { esp_err_t ret; adc_oneshot_unit_init_cfg_t init_config = { .unit_id = ADC_UNIT, .ulp_mode = ADC_ULP_MODE_DISABLE, }; ret = adc_oneshot_new_unit(&init_config, &adc_handle); if (ret != ESP_OK) { ESP_LOGE(TAG, "Failed to initialize ADC unit: %s", esp_err_to_name(ret)); return ret; } adc_oneshot_chan_cfg_t channel_config = { .atten = ADC_ATTEN, .bitwidth = ADC_BITWIDTH, }; ret = adc_oneshot_config_channel(adc_handle, ADC_CHANNEL, &channel_config); if (ret != ESP_OK) { ESP_LOGE(TAG, "Failed to configure ADC channel: %s", esp_err_to_name(ret)); adc_oneshot_del_unit(adc_handle); // Cleanup in case of failure return ret; } adc_cali_curve_fitting_config_t cali_config = { .unit_id = ADC_UNIT, .chan = (adc_channel_t)ADC_CHANNEL, .atten = ADC_ATTEN, .bitwidth = ADC_BITWIDTH, }; if (adc_cali_create_scheme_curve_fitting(&cali_config, &cali_handle) == ESP_OK) { calibration_enabled = true; ESP_LOGI(TAG, "Calibration enabled using curve fitting"); } else { ESP_LOGW(TAG, "Calibration not supported on this device. Proceeding without calibration"); } ESP_LOGI(TAG, "ADC initialization successful"); return ESP_OK; } float battery_measurement_read(void) { int raw_reading = 0; int voltage = 0; // Read raw ADC value ESP_ERROR_CHECK(adc_oneshot_read(adc_handle, ADC_CHANNEL, &raw_reading)); if (calibration_enabled) { // Convert raw value to voltage using calibration ESP_ERROR_CHECK(adc_cali_raw_to_voltage(cali_handle, raw_reading, &voltage)); } else { // Approximate voltage calculation voltage = (raw_reading * REF_VOLTAGE) / (1 << ADC_BITWIDTH); } float battery_voltage = voltage * DIVIDER_RATIO / 1000.0; // Calculate battery voltage in volts // ESP_LOGI(TAG, "Raw ADC Value: %d, Voltage: %d mV, Battery Voltage: %.2f V", raw_reading, voltage, battery_voltage); return battery_voltage; } void battery_measurement_deinit(void) { if (calibration_enabled) { adc_cali_delete_scheme_curve_fitting(cali_handle); } if (adc_handle != NULL) { adc_oneshot_del_unit(adc_handle); } }
4,421
battery_measurement
c
en
c
code
{"qsc_code_num_words": 592, "qsc_code_num_chars": 4421.0, "qsc_code_mean_word_length": 4.68412162, "qsc_code_frac_words_unique": 0.27027027, "qsc_code_frac_chars_top_2grams": 0.04760188, "qsc_code_frac_chars_top_3grams": 0.02812838, "qsc_code_frac_chars_top_4grams": 0.01514605, "qsc_code_frac_chars_dupe_5grams": 0.15037865, "qsc_code_frac_chars_dupe_6grams": 0.11539849, "qsc_code_frac_chars_dupe_7grams": 0.02019473, "qsc_code_frac_chars_dupe_8grams": 0.02019473, "qsc_code_frac_chars_dupe_9grams": 0.02019473, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02389381, "qsc_code_frac_chars_whitespace": 0.23320516, "qsc_code_size_file_byte": 4421.0, "qsc_code_num_lines": 153.0, "qsc_code_num_chars_line_max": 123.0, "qsc_code_num_chars_line_mean": 28.89542484, "qsc_code_frac_chars_alphabet": 0.79410029, "qsc_code_frac_chars_comments": 0.19022846, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.15789474, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0871265, "qsc_code_frac_chars_long_word_length": 0.01870986, "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.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.10526316, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": 0.10526316}
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/T-Glass-Applications
ancs_app/main/ancs_app.c
/* * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Unlicense OR CC0-1.0 */ #include "ancs_app.h" #include <inttypes.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/event_groups.h" #include "esp_system.h" #include "esp_log.h" #include "esp_bt.h" #include "esp_gap_ble_api.h" #include "esp_gatts_api.h" #include "esp_bt_defs.h" #include "esp_bt_main.h" #include "esp_bt_device.h" #include "esp_gattc_api.h" #include "esp_gatt_defs.h" #include "esp_gatt_common_api.h" #include "ble_ancs.h" #include "esp_timer.h" #include "t_glass.h" #define BLE_ANCS_TAG "BLE_ANCS" #define EXAMPLE_DEVICE_NAME "T-Glass ANCS" #define PROFILE_A_APP_ID 0 #define PROFILE_NUM 1 #define ADV_CONFIG_FLAG (1 << 0) #define SCAN_RSP_CONFIG_FLAG (1 << 1) #define INVALID_HANDLE 0 static notification_callback_t user_callback = NULL; static NotificationAttributes notifications[MAX_NOTIFICATIONS]; static uint8_t adv_config_done = 0; static bool get_service = false; static esp_gattc_char_elem_t *char_elem_result = NULL; static esp_gattc_descr_elem_t *descr_elem_result = NULL; static void periodic_timer_callback(void *arg); esp_timer_handle_t periodic_timer; uint8_t notification_index = 0; const esp_timer_create_args_t periodic_timer_args = { .callback = &periodic_timer_callback, /* name is optional, but may help identify the timer when debugging */ .name = "periodic"}; struct data_source_buffer { uint8_t buffer[1024]; uint16_t len; }; static struct data_source_buffer data_buffer = {0}; // In its basic form, the ANCS exposes three characteristics: // service UUID: 7905F431-B5CE-4E99-A40F-4B1E122D00D0 uint8_t Apple_NC_UUID[16] = {0xD0, 0x00, 0x2D, 0x12, 0x1E, 0x4B, 0x0F, 0xA4, 0x99, 0x4E, 0xCE, 0xB5, 0x31, 0xF4, 0x05, 0x79}; // Notification Source UUID: 9FBF120D-6301-42D9-8C58-25E699A21DBD(notifiable) uint8_t notification_source[16] = {0xbd, 0x1d, 0xa2, 0x99, 0xe6, 0x25, 0x58, 0x8c, 0xd9, 0x42, 0x01, 0x63, 0x0d, 0x12, 0xbf, 0x9f}; // Control Point UUID:69D1D8F3-45E1-49A8-9821-9BBDFDAAD9D9(writeable with response) uint8_t control_point[16] = {0xd9, 0xd9, 0xaa, 0xfd, 0xbd, 0x9b, 0x21, 0x98, 0xa8, 0x49, 0xe1, 0x45, 0xf3, 0xd8, 0xd1, 0x69}; // Data Source UUID:22EAC6E9-24D6-4BB5-BE44-B36ACE7C7BFB(notifiable) uint8_t data_source[16] = {0xfb, 0x7b, 0x7c, 0xce, 0x6a, 0xb3, 0x44, 0xbe, 0xb5, 0x4b, 0xd6, 0x24, 0xe9, 0xc6, 0xea, 0x22}; /* Note: There may be more characteristics present in the ANCS than the three listed above. That said, an NC may ignore any characteristic it does not recognize. */ static void gattc_profile_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param); static esp_bt_uuid_t apple_nc_uuid = { .len = ESP_UUID_LEN_128, }; static uint8_t hidd_service_uuid128[] = { /* LSB <--------------------------------------------------------------------------------> MSB */ // first uuid, 16bit, [12],[13] is the value 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x12, 0x18, 0x00, 0x00, }; // config adv data static esp_ble_adv_data_t adv_config = { .set_scan_rsp = false, .include_txpower = false, .min_interval = 0x0006, // slave connection min interval, Time = min_interval * 1.25 msec .max_interval = 0x0010, // slave connection max interval, Time = max_interval * 1.25 msec .appearance = ESP_BLE_APPEARANCE_GENERIC_HID, .service_uuid_len = sizeof(hidd_service_uuid128), .p_service_uuid = hidd_service_uuid128, .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT), }; // config scan response data static esp_ble_adv_data_t scan_rsp_config = { .set_scan_rsp = true, .include_name = true, .manufacturer_len = 0, .p_manufacturer_data = NULL, }; static esp_ble_adv_params_t adv_params = { .adv_int_min = 0x100, .adv_int_max = 0x100, .adv_type = ADV_TYPE_IND, .own_addr_type = BLE_ADDR_TYPE_RPA_PUBLIC, .channel_map = ADV_CHNL_ALL, .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY, }; struct gattc_profile_inst { esp_gattc_cb_t gattc_cb; uint16_t gattc_if; uint16_t app_id; uint16_t conn_id; uint16_t service_start_handle; uint16_t service_end_handle; uint16_t notification_source_handle; uint16_t data_source_handle; uint16_t contol_point_handle; esp_bd_addr_t remote_bda; uint16_t MTU_size; }; static struct gattc_profile_inst gl_profile_tab[PROFILE_NUM] = { [PROFILE_A_APP_ID] = { .gattc_cb = gattc_profile_event_handler, .gattc_if = ESP_GATT_IF_NONE, /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */ }, }; esp_noti_attr_list_t p_attr[8] = { [attr_appidentifier_index] = { .noti_attribute_id = NotificationAttributeIDAppIdentifier, .attribute_len = 0, }, [attr_title_index] = { .noti_attribute_id = NotificationAttributeIDTitle, .attribute_len = 0xFFFF, }, [attr_subtitle_index] = { .noti_attribute_id = NotificationAttributeIDSubtitle, .attribute_len = 0xFFFF, }, [attr_message_index] = { .noti_attribute_id = NotificationAttributeIDMessage, .attribute_len = 0xFFFF, }, [attr_messagesize_index] = { .noti_attribute_id = NotificationAttributeIDMessageSize, .attribute_len = 0, }, [attr_date_index] = { .noti_attribute_id = NotificationAttributeIDDate, .attribute_len = 0, }, [attr_positiveactionlabel_index] = { .noti_attribute_id = NotificationAttributeIDPositiveActionLabel, .attribute_len = 0, }, [attr_negativeactionlabel_index] = { .noti_attribute_id = NotificationAttributeIDNegativeActionLabel, .attribute_len = 0, }, }; void esp_receive_apple_data_source_custom(uint8_t *message, uint16_t message_len) { if (!message || message_len == 0) { return; } // Ignore notifications if index exceeds MAX_NOTIFICATIONS if (notification_index >= MAX_NOTIFICATIONS) { ESP_LOGW(BLE_ANCS_TAG, "Notification ignored: MAX_NOTIFICATIONS reached."); return; } uint8_t Command_id = message[0]; switch (Command_id) { case CommandIDGetNotificationAttributes: { uint32_t NotificationUID = (message[1]) | (message[2] << 8) | (message[3] << 16) | (message[4] << 24); uint32_t remian_attr_len = message_len - 5; uint8_t *attrs = &message[5]; ESP_LOGI(BLE_ANCS_TAG, "recevice Notification Attributes response Command_id %d NotificationUID %" PRIu32, Command_id, NotificationUID); // Get the current notification slot NotificationAttributes *current_notification = &notifications[notification_index]; memset(current_notification, 0, sizeof(NotificationAttributes)); // Clear the slot current_notification->NotificationUID = NotificationUID; while (remian_attr_len > 0) { uint8_t AttributeID = attrs[0]; uint16_t len = attrs[1] | (attrs[2] << 8); if (len > (remian_attr_len - 3)) { ESP_LOGE(BLE_ANCS_TAG, "data error"); break; } switch (AttributeID) { case NotificationAttributeIDAppIdentifier: strncpy(current_notification->Identifier, (char *)&attrs[3], len); current_notification->Identifier[len] = '\0'; // Null-terminate break; case NotificationAttributeIDTitle: strncpy(current_notification->Title, (char *)&attrs[3], len); current_notification->Title[len] = '\0'; // Null-terminate break; case NotificationAttributeIDSubtitle: strncpy(current_notification->Subtitle, (char *)&attrs[3], len); current_notification->Subtitle[len] = '\0'; // Null-terminate break; case NotificationAttributeIDMessage: { char sanitized_message[len + 1]; int sanitized_len = 0; for (int i = 0; i < len; i++) { if (attrs[3 + i] == '\n') { sanitized_message[sanitized_len++] = ' '; // Replace newline with space } else { sanitized_message[sanitized_len++] = attrs[3 + i]; } } sanitized_message[sanitized_len] = '\0'; // Null-terminate // Append to the current message strncat(current_notification->Message, sanitized_message, sizeof(current_notification->Message) - strlen(current_notification->Message) - 1); break; } default: ESP_LOGW(BLE_ANCS_TAG, "Unknown attribute ID: %d", AttributeID); break; } attrs += (1 + 2 + len); remian_attr_len -= (1 + 2 + len); } ESP_LOGI(BLE_ANCS_TAG, "Notification stored: UID=%d, Identifier=%s, Title=%s, Subtitle=%s, Message=%s", (int)current_notification->NotificationUID, current_notification->Identifier, current_notification->Title, current_notification->Subtitle, current_notification->Message); ++notification_index; ESP_LOGI(BLE_ANCS_TAG, "NEXT Notification INDEX: %d", notification_index); // Call the callback function if it's registered if (user_callback != NULL) { user_callback(current_notification); // Pass the new notification to the callback } break; } case CommandIDGetAppAttributes: ESP_LOGI(BLE_ANCS_TAG, "recevice APP Attributes response"); break; case CommandIDPerformNotificationAction: ESP_LOGI(BLE_ANCS_TAG, "recevice Perform Notification Action"); break; default: ESP_LOGI(BLE_ANCS_TAG, "unknown Command ID"); break; } } /* | CommandID(1 Byte) | NotificationUID(4 Bytes) | AttributeIDs | */ void esp_get_notification_attributes(uint8_t *notificationUID, uint8_t num_attr, esp_noti_attr_list_t *p_attr) { uint8_t cmd[600] = {0}; uint32_t index = 0; cmd[0] = CommandIDGetNotificationAttributes; index++; memcpy(&cmd[index], notificationUID, ESP_NOTIFICATIONUID_LEN); index += ESP_NOTIFICATIONUID_LEN; while (num_attr > 0) { cmd[index++] = p_attr->noti_attribute_id; if (p_attr->attribute_len > 0) { cmd[index++] = p_attr->attribute_len; cmd[index++] = (p_attr->attribute_len << 8); } p_attr++; num_attr--; } esp_ble_gattc_write_char(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, gl_profile_tab[PROFILE_A_APP_ID].contol_point_handle, index, cmd, ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE); } void esp_get_app_attributes(uint8_t *appidentifier, uint16_t appidentifier_len, uint8_t num_attr, uint8_t *p_app_attrs) { uint8_t buffer[600] = {0}; uint32_t index = 0; buffer[0] = CommandIDGetAppAttributes; index++; memcpy(&buffer[index], appidentifier, appidentifier_len); index += appidentifier_len; memcpy(&buffer[index], p_app_attrs, num_attr); index += num_attr; esp_ble_gattc_write_char(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, gl_profile_tab[PROFILE_A_APP_ID].contol_point_handle, index, buffer, ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE); } void esp_perform_notification_action(uint8_t *notificationUID, uint8_t ActionID) { uint8_t buffer[600] = {0}; uint32_t index = 0; buffer[0] = CommandIDPerformNotificationAction; index++; memcpy(&buffer[index], notificationUID, ESP_NOTIFICATIONUID_LEN); index += ESP_NOTIFICATIONUID_LEN; buffer[index] = ActionID; index++; esp_ble_gattc_write_char(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, gl_profile_tab[PROFILE_A_APP_ID].contol_point_handle, index, buffer, ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE); } static void periodic_timer_callback(void *arg) { esp_timer_stop(periodic_timer); if (data_buffer.len > 0) { esp_receive_apple_data_source_custom(data_buffer.buffer, data_buffer.len); memset(data_buffer.buffer, 0, data_buffer.len); data_buffer.len = 0; } } static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) { ESP_LOGV(BLE_ANCS_TAG, "GAP_EVT, event %d", event); switch (event) { case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: adv_config_done &= (~SCAN_RSP_CONFIG_FLAG); if (adv_config_done == 0) { esp_ble_gap_start_advertising(&adv_params); } break; case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: adv_config_done &= (~ADV_CONFIG_FLAG); if (adv_config_done == 0) { esp_ble_gap_start_advertising(&adv_params); } break; case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: // advertising start complete event to indicate advertising start successfully or failed if (param->adv_start_cmpl.status != ESP_BT_STATUS_SUCCESS) { ESP_LOGE(BLE_ANCS_TAG, "advertising start failed, error status = %x", param->adv_start_cmpl.status); break; } ESP_LOGI(BLE_ANCS_TAG, "advertising start success"); break; case ESP_GAP_BLE_PASSKEY_REQ_EVT: /* passkey request event */ ESP_LOGI(BLE_ANCS_TAG, "ESP_GAP_BLE_PASSKEY_REQ_EVT"); /* Call the following function to input the passkey which is displayed on the remote device */ // esp_ble_passkey_reply(heart_rate_profile_tab[HEART_PROFILE_APP_IDX].remote_bda, true, 0x00); break; case ESP_GAP_BLE_OOB_REQ_EVT: { ESP_LOGI(BLE_ANCS_TAG, "ESP_GAP_BLE_OOB_REQ_EVT"); uint8_t tk[16] = {1}; // If you paired with OOB, both devices need to use the same tk esp_ble_oob_req_reply(param->ble_security.ble_req.bd_addr, tk, sizeof(tk)); break; } case ESP_GAP_BLE_NC_REQ_EVT: /* The app will receive this evt when the IO has DisplayYesNO capability and the peer device IO also has DisplayYesNo capability. show the passkey number to the user to confirm it with the number displayed by peer device. */ esp_ble_confirm_reply(param->ble_security.ble_req.bd_addr, true); ESP_LOGI(BLE_ANCS_TAG, "ESP_GAP_BLE_NC_REQ_EVT, the passkey Notify number:%" PRIu32, param->ble_security.key_notif.passkey); break; case ESP_GAP_BLE_SEC_REQ_EVT: /* send the positive(true) security response to the peer device to accept the security request. If not accept the security request, should send the security response with negative(false) accept value*/ esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, true); break; case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: /// the app will receive this evt when the IO has Output capability and the peer device IO has Input capability. /// show the passkey number to the user to input it in the peer device. ESP_LOGI(BLE_ANCS_TAG, "The passkey Notify number:%06" PRIu32, param->ble_security.key_notif.passkey); break; case ESP_GAP_BLE_AUTH_CMPL_EVT: { esp_log_buffer_hex("addr", param->ble_security.auth_cmpl.bd_addr, ESP_BD_ADDR_LEN); ESP_LOGI(BLE_ANCS_TAG, "pair status = %s", param->ble_security.auth_cmpl.success ? "success" : "fail"); lv_gui_ble_status(param->ble_security.auth_cmpl.success); if (!param->ble_security.auth_cmpl.success) { ESP_LOGI(BLE_ANCS_TAG, "fail reason = 0x%x", param->ble_security.auth_cmpl.fail_reason); } break; } case ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT: if (param->local_privacy_cmpl.status != ESP_BT_STATUS_SUCCESS) { ESP_LOGE(BLE_ANCS_TAG, "config local privacy failed, error status = %x", param->local_privacy_cmpl.status); break; } esp_err_t ret = esp_ble_gap_config_adv_data(&adv_config); if (ret) { ESP_LOGE(BLE_ANCS_TAG, "config adv data failed, error code = %x", ret); } else { adv_config_done |= ADV_CONFIG_FLAG; } ret = esp_ble_gap_config_adv_data(&scan_rsp_config); if (ret) { ESP_LOGE(BLE_ANCS_TAG, "config adv data failed, error code = %x", ret); } else { adv_config_done |= SCAN_RSP_CONFIG_FLAG; } break; default: break; } } static void gattc_profile_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) { switch (event) { case ESP_GATTC_REG_EVT: ESP_LOGI(BLE_ANCS_TAG, "REG_EVT"); esp_ble_gap_set_device_name(EXAMPLE_DEVICE_NAME); esp_ble_gap_config_local_icon(ESP_BLE_APPEARANCE_GENERIC_WATCH); // generate a resolvable random address esp_ble_gap_config_local_privacy(true); break; case ESP_GATTC_OPEN_EVT: if (param->open.status != ESP_GATT_OK) { ESP_LOGE(BLE_ANCS_TAG, "open failed, error status = %x", param->open.status); break; } ESP_LOGI(BLE_ANCS_TAG, "ESP_GATTC_OPEN_EVT"); gl_profile_tab[PROFILE_A_APP_ID].conn_id = param->open.conn_id; esp_ble_set_encryption(param->open.remote_bda, ESP_BLE_SEC_ENCRYPT_MITM); esp_err_t mtu_ret = esp_ble_gattc_send_mtu_req(gattc_if, param->open.conn_id); if (mtu_ret) { ESP_LOGE(BLE_ANCS_TAG, "config MTU error, error code = %x", mtu_ret); } break; case ESP_GATTC_CFG_MTU_EVT: if (param->cfg_mtu.status != ESP_GATT_OK) { ESP_LOGE(BLE_ANCS_TAG, "config mtu failed, error status = %x", param->cfg_mtu.status); } ESP_LOGI(BLE_ANCS_TAG, "ESP_GATTC_CFG_MTU_EVT, Status %d, MTU %d, conn_id %d", param->cfg_mtu.status, param->cfg_mtu.mtu, param->cfg_mtu.conn_id); gl_profile_tab[PROFILE_A_APP_ID].MTU_size = param->cfg_mtu.mtu; memcpy(apple_nc_uuid.uuid.uuid128, Apple_NC_UUID, 16); esp_ble_gattc_search_service(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, &apple_nc_uuid); break; case ESP_GATTC_SEARCH_RES_EVT: { if (param->search_res.srvc_id.uuid.len == ESP_UUID_LEN_128) { gl_profile_tab[PROFILE_A_APP_ID].service_start_handle = param->search_res.start_handle; gl_profile_tab[PROFILE_A_APP_ID].service_end_handle = param->search_res.end_handle; get_service = true; } break; } case ESP_GATTC_SEARCH_CMPL_EVT: if (param->search_cmpl.status != ESP_GATT_OK) { ESP_LOGE(BLE_ANCS_TAG, "search service failed, error status = %x", param->search_cmpl.status); break; } ESP_LOGI(BLE_ANCS_TAG, "ESP_GATTC_SEARCH_CMPL_EVT"); if (get_service) { uint16_t count = 0; uint16_t offset = 0; esp_gatt_status_t ret_status = esp_ble_gattc_get_attr_count(gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, ESP_GATT_DB_CHARACTERISTIC, gl_profile_tab[PROFILE_A_APP_ID].service_start_handle, gl_profile_tab[PROFILE_A_APP_ID].service_end_handle, INVALID_HANDLE, &count); if (ret_status != ESP_GATT_OK) { ESP_LOGE(BLE_ANCS_TAG, "esp_ble_gattc_get_attr_count error, %d", __LINE__); break; } if (count > 0) { char_elem_result = (esp_gattc_char_elem_t *)malloc(sizeof(esp_gattc_char_elem_t) * count); if (!char_elem_result) { ESP_LOGE(BLE_ANCS_TAG, "gattc no mem"); break; } else { memset(char_elem_result, 0xff, sizeof(esp_gattc_char_elem_t) * count); ret_status = esp_ble_gattc_get_all_char(gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, gl_profile_tab[PROFILE_A_APP_ID].service_start_handle, gl_profile_tab[PROFILE_A_APP_ID].service_end_handle, char_elem_result, &count, offset); if (ret_status != ESP_GATT_OK) { ESP_LOGE(BLE_ANCS_TAG, "esp_ble_gattc_get_all_char error, %d", __LINE__); free(char_elem_result); char_elem_result = NULL; break; } if (count > 0) { for (int i = 0; i < count; i++) { if (char_elem_result[i].uuid.len == ESP_UUID_LEN_128) { if (char_elem_result[i].properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY && memcmp(char_elem_result[i].uuid.uuid.uuid128, notification_source, 16) == 0) { gl_profile_tab[PROFILE_A_APP_ID].notification_source_handle = char_elem_result[i].char_handle; esp_ble_gattc_register_for_notify(gattc_if, gl_profile_tab[PROFILE_A_APP_ID].remote_bda, char_elem_result[i].char_handle); ESP_LOGI(BLE_ANCS_TAG, "Find Apple noticification source char"); } else if (char_elem_result[i].properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY && memcmp(char_elem_result[i].uuid.uuid.uuid128, data_source, 16) == 0) { gl_profile_tab[PROFILE_A_APP_ID].data_source_handle = char_elem_result[i].char_handle; esp_ble_gattc_register_for_notify(gattc_if, gl_profile_tab[PROFILE_A_APP_ID].remote_bda, char_elem_result[i].char_handle); ESP_LOGI(BLE_ANCS_TAG, "Find Apple data source char"); } else if (char_elem_result[i].properties & ESP_GATT_CHAR_PROP_BIT_WRITE && memcmp(char_elem_result[i].uuid.uuid.uuid128, control_point, 16) == 0) { gl_profile_tab[PROFILE_A_APP_ID].contol_point_handle = char_elem_result[i].char_handle; ESP_LOGI(BLE_ANCS_TAG, "Find Apple control point char"); } } } } } free(char_elem_result); char_elem_result = NULL; } } else { ESP_LOGE(BLE_ANCS_TAG, "No Apple Notification Service found"); } break; case ESP_GATTC_REG_FOR_NOTIFY_EVT: { if (param->reg_for_notify.status != ESP_GATT_OK) { ESP_LOGI(BLE_ANCS_TAG, "ESP_GATTC_REG_FOR_NOTIFY_EVT status %d", param->reg_for_notify.status); break; } uint16_t count = 0; uint16_t offset = 0; // uint16_t notify_en = 1; uint8_t notify_en[2] = {0x01, 0x00}; esp_gatt_status_t ret_status = esp_ble_gattc_get_attr_count(gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, ESP_GATT_DB_DESCRIPTOR, gl_profile_tab[PROFILE_A_APP_ID].service_start_handle, gl_profile_tab[PROFILE_A_APP_ID].service_end_handle, param->reg_for_notify.handle, &count); if (ret_status != ESP_GATT_OK) { ESP_LOGE(BLE_ANCS_TAG, "esp_ble_gattc_get_attr_count error, %d", __LINE__); break; } if (count > 0) { descr_elem_result = malloc(sizeof(esp_gattc_descr_elem_t) * count); if (!descr_elem_result) { ESP_LOGE(BLE_ANCS_TAG, "malloc error, gattc no mem"); break; } else { ret_status = esp_ble_gattc_get_all_descr(gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, param->reg_for_notify.handle, descr_elem_result, &count, offset); if (ret_status != ESP_GATT_OK) { ESP_LOGE(BLE_ANCS_TAG, "esp_ble_gattc_get_all_descr error, %d", __LINE__); free(descr_elem_result); descr_elem_result = NULL; break; } for (int i = 0; i < count; ++i) { if (descr_elem_result[i].uuid.len == ESP_UUID_LEN_16 && descr_elem_result[i].uuid.uuid.uuid16 == ESP_GATT_UUID_CHAR_CLIENT_CONFIG) { esp_ble_gattc_write_char_descr(gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, descr_elem_result[i].handle, sizeof(notify_en), (uint8_t *)&notify_en, ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE); break; } } } free(descr_elem_result); descr_elem_result = NULL; } break; } case ESP_GATTC_NOTIFY_EVT: // esp_log_buffer_hex(BLE_ANCS_TAG, param->notify.value, param->notify.value_len); if (param->notify.handle == gl_profile_tab[PROFILE_A_APP_ID].notification_source_handle) { esp_receive_apple_notification_source(param->notify.value, param->notify.value_len); uint8_t *notificationUID = &param->notify.value[4]; // if (param->notify.value[0] == EventIDNotificationAdded && param->notify.value[2] == CategoryIDIncomingCall) { // ESP_LOGI(BLE_ANCS_TAG, "IncomingCall, reject"); // //Call reject // esp_perform_notification_action(notificationUID, ActionIDNegative); // } else if (param->notify.value[0] == EventIDNotificationAdded) { // get more information ESP_LOGI(BLE_ANCS_TAG, "Get detailed information"); esp_get_notification_attributes(notificationUID, sizeof(p_attr) / sizeof(esp_noti_attr_list_t), p_attr); } else if (param->notify.value[0] == EventIDNotificationRemoved) { // get more information ESP_LOGI(BLE_ANCS_TAG, "Removed message"); } } else if (param->notify.handle == gl_profile_tab[PROFILE_A_APP_ID].data_source_handle) { memcpy(&data_buffer.buffer[data_buffer.len], param->notify.value, param->notify.value_len); data_buffer.len += param->notify.value_len; if (param->notify.value_len == (gl_profile_tab[PROFILE_A_APP_ID].MTU_size - 3)) { // copy and wait next packet, start timer 500ms esp_timer_start_periodic(periodic_timer, 500000); } else { esp_timer_stop(periodic_timer); esp_receive_apple_data_source_custom(data_buffer.buffer, data_buffer.len); memset(data_buffer.buffer, 0, data_buffer.len); data_buffer.len = 0; } } else { ESP_LOGI(BLE_ANCS_TAG, "unknown handle, receive notify value:"); } break; case ESP_GATTC_WRITE_DESCR_EVT: if (param->write.status != ESP_GATT_OK) { ESP_LOGE(BLE_ANCS_TAG, "write descr failed, error status = %x", param->write.status); break; } // ESP_LOGI(BLE_ANCS_TAG, "write descr successfully"); break; case ESP_GATTC_SRVC_CHG_EVT: { ESP_LOGI(BLE_ANCS_TAG, "ESP_GATTC_SRVC_CHG_EVT, bd_addr:"); esp_log_buffer_hex(BLE_ANCS_TAG, param->srvc_chg.remote_bda, 6); break; } case ESP_GATTC_WRITE_CHAR_EVT: if (param->write.status != ESP_GATT_OK) { char *Errstr = Errcode_to_String(param->write.status); if (Errstr) { ESP_LOGE(BLE_ANCS_TAG, "write control point error %s", Errstr); } break; } // ESP_LOGI(BLE_ANCS_TAG, "Write char success "); break; case ESP_GATTC_DISCONNECT_EVT: ESP_LOGI(BLE_ANCS_TAG, "ESP_GATTC_DISCONNECT_EVT, reason = 0x%x", param->disconnect.reason); get_service = false; esp_ble_gap_start_advertising(&adv_params); lv_gui_ble_status(false); break; case ESP_GATTC_CONNECT_EVT: // ESP_LOGI(BLE_ANCS_TAG, "ESP_GATTC_CONNECT_EVT"); // esp_log_buffer_hex("bda", param->connect.remote_bda, 6); memcpy(gl_profile_tab[PROFILE_A_APP_ID].remote_bda, param->connect.remote_bda, 6); // create gattc virtual connection esp_ble_gattc_open(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, gl_profile_tab[PROFILE_A_APP_ID].remote_bda, BLE_ADDR_TYPE_RANDOM, true); break; case ESP_GATTC_DIS_SRVC_CMPL_EVT: ESP_LOGI(BLE_ANCS_TAG, "ESP_GATTC_DIS_SRVC_CMPL_EVT"); break; default: break; } } static void esp_gattc_cb(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) { /* If event is register event, store the gattc_if for each profile */ if (event == ESP_GATTC_REG_EVT) { if (param->reg.status == ESP_GATT_OK) { gl_profile_tab[param->reg.app_id].gattc_if = gattc_if; } else { ESP_LOGI(BLE_ANCS_TAG, "Reg app failed, app_id %04x, status %d", param->reg.app_id, param->reg.status); return; } } /* If the gattc_if equal to profile A, call profile A cb handler, * so here call each profile's callback */ do { int idx; for (idx = 0; idx < PROFILE_NUM; idx++) { if (gattc_if == ESP_GATT_IF_NONE || /* ESP_GATT_IF_NONE, not specify a certain gatt_if, need to call every profile cb function */ gattc_if == gl_profile_tab[idx].gattc_if) { if (gl_profile_tab[idx].gattc_cb) { gl_profile_tab[idx].gattc_cb(event, gattc_if, param); } } } } while (0); } void init_timer(void) { ESP_ERROR_CHECK(esp_timer_create(&periodic_timer_args, &periodic_timer)); } void ancs_app(notification_callback_t callback) { esp_err_t ret; user_callback = callback; // Store the user-defined callback // init timer init_timer(); ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT)); esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); ret = esp_bt_controller_init(&bt_cfg); if (ret) { ESP_LOGE(BLE_ANCS_TAG, "%s init controller failed: %s", __func__, esp_err_to_name(ret)); return; } ret = esp_bt_controller_enable(ESP_BT_MODE_BLE); if (ret) { ESP_LOGE(BLE_ANCS_TAG, "%s enable controller failed: %s", __func__, esp_err_to_name(ret)); return; } ESP_LOGI(BLE_ANCS_TAG, "%s init bluetooth", __func__); ret = esp_bluedroid_init(); if (ret) { ESP_LOGE(BLE_ANCS_TAG, "%s init bluetooth failed: %s", __func__, esp_err_to_name(ret)); return; } ret = esp_bluedroid_enable(); if (ret) { ESP_LOGE(BLE_ANCS_TAG, "%s enable bluetooth failed: %s", __func__, esp_err_to_name(ret)); return; } // register the callback function to the gattc module ret = esp_ble_gattc_register_callback(esp_gattc_cb); if (ret) { ESP_LOGE(BLE_ANCS_TAG, "%s gattc register error, error code = %x", __func__, ret); return; } ret = esp_ble_gap_register_callback(gap_event_handler); if (ret) { ESP_LOGE(BLE_ANCS_TAG, "gap register error, error code = %x", ret); return; } ret = esp_ble_gattc_app_register(PROFILE_A_APP_ID); if (ret) { ESP_LOGE(BLE_ANCS_TAG, "%s gattc app register error, error code = %x", __func__, ret); } ret = esp_ble_gatt_set_local_mtu(500); if (ret) { ESP_LOGE(BLE_ANCS_TAG, "set local MTU failed, error code = %x", ret); } /* set the security iocap & auth_req & key size & init key response key parameters to the stack*/ esp_ble_auth_req_t auth_req = ESP_LE_AUTH_REQ_SC_MITM_BOND; // bonding with peer device after authentication esp_ble_io_cap_t iocap = ESP_IO_CAP_NONE; // set the IO capability to No output No input uint8_t key_size = 16; // the key size should be 7~16 bytes uint8_t init_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK; uint8_t rsp_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK; // set static passkey uint32_t passkey = 123456; uint8_t auth_option = ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_DISABLE; uint8_t oob_support = ESP_BLE_OOB_DISABLE; esp_ble_gap_set_security_param(ESP_BLE_SM_SET_STATIC_PASSKEY, &passkey, sizeof(uint32_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &auth_req, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &key_size, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH, &auth_option, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_OOB_SUPPORT, &oob_support, sizeof(uint8_t)); /* If your BLE device acts as a Slave, the init_key means you hope which types of key of the master should distribute to you, and the response key means which key you can distribute to the master; If your BLE device acts as a master, the response key means you hope which types of key of the slave should distribute to you, and the init key means which key you can distribute to the slave. */ esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &init_key, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &rsp_key, sizeof(uint8_t)); }
37,141
ancs_app
c
en
c
code
{"qsc_code_num_words": 4541, "qsc_code_num_chars": 37141.0, "qsc_code_mean_word_length": 4.43470601, "qsc_code_frac_words_unique": 0.12332085, "qsc_code_frac_chars_top_2grams": 0.02085609, "qsc_code_frac_chars_top_3grams": 0.03227729, "qsc_code_frac_chars_top_4grams": 0.02582183, "qsc_code_frac_chars_dupe_5grams": 0.47919356, "qsc_code_frac_chars_dupe_6grams": 0.41449002, "qsc_code_frac_chars_dupe_7grams": 0.34789949, "qsc_code_frac_chars_dupe_8grams": 0.30325752, "qsc_code_frac_chars_dupe_9grams": 0.26576621, "qsc_code_frac_chars_dupe_10grams": 0.21893932, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02375494, "qsc_code_frac_chars_whitespace": 0.31881209, "qsc_code_size_file_byte": 37141.0, "qsc_code_num_lines": 915.0, "qsc_code_num_chars_line_max": 179.0, "qsc_code_num_chars_line_mean": 40.59125683, "qsc_code_frac_chars_alphabet": 0.77221344, "qsc_code_frac_chars_comments": 0.11612504, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.26390686, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00129366, "qsc_code_frac_chars_string_length": 0.06655903, "qsc_code_frac_chars_long_word_length": 0.01145364, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.01133179, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.01552393, "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.0530401, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": 0.03880983}
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/vector/vimageloader.cpp
#include "vimageloader.h" #include "config.h" #include "vdebug.h" #include <cstring> #ifdef _WIN32 #include <windows.h> #elif !defined(ESP_PLATFORM) #include <dlfcn.h> #endif using lottie_image_load_f = unsigned char * (*)(const char *filename, int *x, int *y, int *comp, int req_comp); using lottie_image_load_data_f = unsigned char *(*)(const char *data, int len, int *x, int *y, int *comp, int req_comp); using lottie_image_free_f = void (*)(unsigned char *); #ifdef __cplusplus extern "C" { #endif extern unsigned char *lottie_image_load(char const *filename, int *x, int *y, int *comp, int req_comp); extern unsigned char *lottie_image_load_from_data(const char *imageData, int len, int *x, int *y, int *comp, int req_comp); extern void lottie_image_free(unsigned char *data); #ifdef __cplusplus } #endif struct VImageLoader::Impl { lottie_image_load_f imageLoad{nullptr}; lottie_image_free_f imageFree{nullptr}; lottie_image_load_data_f imageFromData{nullptr}; #ifdef LOTTIE_IMAGE_MODULE_SUPPORT # ifdef _WIN32 HMODULE dl_handle{nullptr}; bool moduleLoad() { dl_handle = LoadLibraryA(LOTTIE_IMAGE_MODULE_PLUGIN); return (dl_handle == nullptr); } void moduleFree() { if (dl_handle) FreeLibrary(dl_handle); } void init() { imageLoad = reinterpret_cast<lottie_image_load_f>( GetProcAddress(dl_handle, "lottie_image_load")); imageFree = reinterpret_cast<lottie_image_free_f>( GetProcAddress(dl_handle, "lottie_image_free")); imageFromData = reinterpret_cast<lottie_image_load_data_f>( GetProcAddress(dl_handle, "lottie_image_load_from_data")); } # else // _WIN32 void *dl_handle{nullptr}; void init() { imageLoad = reinterpret_cast<lottie_image_load_f>( dlsym(dl_handle, "lottie_image_load")); imageFree = reinterpret_cast<lottie_image_free_f>( dlsym(dl_handle, "lottie_image_free")); imageFromData = reinterpret_cast<lottie_image_load_data_f>( dlsym(dl_handle, "lottie_image_load_from_data")); } void moduleFree() { if (dl_handle) dlclose(dl_handle); } bool moduleLoad() { dl_handle = dlopen(LOTTIE_IMAGE_MODULE_PLUGIN, RTLD_LAZY); return (dl_handle == nullptr); } # endif // _WIN32 #else // LOTTIE_IMAGE_MODULE_SUPPORT void init() { imageLoad = lottie_image_load; imageFree = lottie_image_free; imageFromData = lottie_image_load_from_data; } void moduleFree() {} bool moduleLoad() { return false; } #endif // LOTTIE_IMAGE_MODULE_SUPPORT Impl() { if (moduleLoad()) { vWarning << "Failed to dlopen librlottie-image-loader library"; return; } init(); if (!imageLoad) vWarning << "Failed to find symbol lottie_image_load in " "librlottie-image-loader library"; if (!imageFree) vWarning << "Failed to find symbol lottie_image_free in " "librlottie-image-loader library"; if (!imageFromData) vWarning << "Failed to find symbol lottie_image_load_data in " "librlottie-image-loader library"; } ~Impl() { moduleFree(); } VBitmap createBitmap(unsigned char *data, int width, int height, int channel) { // premultiply alpha if (channel == 4) convertToBGRAPremul(data, width, height); else convertToBGRA(data, width, height); // create a bitmap of same size. VBitmap result = VBitmap(width, height, VBitmap::Format::ARGB32_Premultiplied); // copy the data to bitmap buffer memcpy(result.data(), data, width * height * 4); // free the image data imageFree(data); return result; } VBitmap load(const char *fileName) { if (!imageLoad) return VBitmap(); int width, height, n; unsigned char *data = imageLoad(fileName, &width, &height, &n, 4); if (!data) { return VBitmap(); } return createBitmap(data, width, height, n); } VBitmap load(const char *imageData, size_t len) { if (!imageFromData) return VBitmap(); int width, height, n; unsigned char *data = imageFromData(imageData, static_cast<int>(len), &width, &height, &n, 4); if (!data) { return VBitmap(); } return createBitmap(data, width, height, n); } /* * convert from RGBA to BGRA and premultiply */ void convertToBGRAPremul(unsigned char *bits, int width, int height) { int pixelCount = width * height; unsigned char *pix = bits; for (int i = 0; i < pixelCount; i++) { unsigned char r = pix[0]; unsigned char g = pix[1]; unsigned char b = pix[2]; unsigned char a = pix[3]; r = (r * a) / 255; g = (g * a) / 255; b = (b * a) / 255; pix[0] = b; pix[1] = g; pix[2] = r; pix += 4; } } /* * convert from RGBA to BGRA */ void convertToBGRA(unsigned char *bits, int width, int height) { int pixelCount = width * height; unsigned char *pix = bits; for (int i = 0; i < pixelCount; i++) { unsigned char r = pix[0]; unsigned char b = pix[2]; pix[0] = b; pix[2] = r; pix += 4; } } }; VImageLoader::VImageLoader() : mImpl(std::make_unique<VImageLoader::Impl>()) {} VImageLoader::~VImageLoader() {} VBitmap VImageLoader::load(const char *fileName) { return mImpl->load(fileName); } VBitmap VImageLoader::load(const char *data, size_t len) { return mImpl->load(data, int(len)); }
6,356
vimageloader
cpp
en
cpp
code
{"qsc_code_num_words": 683, "qsc_code_num_chars": 6356.0, "qsc_code_mean_word_length": 4.99267936, "qsc_code_frac_words_unique": 0.18301611, "qsc_code_frac_chars_top_2grams": 0.10322581, "qsc_code_frac_chars_top_3grams": 0.07917889, "qsc_code_frac_chars_top_4grams": 0.0457478, "qsc_code_frac_chars_dupe_5grams": 0.50703812, "qsc_code_frac_chars_dupe_6grams": 0.41612903, "qsc_code_frac_chars_dupe_7grams": 0.37419355, "qsc_code_frac_chars_dupe_8grams": 0.31906158, "qsc_code_frac_chars_dupe_9grams": 0.29501466, "qsc_code_frac_chars_dupe_10grams": 0.24105572, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00903256, "qsc_code_frac_chars_whitespace": 0.33810573, "qsc_code_size_file_byte": 6356.0, "qsc_code_num_lines": 222.0, "qsc_code_num_chars_line_max": 85.0, "qsc_code_num_chars_line_mean": 28.63063063, "qsc_code_frac_chars_alphabet": 0.80152127, "qsc_code_frac_chars_comments": 0.04641284, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.29310345, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.07061541, "qsc_code_frac_chars_long_word_length": 0.0277182, "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.12643678, "qsc_codecpp_frac_lines_func_ratio": 0.14367816, "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.18965517, "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}
000linlin/ConsisLoRA
README.md
# ConsisLoRA: Enhancing Content and Style Consistency for LoRA-based Style Transfer <a href='https://ConsisLoRA.github.io/'><img src='https://img.shields.io/badge/Project-Page-green'></a> <a href='https://arxiv.org/abs/2503.10614'><img src='https://img.shields.io/badge/arXiv-2503.10614-b31b1b.svg'></a> This repository contains the reference source code for the paper [ConsisLoRA: Enhancing Content and Style Consistency for LoRA-based Style Transfer](https://arxiv.org/pdf/2503.10614). ![teaser](assets/teaser.png) ## 🔥 News - **2025/03/24**: We release the inference code and LoRA checkpoints (see [here](https://huggingface.co/chenblin26)). ## ⏳ TODOs - [x] Release the inference code. - [ ] Release the training code. ## Getting Started This code was tested with Python 3.11, Pytorch 2.1 and Diffusers 0.31. ### Installation ```bash git clone https://github.com/000linlin/ConsisLoRA.git cd consislora conda create -n consislora python=3.11 conda activate consislora pip install -r requirements.txt ``` ### 1. Train ConsisLoRA for content and style image Waiting for training code release. ### 2. Inference - For style transfer, run: ``` python inference.py \ --prompt "a [c] in the style of [v]" \ --content_image_lora_path "path/to/content" \ --style_image_lora_path "path/to/style" \ --lora_scaling 1. 1. \ --guidance_scale 7.5 \ --output_dir "inference-images" \ --num_images_per_prompt 1 \ --num_steps 30 ``` Note that some additional parameters can be set for two guidance (see [Section 4.3](https://arxiv.org/pdf/2503.10614) of our paper). 1. `--content_guidance_scale`, `--style_guidance_scale` for controlling the strength of two guidance. Turning on the guidance will increase the inference time. 2. `--add_positive_content_prompt`, `--add_negative_content_prompt` is positive and negative prompts for content guidance, respectively. e.g, you can set `a [c]` and `a [v]` for them. 3. `--add_positive_style_prompt`, `--add_negative_style_prompt` is positive and negative prompts for style guidance, respectively. e.g, you can set `in the style of [v]` and `in the style of [c]` for them. - For using the content LoRA separately, run: ``` python inference.py \ --prompt "a [c] in pixel art style" \ --content_image_lora_path "path/to/content" \ --lora_scaling 1. 0. ``` - For using the style LoRA separately, run: ``` python inference.py \ --prompt "a dog in the style of [v]" \ --style_image_lora_path "path/to/style" \ --lora_scaling 0. 1. ``` See the [**inference_demo**][inference] notebook for more details on how to generate stylized images. ## Demos For more results, please visit our <a href="https://ConsisLoRA.github.io/"><strong>Project page</strong></a>. ![results](assets/results.png) ## Acknowledgements Our code mainly bases on [B-LoRA](https://github.com/yardenfren1996/B-LoRA) and [diffusers](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth_lora_sdxl.py). A huge thank you to the authors for their valuable contributions. ## Citation If you use this code, please consider citing our paper: ```bibtex @article{chen2025consislora, title={ConsisLoRA: Enhancing Content and Style Consistency for LoRA-based Style Transfer}, author={Bolin Chen, Baoquan Zhao, Haoran Xie, Yi Cai, Qing Li and Xudong Mao}, journal={arXiv preprint arXiv:2503.10614}, year={2025} } ``` [inference]: inference_demo.ipynb
3,474
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.00287853, "qsc_doc_frac_words_redpajama_stop": 0.16985951, "qsc_doc_num_sentences": 67.0, "qsc_doc_num_words": 518, "qsc_doc_num_chars": 3474.0, "qsc_doc_num_lines": 90.0, "qsc_doc_mean_word_length": 4.77992278, "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.38803089, "qsc_doc_entropy_unigram": 4.84643455, "qsc_doc_frac_words_all_caps": 0.00383142, "qsc_doc_frac_lines_dupe_lines": 0.21126761, "qsc_doc_frac_chars_dupe_lines": 0.07867558, "qsc_doc_frac_chars_top_2grams": 0.01817447, "qsc_doc_frac_chars_top_3grams": 0.02423263, "qsc_doc_frac_chars_top_4grams": 0.01938611, "qsc_doc_frac_chars_dupe_5grams": 0.32552504, "qsc_doc_frac_chars_dupe_6grams": 0.31058158, "qsc_doc_frac_chars_dupe_7grams": 0.2677706, "qsc_doc_frac_chars_dupe_8grams": 0.16357027, "qsc_doc_frac_chars_dupe_9grams": 0.11712439, "qsc_doc_frac_chars_dupe_10grams": 0.08481422, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 20.99367089, "qsc_doc_frac_chars_hyperlink_html_tag": 0.15169833, "qsc_doc_frac_chars_alphabet": 0.79946073, "qsc_doc_frac_chars_digital": 0.03437816, "qsc_doc_frac_chars_whitespace": 0.14594128, "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}
000haoji/deep-student
src/chat-core/styles/chat.css
/** * Chat Core Styles - 聊天界面核心样式 * 提取自原项目中所有聊天相关的样式 */ /* ============================================================================ 聊天容器 - Chat Container ============================================================================ */ .chat-container { display: flex; flex-direction: column; height: 100%; background: white; border-radius: 100px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); overflow: hidden; transition: all 0.3s ease; } .chat-container.chat-fullscreen { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 1000; border-radius: 0; box-shadow: none; background: white; } .chat-header { padding: 1rem 1.5rem; border-bottom: 1px solid #e0e0e0; background: #f8f9fa; display: flex; justify-content: space-between; align-items: center; min-height: 60px; } .chat-header h3, .chat-header h4 { margin: 0; font-size: 1.1rem; color: #333; font-weight: 600; } .chat-header-actions { display: flex; align-items: center; gap: 10px; } .chat-fullscreen-toggle { background: none; border: none; font-size: 1.2rem; cursor: pointer; color: #666; padding: 0.25rem 0.5rem; border-radius: 4px; transition: all 0.2s; } .chat-fullscreen-toggle:hover { background-color: #e0e0e0; color: #333; } .chain-indicator { display: flex; align-items: center; gap: 0.5rem; font-size: 0.9rem; color: #666; background: #f0f8ff; padding: 0.25rem 0.75rem; border-radius: 12px; border: 1px solid #e0e7ff; } /* ============================================================================ 聊天历史 - Chat History ============================================================================ */ .chat-history { flex: 1; overflow-y: auto; padding: 1rem; display: flex; flex-direction: column; gap: 1rem; max-height: 100vh; scroll-behavior: smooth; } .chat-messages { flex: 1; overflow-y: auto; padding: 1rem; display: flex; flex-direction: column; gap: 1rem; max-height: 100vh; } .empty-chat { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 3rem 1rem; color: #666; text-align: center; } .empty-chat p { margin: 0.5rem 0; line-height: 1.5; } /* ============================================================================ 消息样式 - Message Styles ============================================================================ */ .message { display: flex; flex-direction: column; margin-bottom: 1.5rem; opacity: 1; transition: opacity 0.3s ease; } .message.user { align-items: flex-end; } .message.assistant { align-items: flex-start; } .message.streaming { opacity: 1; } .message-content { max-width: 80%; padding: 1rem 1.25rem; border-radius: 18px; word-wrap: break-word; line-height: 1.5; font-size: 0.95rem; position: relative; } .message.user .message-content { background: linear-gradient(135deg, #007bff 0%, #0056b3 100%); color: white; border-bottom-right-radius: 8px; } .message.assistant .message-content { background: #f8f9fa; color: #333; border: 1px solid #e9ecef; border-bottom-left-radius: 8px; } .message-time { font-size: 0.75rem; color: #666; margin-top: 0.5rem; padding: 0 0.5rem; } .message.user .message-time { text-align: right; } .message.assistant .message-time { text-align: left; } /* ============================================================================ 思维链样式 - Thinking Chain Styles ============================================================================ */ .thinking-container { margin-bottom: 1rem; border: 1px solid #e0e7ff; border-radius: 8px; background: #f8faff; overflow: hidden; } .thinking-header { padding: 0.75rem 1rem; background: #f0f8ff; border-bottom: 1px solid #e0e7ff; cursor: pointer; display: flex; align-items: center; gap: 0.5rem; transition: background-color 0.2s; user-select: none; } .thinking-header:hover { background: #e6f3ff; } .thinking-icon { font-size: 1.1rem; } .thinking-title { font-weight: 500; color: #4338ca; font-size: 0.9rem; } .thinking-toggle { margin-left: auto; color: #6b7280; font-size: 0.8rem; transition: transform 0.2s; } .thinking-content-box { padding: 1rem; background: white; border-top: 1px solid #e0e7ff; } .thinking-status { display: flex; align-items: center; gap: 0.5rem; font-size: 0.9rem; color: #666; margin-bottom: 0.5rem; } /* ============================================================================ 流式处理样式 - Streaming Styles ============================================================================ */ .streaming-indicator { display: flex; align-items: center; gap: 0.5rem; color: #007bff; font-size: 0.9rem; margin: 0.5rem 0; } .streaming-text { position: relative; } .streaming-cursor { display: inline-block; width: 2px; height: 1.2em; background-color: #007bff; animation: blink 1s infinite; margin-left: 2px; vertical-align: text-bottom; } @keyframes blink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0; } } .typing-indicator { display: inline-flex; gap: 4px; margin-right: 8px; } .typing-indicator span { width: 6px; height: 6px; border-radius: 50%; background-color: #666; animation: typing 1.4s infinite ease-in-out; } .typing-indicator span:nth-child(1) { animation-delay: -0.32s; } .typing-indicator span:nth-child(2) { animation-delay: -0.16s; } @keyframes typing { 0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; } 40% { transform: scale(1); opacity: 1; } } .partial-math-indicator { display: inline-block; margin-left: 4px; opacity: 0.7; animation: pulse 1s infinite; } @keyframes pulse { 0%, 100% { opacity: 0.7; } 50% { opacity: 1; } } /* ============================================================================ 聊天输入 - Chat Input ============================================================================ */ .chat-input { padding: 1rem 1.5rem; border-top: 1px solid #e0e0e0; background: white; display: flex; flex-direction: column; gap: 0.75rem; } .input-row { display: flex; align-items: flex-end; gap: 0.5rem; } .chat-input input[type="text"] { flex: 1; padding: 0.75rem 1rem; border: 1px solid #ddd; border-radius: 20px; font-size: 0.95rem; outline: none; transition: border-color 0.2s; resize: none; min-height: 44px; max-height: 120px; } .chat-input input[type="text"]:focus { border-color: #007bff; box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1); } .chat-input input[type="text"]:disabled { background-color: #f8f9fa; color: #6c757d; cursor: not-allowed; } .send-button { background: #007bff; color: white; border: none; border-radius: 50%; width: 44px; height: 44px; cursor: pointer; transition: all 0.2s; display: flex; align-items: center; justify-content: center; font-size: 1.1rem; flex-shrink: 0; } .send-button:hover:not(:disabled) { background: #0056b3; transform: scale(1.05); } .send-button:disabled { background: #6c757d; cursor: not-allowed; transform: none; } .image-upload-btn { background: #f8f9fa; color: #666; border: 1px solid #ddd; border-radius: 50%; width: 44px; height: 44px; cursor: pointer; transition: all 0.2s; display: flex; align-items: center; justify-content: center; font-size: 1.1rem; flex-shrink: 0; } .image-upload-btn:hover:not(:disabled) { background: #e9ecef; color: #495057; transform: scale(1.05); } .image-upload-btn:disabled { background: #f8f9fa; color: #6c757d; cursor: not-allowed; transform: none; } /* ============================================================================ 图片预览 - Image Preview ============================================================================ */ .image-preview-container { border: 1px solid #e0e0e0; border-radius: 8px; padding: 0.75rem; background: #f8f9fa; } .image-preview-header { font-size: 0.85rem; color: #666; margin-bottom: 0.5rem; font-weight: 500; } .image-preview-grid { display: flex; gap: 0.5rem; flex-wrap: wrap; } .image-preview-item { position: relative; width: 60px; height: 60px; border-radius: 6px; overflow: hidden; border: 1px solid #ddd; } .image-preview-item img { width: 100%; height: 100%; object-fit: cover; } .image-preview-info { position: absolute; top: 0; right: 0; background: rgba(0, 0, 0, 0.7); color: white; padding: 2px; border-radius: 0 0 0 4px; } .remove-image-btn { background: rgba(220, 53, 69, 0.9); color: white; border: none; border-radius: 50%; width: 18px; height: 18px; cursor: pointer; font-size: 10px; display: flex; align-items: center; justify-content: center; transition: background-color 0.2s; } .remove-image-btn:hover { background: rgba(220, 53, 69, 1); } /* ============================================================================ 多模态内容 - Multimodal Content ============================================================================ */ .content-text-part { margin-bottom: 0.5rem; } .content-text-part:last-child { margin-bottom: 0; } .content-image-part { margin: 0.5rem 0; } .content-image-part img { max-width: 100%; max-height: 300px; display: block; margin: 0 auto; border-radius: 8px; border: 1px solid #e5e7eb; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .content-unknown { padding: 1rem; background: #fff3cd; color: #856404; border: 1px solid #ffeaa7; border-radius: 6px; font-style: italic; } /* ============================================================================ 保存按钮 - Save Buttons ============================================================================ */ .save-buttons-row { margin-top: 0.75rem; padding-top: 0.75rem; border-top: 1px solid #e9ecef; display: flex; gap: 0.75rem; flex-wrap: wrap; } .save-button-inline, .save-button-primary, .save-button-secondary { padding: 0.5rem 1rem; border: none; border-radius: 6px; font-size: 0.85rem; font-weight: 500; cursor: pointer; transition: all 0.2s; display: flex; align-items: center; gap: 0.5rem; } .save-button-inline { background: #28a745; color: white; } .save-button-inline:hover:not(:disabled) { background: #218838; } .save-button-primary { background: #007bff; color: white; } .save-button-primary:hover:not(:disabled) { background: #0056b3; } .save-button-secondary { background: #6c757d; color: white; } .save-button-secondary:hover:not(:disabled) { background: #545b62; } .save-buttons-group { display: flex; gap: 0.5rem; } /* ============================================================================ 响应式设计 - Responsive Design ============================================================================ */ @media (max-width: 768px) { .chat-container { border-radius: 0; height: 100vh; } .chat-header { padding: 0.75rem 1rem; } .chat-history { padding: 0.75rem; } .message-content { max-width: 90%; padding: 0.75rem 1rem; font-size: 0.9rem; } .chat-input { padding: 0.75rem 1rem; } .input-row { gap: 0.5rem; } .send-button, .image-upload-btn { width: 40px; height: 40px; font-size: 1rem; } .chat-input input[type="text"] { font-size: 16px; /* 防止iOS缩放 */ } } @media (max-width: 480px) { .message-content { max-width: 95%; padding: 0.6rem 0.8rem; font-size: 0.85rem; } .thinking-header { padding: 0.6rem 0.8rem; font-size: 0.85rem; } .thinking-content-box { padding: 0.8rem; } }
11,707
chat
css
en
css
data
{"qsc_code_num_words": 1342, "qsc_code_num_chars": 11707.0, "qsc_code_mean_word_length": 4.84500745, "qsc_code_frac_words_unique": 0.18256334, "qsc_code_frac_chars_top_2grams": 0.0258382, "qsc_code_frac_chars_top_3grams": 0.01799446, "qsc_code_frac_chars_top_4grams": 0.03229775, "qsc_code_frac_chars_dupe_5grams": 0.26499539, "qsc_code_frac_chars_dupe_6grams": 0.18348201, "qsc_code_frac_chars_dupe_7grams": 0.13442018, "qsc_code_frac_chars_dupe_8grams": 0.13442018, "qsc_code_frac_chars_dupe_9grams": 0.11150415, "qsc_code_frac_chars_dupe_10grams": 0.10335281, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.06501354, "qsc_code_frac_chars_whitespace": 0.18014863, "qsc_code_size_file_byte": 11707.0, "qsc_code_num_lines": 640.0, "qsc_code_num_chars_line_max": 83.0, "qsc_code_num_chars_line_mean": 18.2921875, "qsc_code_frac_chars_alphabet": 0.61241925, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.45421245, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00136659, "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/chat-core/styles/analysis.css
/** * Analysis Styles - 分析相关样式 * 从ReviewAnalysis.css中提取与聊天分析相关的样式 */ /* ============================================================================ 分析容器 - Analysis Container ============================================================================ */ .analysis-container { width: 100%; display: flex; flex-direction: column; background-color: #f8fafc; } .analysis-main { flex: 1; padding: 20px; overflow-y: auto; } /* ============================================================================ 分析头部 - Analysis Header ============================================================================ */ .analysis-header { background: white; border-bottom: 1px solid #e2e8f0; padding: 16px 24px; display: flex; justify-content: space-between; align-items: center; } .analysis-title { font-size: 20px; font-weight: 600; color: #1f2937; margin: 0; } .analysis-back-btn { padding: 8px 12px; background: #f3f4f6; border: none; border-radius: 6px; cursor: pointer; color: #374151; display: flex; align-items: center; gap: 8px; transition: background-color 0.2s; } .analysis-back-btn:hover { background: #e5e7eb; } .analysis-create-btn { padding: 12px 24px; background: #3b82f6; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 500; transition: background-color 0.2s; } .analysis-create-btn:hover { background: #2563eb; } /* ============================================================================ 分析步骤指示器 - Analysis Steps ============================================================================ */ .analysis-steps { display: flex; align-items: center; gap: 16px; margin-bottom: 24px; padding: 0 20px; } .analysis-step { display: flex; align-items: center; gap: 8px; } .analysis-step-circle { width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 500; } .analysis-step-circle.active { background: #3b82f6; color: white; } .analysis-step-circle.completed { background: #10b981; color: white; } .analysis-step-circle.pending { background: #e5e7eb; color: #6b7280; } .analysis-step-label { font-size: 14px; color: #374151; } .analysis-step-divider { width: 32px; height: 1px; background: #d1d5db; } /* ============================================================================ 分析表单 - Analysis Form ============================================================================ */ .analysis-form-container { background: white; border-radius: 12px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb; padding: 24px; margin: 0 20px; min-height: 400px; } .analysis-form-group { margin-bottom: 20px; } .analysis-form-label { display: block; font-size: 14px; font-weight: 500; color: #374151; margin-bottom: 8px; } .analysis-form-input, .analysis-form-select, .analysis-form-textarea { width: 100%; padding: 12px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 14px; transition: border-color 0.2s, box-shadow 0.2s; } .analysis-form-input:focus, .analysis-form-select:focus, .analysis-form-textarea:focus { outline: none; border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); } .analysis-form-input:hover, .analysis-form-select:hover { border-color: #9ca3af; } .analysis-form-textarea { resize: vertical; min-height: 120px; } /* ============================================================================ 分析模板 - Analysis Templates ============================================================================ */ .analysis-templates { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 8px; margin-bottom: 16px; } .analysis-template-btn { text-align: left; padding: 12px; font-size: 14px; border: 1px solid #e5e7eb; border-radius: 6px; background: white; cursor: pointer; transition: all 0.2s; } .analysis-template-btn:hover { border-color: #3b82f6; background: #eff6ff; } /* ============================================================================ 错题选择 - Mistake Selection ============================================================================ */ .analysis-mistakes-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 16px; max-height: 400px; overflow-y: auto; padding-right: 8px; } .analysis-mistake-card { border: 1px solid #e5e7eb; border-radius: 8px; padding: 16px; cursor: pointer; transition: all 0.2s; background: white; } .analysis-mistake-card:hover { border-color: #d1d5db; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); } .analysis-mistake-card.selected { border-color: #3b82f6; background: #eff6ff; box-shadow: 0 0 0 1px #3b82f6; } .analysis-mistake-header { display: flex; align-items: center; margin-bottom: 8px; gap: 12px; } .analysis-mistake-checkbox { width: 16px; height: 16px; } .analysis-mistake-subject { font-size: 12px; color: #3b82f6; font-weight: 500; background: #eff6ff; padding: 2px 8px; border-radius: 12px; } .analysis-mistake-date { font-size: 12px; color: #6b7280; margin-left: auto; } .analysis-mistake-question { font-weight: 500; color: #1f2937; margin-bottom: 8px; line-height: 1.4; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } .analysis-mistake-content { color: #6b7280; font-size: 14px; line-height: 1.4; margin-bottom: 12px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; } .analysis-mistake-tags { display: flex; flex-wrap: wrap; gap: 4px; } .analysis-mistake-tag { background: #f3f4f6; color: #374151; padding: 2px 8px; border-radius: 12px; font-size: 12px; } /* ============================================================================ 分析筛选 - Analysis Filters ============================================================================ */ .analysis-filters { display: grid; grid-template-columns: 1fr 1fr 2fr; gap: 20px; margin-bottom: 24px; background: white; padding: 20px; border-radius: 12px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb; } .analysis-search-group { grid-column: 1 / -1; } .analysis-search-input { background: white; } .analysis-search-input:focus { box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); } /* ============================================================================ 分析库 - Analysis Library ============================================================================ */ .analysis-library-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(400px, 1fr)); gap: 20px; padding: 20px; } .analysis-library-card { background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); border: 1px solid #e5e7eb; padding: 20px; cursor: pointer; transition: all 0.3s ease; position: relative; overflow: hidden; animation: fadeInUp 0.3s ease-out; } .analysis-library-card:hover { transform: translateY(-2px); box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12); border-color: #d1d5db; } .analysis-library-card:active { transform: translateY(0); } .analysis-library-card:nth-child(odd) { animation-delay: 0.1s; } .analysis-library-card:nth-child(even) { animation-delay: 0.2s; } .analysis-card-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 16px; padding-bottom: 12px; border-bottom: 1px solid #f3f4f6; } .analysis-card-info { flex: 1; min-width: 0; } .analysis-card-title { font-size: 16px; font-weight: 600; color: #1f2937; margin: 0 0 4px 0; line-height: 1.4; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .analysis-card-id { font-size: 12px; color: #9ca3af; font-family: monospace; background: #f9fafb; padding: 2px 6px; border-radius: 4px; } .analysis-card-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; } .analysis-status-badge { font-size: 12px; font-weight: 500; padding: 4px 8px; border-radius: 12px; white-space: nowrap; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); } .analysis-delete-btn { background: #f3f4f6; border: none; border-radius: 6px; padding: 6px 8px; cursor: pointer; font-size: 14px; transition: all 0.2s; color: #6b7280; } .analysis-delete-btn:hover { background: #fee2e2; color: #dc2626; } .analysis-card-content { display: flex; flex-direction: column; gap: 12px; } .analysis-meta-row { display: flex; flex-wrap: wrap; gap: 8px; } .analysis-meta-item { font-size: 12px; padding: 4px 8px; border-radius: 12px; white-space: nowrap; flex-shrink: 0; transition: all 0.2s ease; } .analysis-library-card:hover .analysis-meta-item { transform: scale(1.05); } .analysis-subject-tag { background: #eff6ff; color: #1d4ed8; font-weight: 500; } .analysis-mistake-count { background: #f0fdf4; color: #166534; } .analysis-chat-count { background: #fef3c7; color: #92400e; } .analysis-target-section, .analysis-preview-section { background: #f9fafb; padding: 12px; border-radius: 8px; border-left: 3px solid #3b82f6; transition: all 0.2s ease; } .analysis-library-card:hover .analysis-target-section, .analysis-library-card:hover .analysis-preview-section { background: #f3f4f6; } .analysis-target-label, .analysis-preview-label { font-size: 12px; font-weight: 600; color: #374151; margin-bottom: 4px; text-transform: uppercase; letter-spacing: 0.5px; } .analysis-target-content, .analysis-preview-content { font-size: 14px; color: #6b7280; line-height: 1.5; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } .analysis-date-section { display: flex; align-items: center; gap: 6px; padding-top: 8px; border-top: 1px solid #f3f4f6; } .analysis-date-icon { font-size: 14px; color: #9ca3af; } .analysis-date-text { font-size: 12px; color: #6b7280; font-weight: 500; } /* ============================================================================ 选中项预览 - Selected Preview ============================================================================ */ .analysis-selected-preview { background: #f9fafb; padding: 12px; border-radius: 6px; max-height: 120px; overflow-y: auto; margin-top: 8px; } .analysis-selected-item { font-size: 14px; color: #374151; margin-bottom: 4px; line-height: 1.4; } /* ============================================================================ 分析按钮 - Analysis Buttons ============================================================================ */ .analysis-actions { display: flex; justify-content: space-between; padding: 20px; background: white; border-top: 1px solid #e5e7eb; } .analysis-action-group { display: flex; gap: 12px; } .analysis-btn { padding: 12px 24px; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500; transition: all 0.2s; } .analysis-btn-primary { background: #3b82f6; color: white; } .analysis-btn-primary:hover { background: #2563eb; } .analysis-btn-primary:disabled { background: #d1d5db; cursor: not-allowed; } .analysis-btn-secondary { background: #6b7280; color: white; } .analysis-btn-secondary:hover { background: #4b5563; } .analysis-btn-ghost { background: #f3f4f6; color: #374151; } .analysis-btn-ghost:hover { background: #e5e7eb; } /* ============================================================================ 分析状态 - Analysis States ============================================================================ */ .analysis-loading { display: flex; justify-content: center; align-items: center; height: 200px; gap: 12px; opacity: 0; animation: fadeIn 0.3s ease-in-out forwards; } .analysis-loading-spinner { width: 24px; height: 24px; border: 2px solid #e5e7eb; border-top: 2px solid #3b82f6; border-radius: 50%; animation: spin 1s linear infinite; } .analysis-loading-text { color: #6b7280; font-size: 14px; } .analysis-empty { text-align: center; padding: 48px 24px; color: #6b7280; } .analysis-empty-icon { font-size: 48px; margin-bottom: 16px; } .analysis-empty-title { font-size: 18px; font-weight: 600; color: #374151; margin-bottom: 8px; } .analysis-empty-description { font-size: 14px; color: #6b7280; margin-bottom: 4px; } .analysis-empty-hint { font-size: 14px; color: #9ca3af; } /* ============================================================================ 分析统计 - Analysis Stats ============================================================================ */ .analysis-library-stats { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; } .analysis-stats-text { font-size: 16px; font-weight: 500; color: #1f2937; } .analysis-stats-filter { font-size: 14px; color: #6b7280; } /* ============================================================================ 动画定义 - Animations ============================================================================ */ @keyframes fadeInUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } } @keyframes fadeIn { to { opacity: 1; } } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } /* ============================================================================ 滚动条样式 - Scrollbar ============================================================================ */ .analysis-mistakes-grid::-webkit-scrollbar, .analysis-selected-preview::-webkit-scrollbar, .analysis-library-grid::-webkit-scrollbar { width: 6px; } .analysis-mistakes-grid::-webkit-scrollbar-track, .analysis-selected-preview::-webkit-scrollbar-track, .analysis-library-grid::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 3px; } .analysis-mistakes-grid::-webkit-scrollbar-thumb, .analysis-selected-preview::-webkit-scrollbar-thumb, .analysis-library-grid::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 3px; } .analysis-mistakes-grid::-webkit-scrollbar-thumb:hover, .analysis-selected-preview::-webkit-scrollbar-thumb:hover, .analysis-library-grid::-webkit-scrollbar-thumb:hover { background: #94a3b8; } /* ============================================================================ 响应式设计 - Responsive Design ============================================================================ */ @media (max-width: 1024px) { .analysis-filters { grid-template-columns: 1fr 1fr; gap: 16px; } .analysis-search-group { grid-column: 1 / -1; } } @media (max-width: 768px) { .analysis-filters { grid-template-columns: 1fr; padding: 16px; gap: 12px; } .analysis-search-group { grid-column: 1; } .analysis-mistakes-grid { grid-template-columns: 1fr; } .analysis-templates { grid-template-columns: 1fr; } .analysis-actions { flex-direction: column; gap: 12px; } .analysis-header { padding: 12px 16px; flex-direction: column; gap: 12px; align-items: flex-start; } .analysis-library-stats { width: 100%; align-items: flex-start; } .analysis-library-grid { grid-template-columns: 1fr; gap: 16px; padding: 16px; } .analysis-library-card { padding: 16px; } .analysis-card-header { flex-direction: column; gap: 8px; align-items: flex-start; } .analysis-card-actions { align-self: flex-end; } .analysis-library-stats { align-items: flex-start; } } @media (max-width: 480px) { .analysis-meta-row { flex-direction: column; gap: 6px; } .analysis-meta-item { align-self: flex-start; } }
16,106
analysis
css
fr
css
data
{"qsc_code_num_words": 1723, "qsc_code_num_chars": 16106.0, "qsc_code_mean_word_length": 5.28554846, "qsc_code_frac_words_unique": 0.15264074, "qsc_code_frac_chars_top_2grams": 0.02459646, "qsc_code_frac_chars_top_3grams": 0.01976502, "qsc_code_frac_chars_top_4grams": 0.01614143, "qsc_code_frac_chars_dupe_5grams": 0.4280224, "qsc_code_frac_chars_dupe_6grams": 0.28703195, "qsc_code_frac_chars_dupe_7grams": 0.16503788, "qsc_code_frac_chars_dupe_8grams": 0.11924893, "qsc_code_frac_chars_dupe_9grams": 0.08971121, "qsc_code_frac_chars_dupe_10grams": 0.06522455, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.05968042, "qsc_code_frac_chars_whitespace": 0.16459704, "qsc_code_size_file_byte": 16106.0, "qsc_code_num_lines": 839.0, "qsc_code_num_chars_line_max": 83.0, "qsc_code_num_chars_line_mean": 19.19666269, "qsc_code_frac_chars_alphabet": 0.61716834, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.51129944, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "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/chat-core/styles/index.css
/* Chat Core Styles - 统一样式入口 */ /* 从现有CSS文件中提取和整理的聊天核心样式集合 */ /* 导入核心聊天样式 */ @import './chat.css'; /* 导入Markdown渲染样式 */ @import './markdown.css'; /* 导入分析相关样式 */ @import './analysis.css'; /* ===== 全局聊天相关CSS变量 ===== */ :root { /* 聊天主色调 */ --chat-primary: #667eea; --chat-primary-dark: #5a6fd8; --chat-secondary: #764ba2; --chat-accent: #f093fb; /* 聊天背景色 */ --chat-bg: #ffffff; --chat-bg-light: #f8fafc; --chat-bg-dark: #edf2f7; /* 聊天边框色 */ --chat-border: #e2e8f0; --chat-border-light: #f1f5f9; --chat-border-dark: #cbd5e0; /* 聊天文本色 */ --chat-text: #2d3748; --chat-text-light: #4a5568; --chat-text-muted: #718096; /* 用户消息样式 */ --user-message-bg: linear-gradient(135deg, #667eea 0%, #764ba2 100%); --user-message-text: #ffffff; /* 助手消息样式 */ --assistant-message-bg: #f8f9fa; --assistant-message-text: #333333; --assistant-message-border: #e1e5e9; /* 流式处理样式 */ --streaming-bg: linear-gradient(135deg, #f0f8ff, #e6f3ff); --streaming-border: rgba(66, 153, 225, 0.2); --streaming-text: #2b6cb0; /* 思维链样式 */ --thinking-bg: linear-gradient(135deg, #fef7e0, #fef3cd); --thinking-border: #f6cc6d; --thinking-text: #92400e; /* RAG来源样式 */ --rag-bg: linear-gradient(135deg, #f0fdf4, #ecfdf5); --rag-border: #86efac; --rag-text: #166534; /* 阴影 */ --chat-shadow-sm: 0 2px 4px rgba(0, 0, 0, 0.05); --chat-shadow-md: 0 4px 12px rgba(0, 0, 0, 0.1); --chat-shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.15); /* 圆角 */ --chat-radius-sm: 6px; --chat-radius-md: 8px; --chat-radius-lg: 12px; --chat-radius-xl: 16px; /* 间距 */ --chat-spacing-xs: 0.25rem; --chat-spacing-sm: 0.5rem; --chat-spacing-md: 1rem; --chat-spacing-lg: 1.5rem; --chat-spacing-xl: 2rem; /* 动画时长 */ --chat-transition-fast: 0.15s; --chat-transition-normal: 0.3s; --chat-transition-slow: 0.5s; } /* ===== 聊天相关工具类 ===== */ .chat-flex { display: flex; } .chat-flex-col { flex-direction: column; } .chat-flex-1 { flex: 1; } .chat-items-center { align-items: center; } .chat-justify-between { justify-content: space-between; } .chat-gap-sm { gap: var(--chat-spacing-sm); } .chat-gap-md { gap: var(--chat-spacing-md); } .chat-gap-lg { gap: var(--chat-spacing-lg); } .chat-p-sm { padding: var(--chat-spacing-sm); } .chat-p-md { padding: var(--chat-spacing-md); } .chat-p-lg { padding: var(--chat-spacing-lg); } .chat-m-sm { margin: var(--chat-spacing-sm); } .chat-m-md { margin: var(--chat-spacing-md); } .chat-m-lg { margin: var(--chat-spacing-lg); } .chat-rounded-sm { border-radius: var(--chat-radius-sm); } .chat-rounded-md { border-radius: var(--chat-radius-md); } .chat-rounded-lg { border-radius: var(--chat-radius-lg); } .chat-shadow-sm { box-shadow: var(--chat-shadow-sm); } .chat-shadow-md { box-shadow: var(--chat-shadow-md); } .chat-shadow-lg { box-shadow: var(--chat-shadow-lg); } .chat-transition { transition: all var(--chat-transition-normal) ease; } .chat-transition-fast { transition: all var(--chat-transition-fast) ease; } .chat-transition-slow { transition: all var(--chat-transition-slow) ease; } /* ===== 聊天状态指示器 ===== */ .chat-status-online { color: #22c55e; } .chat-status-offline { color: #ef4444; } .chat-status-thinking { color: #f59e0b; animation: pulse 2s ease-in-out infinite; } .chat-status-streaming { color: var(--chat-primary); animation: pulse 2s ease-in-out infinite; } /* ===== 聊天加载动画 ===== */ .chat-loading { display: inline-flex; align-items: center; gap: 0.5rem; } .chat-loading-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--chat-primary); animation: chat-loading-bounce 1.4s ease-in-out infinite both; } .chat-loading-dot:nth-child(1) { animation-delay: -0.32s; } .chat-loading-dot:nth-child(2) { animation-delay: -0.16s; } .chat-loading-dot:nth-child(3) { animation-delay: 0s; } @keyframes chat-loading-bounce { 0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; } 40% { transform: scale(1); opacity: 1; } } /* ===== 聊天按钮样式 ===== */ .chat-btn { display: inline-flex; align-items: center; justify-content: center; padding: 0.5rem 1rem; border: none; border-radius: var(--chat-radius-md); font-size: 0.875rem; font-weight: 500; cursor: pointer; transition: all var(--chat-transition-normal) ease; text-decoration: none; gap: 0.5rem; } .chat-btn:disabled { opacity: 0.6; cursor: not-allowed; } .chat-btn-primary { background: var(--user-message-bg); color: var(--user-message-text); box-shadow: var(--chat-shadow-sm); } .chat-btn-primary:hover:not(:disabled) { transform: translateY(-1px); box-shadow: var(--chat-shadow-md); } .chat-btn-secondary { background: var(--chat-bg-dark); color: var(--chat-text); border: 1px solid var(--chat-border); } .chat-btn-secondary:hover:not(:disabled) { background: var(--chat-bg-light); border-color: var(--chat-border-dark); } .chat-btn-ghost { background: transparent; color: var(--chat-text-light); } .chat-btn-ghost:hover:not(:disabled) { background: var(--chat-bg-light); } .chat-btn-sm { padding: 0.25rem 0.75rem; font-size: 0.75rem; } .chat-btn-lg { padding: 0.75rem 1.5rem; font-size: 1rem; } /* ===== 聊天输入框样式 ===== */ .chat-input-base { width: 100%; padding: 0.75rem 1rem; border: 2px solid var(--chat-border); border-radius: var(--chat-radius-md); font-size: 0.875rem; font-family: inherit; background: var(--chat-bg); color: var(--chat-text); transition: all var(--chat-transition-normal) ease; outline: none; } .chat-input-base:focus { border-color: var(--chat-primary); box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); } .chat-input-base:disabled { background: var(--chat-bg-dark); cursor: not-allowed; opacity: 0.7; } .chat-input-base::placeholder { color: var(--chat-text-muted); } /* ===== 聊天徽章样式 ===== */ .chat-badge { display: inline-flex; align-items: center; padding: 0.25rem 0.75rem; border-radius: 12px; font-size: 0.75rem; font-weight: 500; white-space: nowrap; } .chat-badge-primary { background: rgba(102, 126, 234, 0.1); color: var(--chat-primary); } .chat-badge-success { background: rgba(34, 197, 94, 0.1); color: #166534; } .chat-badge-warning { background: rgba(245, 158, 11, 0.1); color: #92400e; } .chat-badge-error { background: rgba(239, 68, 68, 0.1); color: #dc2626; } .chat-badge-info { background: rgba(59, 130, 246, 0.1); color: #1e40af; } /* ===== 聊天分隔符 ===== */ .chat-divider { height: 1px; background: var(--chat-border); margin: var(--chat-spacing-md) 0; } .chat-divider-text { position: relative; text-align: center; margin: var(--chat-spacing-lg) 0; } .chat-divider-text::before { content: ''; position: absolute; top: 50%; left: 0; right: 0; height: 1px; background: var(--chat-border); } .chat-divider-text span { background: var(--chat-bg); padding: 0 var(--chat-spacing-md); color: var(--chat-text-muted); font-size: 0.875rem; position: relative; } /* ===== 聊天时间戳 ===== */ .chat-timestamp { font-size: 0.75rem; color: var(--chat-text-muted); font-weight: 500; } .chat-timestamp-relative { font-style: italic; } /* ===== 聊天头像样式 ===== */ .chat-avatar { width: 32px; height: 32px; border-radius: 50%; background: var(--chat-bg-dark); display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 0.875rem; color: var(--chat-text); flex-shrink: 0; } .chat-avatar-sm { width: 24px; height: 24px; font-size: 0.75rem; } .chat-avatar-lg { width: 40px; height: 40px; font-size: 1rem; } .chat-avatar-user { background: var(--user-message-bg); color: var(--user-message-text); } .chat-avatar-assistant { background: var(--chat-primary); color: white; } /* ===== 聊天图标样式 ===== */ .chat-icon { width: 1em; height: 1em; display: inline-block; vertical-align: middle; } .chat-icon-sm { width: 0.875em; height: 0.875em; } .chat-icon-lg { width: 1.25em; height: 1.25em; } /* ===== 响应式断点 ===== */ @media (max-width: 768px) { :root { --chat-spacing-md: 0.75rem; --chat-spacing-lg: 1rem; --chat-spacing-xl: 1.5rem; } .chat-btn { padding: 0.5rem 0.875rem; font-size: 0.8rem; } .chat-input-base { padding: 0.625rem 0.875rem; font-size: 0.8rem; } .chat-avatar { width: 28px; height: 28px; font-size: 0.8rem; } } @media (max-width: 480px) { :root { --chat-spacing-sm: 0.375rem; --chat-spacing-md: 0.625rem; --chat-spacing-lg: 0.875rem; --chat-spacing-xl: 1.25rem; } .chat-btn { padding: 0.375rem 0.75rem; font-size: 0.75rem; } .chat-input-base { padding: 0.5rem 0.75rem; font-size: 0.75rem; } .chat-avatar { width: 24px; height: 24px; font-size: 0.75rem; } } /* ===== 深色主题支持 ===== */ @media (prefers-color-scheme: dark) { :root { --chat-bg: #1a202c; --chat-bg-light: #2d3748; --chat-bg-dark: #4a5568; --chat-border: #4a5568; --chat-border-light: #718096; --chat-border-dark: #2d3748; --chat-text: #e2e8f0; --chat-text-light: #cbd5e0; --chat-text-muted: #a0aec0; --assistant-message-bg: #2d3748; --assistant-message-text: #e2e8f0; --assistant-message-border: #4a5568; } } /* ===== 打印样式 ===== */ @media print { .chat-container { background: white !important; border: 1px solid #000 !important; box-shadow: none !important; } .streaming-cursor, .chat-loading, .chat-btn { display: none !important; } .message-content { break-inside: avoid; } .thinking-section, .chain-of-thought, .rag-sources { break-inside: avoid; } }
9,781
index
css
zh
css
data
{"qsc_code_num_words": 1372, "qsc_code_num_chars": 9781.0, "qsc_code_mean_word_length": 4.3425656, "qsc_code_frac_words_unique": 0.22594752, "qsc_code_frac_chars_top_2grams": 0.05991944, "qsc_code_frac_chars_top_3grams": 0.02114804, "qsc_code_frac_chars_top_4grams": 0.02232293, "qsc_code_frac_chars_dupe_5grams": 0.29657603, "qsc_code_frac_chars_dupe_6grams": 0.19503189, "qsc_code_frac_chars_dupe_7grams": 0.13997986, "qsc_code_frac_chars_dupe_8grams": 0.05639476, "qsc_code_frac_chars_dupe_9grams": 0.0318899, "qsc_code_frac_chars_dupe_10grams": 0.0318899, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.06754057, "qsc_code_frac_chars_whitespace": 0.18106533, "qsc_code_size_file_byte": 9781.0, "qsc_code_num_lines": 544.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 17.97977941, "qsc_code_frac_chars_alphabet": 0.67627965, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.21923937, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00388469, "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/chat-core/styles/README.md
# Chat Core Styles 这个目录包含了从现有CSS文件中提取和整理的聊天相关样式,提供了一套完整的聊天界面样式系统。 ## 文件结构 ``` styles/ ├── index.css # 主入口文件,导入所有样式和定义CSS变量 ├── chat.css # 聊天界面核心样式 ├── markdown.css # Markdown渲染和思维链样式 ├── analysis.css # 分析相关样式(回顾分析、错题选择等) └── README.md # 本文档 ``` ## 样式文件说明 ### 1. index.css - **主入口文件**,统一导入所有样式 - 定义CSS变量系统,便于主题定制 - 提供工具类和通用组件样式 - 包含响应式断点和深色主题支持 ### 2. chat.css - **聊天界面核心样式**,从App.css和DeepStudent.css中提取 - 包含以下主要样式: - 聊天容器和布局 - 聊天头部和工具栏 - 消息显示(用户消息、助手消息) - 流式处理指示器 - 聊天输入区域 - 全屏模式支持 - 聊天界面测试页面样式 ### 3. markdown.css - **Markdown渲染样式**,包含思维链和RAG来源显示 - 包含以下主要样式: - 基础Markdown元素(标题、段落、列表等) - 代码块和行内代码 - 表格样式 - 思维链显示(thinking-section) - 推理链条显示(chain-of-thought) - RAG来源显示(rag-sources) - 流式渲染效果 - 特殊内容块(信息框、警告框等) ### 4. analysis.css - **分析相关样式**,从ReviewAnalysis.css中提取 - 包含以下主要样式: - 分析容器和布局 - 分析步骤指示器 - 分析表单和输入控件 - 错题选择和筛选界面 - 分析库卡片展示 - 分析结果预览 - 分析模板选择 - 响应式分析界面设计 ## 样式提取来源 这些样式主要从以下文件中提取和整理: 1. **App.css** - 主要的聊天界面样式 - 流式聊天界面(.streaming-chat-interface) - 消息样式(.message, .user-message-content) - 聊天容器(.chat-container, .chat-header, .chat-input) - Markdown渲染样式 - 流式处理样式 2. **DeepStudent.css** - 侧边栏和布局样式 - 聊天容器布局和全屏模式 - 聊天头部和操作按钮 3. **ReviewAnalysis.css** - 回顾分析相关样式(已提取到analysis.css) - 分析容器和布局样式 - 分析步骤指示器 - 错题选择界面 - 分析库卡片展示 - 表单和按钮样式 - 筛选和搜索控件 4. **RagQueryView.css** - RAG查询界面样式 - RAG结果显示 - 查询配置样式 ## 主要功能特性 ### 1. 响应式设计 - 支持桌面端、平板和移动端 - 自适应布局和字体大小调整 - 移动端优化的交互体验 ### 2. 主题支持 - 浅色主题(默认) - 深色主题支持(通过 prefers-color-scheme) - CSS变量系统便于主题定制 ### 3. 聊天功能 - 用户和助手消息区分显示 - 流式文本渲染效果 - 打字指示器动画 - 全屏聊天模式 - 消息时间戳显示 ### 4. 思维链显示 - 思维过程可视化 - 推理步骤展示 - 可折叠的思维内容 - RAG来源信息显示 ### 5. Markdown增强 - 完整的Markdown语法支持 - 代码高亮(多语言支持) - 表格美化 - 数学公式支持 - 特殊内容块(信息、警告、成功、错误) ### 6. 无障碍支持 - 键盘导航支持 - 屏幕阅读器友好 - 高对比度支持 - 焦点指示器 ### 7. 动画效果 - 平滑的过渡动画 - 加载指示器 - 悬停效果 - 流式渲染动画 ## 使用方法 ### 基础使用 ```tsx import './chat-core/styles/index.css'; // 在你的组件中使用样式类 <div className="chat-container"> <div className="chat-header"> <h4>AI 助手</h4> </div> <div className="chat-history"> {/* 消息内容 */} </div> <div className="chat-input"> {/* 输入区域 */} </div> </div> ``` ### 思维链使用 ```tsx <div className="thinking-section"> <div className="thinking-header"> 🤔 思考过程 </div> <div className="thinking-content"> <p>让我分析一下这个问题...</p> </div> </div> ``` ### RAG来源显示 ```tsx <div className="rag-sources"> <div className="rag-sources-header"> 📚 参考来源 </div> <div className="rag-source-item"> <div className="rag-source-header"> <span className="rag-source-title">文档标题</span> <span className="rag-source-score">0.95</span> </div> <div className="rag-source-content"> 相关内容摘要... </div> </div> </div> ``` ### 工具类使用 ```tsx <div className="chat-flex chat-items-center chat-gap-md"> <button className="chat-btn chat-btn-primary"> 发送消息 </button> <span className="chat-badge chat-badge-success"> 在线 </span> </div> ``` ## CSS变量定制 你可以通过重写CSS变量来定制主题: ```css :root { --chat-primary: #your-color; --chat-bg: #your-bg-color; --chat-text: #your-text-color; /* 更多变量见 index.css */ } ``` ## 注意事项 1. **样式隔离**:所有样式都使用了明确的类名前缀,避免与其他样式冲突 2. **性能优化**:使用了CSS变量和工具类,减少重复代码 3. **兼容性**:支持现代浏览器,包括Chrome、Firefox、Safari、Edge 4. **维护性**:样式按功能分类,便于维护和扩展 ## 更新日志 - **v1.0.0** - 初始版本,从现有CSS文件中提取和整理聊天相关样式 - 包含完整的聊天界面、Markdown渲染、思维链显示功能 - 支持响应式设计和深色主题 - 提供丰富的工具类和组件样式 ## 贡献指南 如果需要添加新的聊天相关样式: 1. 确定样式的功能分类(聊天界面 vs Markdown渲染) 2. 添加到对应的CSS文件中 3. 遵循现有的命名规范和代码风格 4. 确保添加响应式和深色主题支持 5. 更新本README文档
3,565
README
md
zh
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.00168303, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 57.0, "qsc_doc_num_words": 866, "qsc_doc_num_chars": 3565.0, "qsc_doc_num_lines": 227.0, "qsc_doc_mean_word_length": 2.63625866, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.00440529, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.34064665, "qsc_doc_entropy_unigram": 5.11560366, "qsc_doc_frac_words_all_caps": 0.01257862, "qsc_doc_frac_lines_dupe_lines": 0.16402116, "qsc_doc_frac_chars_dupe_lines": 0.06118547, "qsc_doc_frac_chars_top_2grams": 0.06833114, "qsc_doc_frac_chars_top_3grams": 0.03504161, "qsc_doc_frac_chars_top_4grams": 0.00788436, "qsc_doc_frac_chars_dupe_5grams": 0.10775296, "qsc_doc_frac_chars_dupe_6grams": 0.04905826, "qsc_doc_frac_chars_dupe_7grams": 0.02452913, "qsc_doc_frac_chars_dupe_8grams": 0.01226456, "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": 11.46853147, "qsc_doc_frac_chars_hyperlink_html_tag": 0.2058906, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.0110421, "qsc_doc_frac_chars_whitespace": 0.18709677, "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}
0015/esp_rlottie
rlottie/test/test_vpath.cpp
#include <gtest/gtest.h> #include "vpath.h" class VPathTest : public ::testing::Test { public: void SetUp() { pathRect.addRect({-10, -20, 100, 100}); pathRoundRect.addRoundRect({0, 0, 100, 100}, 5, 5); pathRoundRectZeroCorner.addRoundRect({0, 0, 100, 100}, 0, 0); pathRoundRectHalfCircle.addRoundRect({0, 0, 100, 100}, 60, 60); pathOval.addOval({0,0,100,50}); pathOvalCircle.addOval({0,0,100,100}); pathCircle.addCircle(0, 0, 100); pathCircleZeroRadius.addCircle(10, 10, 0); pathPolygon.addPolygon(10, 50, 5, 0, 0, 0); pathPolystar.addPolystar(10, 50, 100, 7, 14, 0, 0, 0); pathPolygonZero.addPolygon(10, 50, 0, 0, 0, 0); pathPolystarZero.addPolystar(10, 50, 100, 0, 0, 0, 0, 0); } void TearDown() { } public: VPath pathEmpty; VPath pathRect; VPath pathRoundRect; VPath pathRoundRectZeroCorner; VPath pathRoundRectHalfCircle; VPath pathOval; VPath pathOvalCircle; VPath pathCircle; VPath pathCircleZeroRadius; VPath pathPolygon; VPath pathPolystar; VPath pathPolygonZero; VPath pathPolystarZero; }; TEST_F(VPathTest, emptyPath) { ASSERT_EQ(sizeof(pathEmpty), sizeof(void *)); ASSERT_TRUE(pathEmpty.empty()); ASSERT_FALSE(pathEmpty.segments()); ASSERT_EQ(pathEmpty.segments() , 0); ASSERT_EQ(pathEmpty.elements().size() , 0); ASSERT_EQ(pathEmpty.elements().capacity() , pathEmpty.elements().size()); ASSERT_EQ(pathEmpty.points().size() , 0); ASSERT_EQ(pathEmpty.points().capacity() , pathEmpty.points().size()); } TEST_F(VPathTest, reset) { pathRect.reset(); ASSERT_TRUE(pathRect.empty()); ASSERT_EQ(pathRect.segments() , 0); ASSERT_GE(pathRect.points().capacity(), 1); ASSERT_GE(pathRect.elements().capacity(), 1); } TEST_F(VPathTest, reserve) { pathEmpty.reserve(10, 10); ASSERT_EQ(pathEmpty.points().capacity(), 10); ASSERT_GE(pathEmpty.elements().capacity(), 10); ASSERT_EQ(pathEmpty.segments() , 0); ASSERT_EQ(pathEmpty.points().size(), 0); ASSERT_GE(pathEmpty.elements().size(), 0); } TEST_F(VPathTest, clone) { VPath pathClone; pathClone.clone(pathOval); ASSERT_TRUE(pathClone.unique()); ASSERT_EQ(pathClone.segments(), pathOval.segments()); ASSERT_EQ(pathClone.points().size(), pathOval.points().size()); ASSERT_NE(pathClone.points().data(), pathOval.points().data()); ASSERT_EQ(pathClone.elements().size(), pathOval.elements().size()); ASSERT_NE(pathClone.elements().data(), pathOval.elements().data()); } TEST_F(VPathTest, copyOnWrite) { VPath pathCopy; pathCopy = pathOval; ASSERT_EQ(pathCopy.segments(), pathOval.segments()); ASSERT_EQ(pathCopy.points().size(), pathOval.points().size()); ASSERT_EQ(pathCopy.points().data(), pathOval.points().data()); ASSERT_EQ(pathCopy.elements().size(), pathOval.elements().size()); ASSERT_EQ(pathCopy.elements().data(), pathOval.elements().data()); } TEST_F(VPathTest, addRect) { ASSERT_FALSE(pathRect.empty()); ASSERT_EQ(pathRect.segments() , 1); ASSERT_EQ(pathRect.elements().capacity() , pathRect.elements().size()); ASSERT_EQ(pathRect.points().capacity() , pathRect.points().size()); } TEST_F(VPathTest, addRect_N) { pathEmpty.addRect({}); ASSERT_TRUE(pathEmpty.empty()); ASSERT_EQ(pathEmpty.segments() , 0); } TEST_F(VPathTest, addRoundRect) { ASSERT_FALSE(pathRoundRect.empty()); ASSERT_EQ(pathRoundRect.segments() , 1); ASSERT_EQ(pathRoundRect.elements().capacity() , pathRoundRect.elements().size()); ASSERT_EQ(pathRoundRect.points().capacity() , pathRoundRect.points().size()); } TEST_F(VPathTest, addRoundRectZeoCorner) { ASSERT_FALSE(pathRoundRectZeroCorner.empty()); ASSERT_EQ(pathRoundRectZeroCorner.segments() , 1); ASSERT_EQ(pathRoundRectZeroCorner.elements().size() , pathRect.elements().size()); ASSERT_EQ(pathRoundRectZeroCorner.elements().capacity() , pathRoundRectZeroCorner.elements().size()); ASSERT_EQ(pathRoundRectZeroCorner.points().size() , pathRect.points().size()); ASSERT_EQ(pathRoundRectZeroCorner.points().capacity() , pathRoundRectZeroCorner.points().size()); } TEST_F(VPathTest, addRoundRectHalfCircle) { ASSERT_FALSE(pathRoundRectHalfCircle.empty()); ASSERT_EQ(pathRoundRectHalfCircle.segments() , 1); ASSERT_EQ(pathRoundRectHalfCircle.elements().capacity() , pathRoundRectHalfCircle.elements().size()); ASSERT_EQ(pathRoundRectHalfCircle.points().capacity() , pathRoundRectHalfCircle.points().size()); } TEST_F(VPathTest, addOval) { ASSERT_FALSE(pathOval.empty()); ASSERT_EQ(pathOval.segments() , 1); ASSERT_EQ(pathOval.elements().capacity() , pathOval.elements().size()); ASSERT_EQ(pathOval.points().capacity() , pathOval.points().size()); } TEST_F(VPathTest, addOvalCircle) { ASSERT_FALSE(pathOvalCircle.empty()); ASSERT_EQ(pathOvalCircle.segments() , 1); ASSERT_EQ(pathOvalCircle.elements().size() , pathOval.elements().size()); ASSERT_EQ(pathOvalCircle.elements().capacity() , pathOvalCircle.elements().size()); ASSERT_EQ(pathOvalCircle.points().size() , pathOval.points().size()); ASSERT_EQ(pathOvalCircle.points().capacity() , pathOvalCircle.points().size()); } TEST_F(VPathTest, addCircle) { ASSERT_FALSE(pathCircle.empty()); ASSERT_EQ(pathCircle.segments() , 1); ASSERT_EQ(pathCircle.elements().size() , pathOval.elements().size()); ASSERT_EQ(pathCircle.elements().capacity() , pathCircle.elements().size()); ASSERT_EQ(pathCircle.points().size() , pathOval.points().size()); ASSERT_EQ(pathCircle.points().capacity() , pathCircle.points().size()); } TEST_F(VPathTest, addCircleZeroRadius) { ASSERT_TRUE(pathCircleZeroRadius.empty()); ASSERT_EQ(pathCircleZeroRadius.segments() , 0); } TEST_F(VPathTest, length) { ASSERT_EQ(pathRect.length(), 400); } TEST_F(VPathTest, lengthEmptyPath) { ASSERT_EQ(pathEmpty.length(), 0); } TEST_F(VPathTest, addPolygon) { ASSERT_FALSE(pathPolygon.empty()); ASSERT_EQ(pathPolygon.segments() , 1); ASSERT_EQ(pathPolygon.elements().size() , pathPolygon.elements().capacity()); ASSERT_EQ(pathPolygon.points().size() , pathPolygon.points().capacity()); } TEST_F(VPathTest, addPolygonZeroRoundness) { ASSERT_FALSE(pathPolygonZero.empty()); ASSERT_EQ(pathPolygonZero.segments() , 1); ASSERT_EQ(pathPolygonZero.elements().size() , pathPolygonZero.elements().capacity()); ASSERT_EQ(pathPolygonZero.points().size() , pathPolygonZero.points().capacity()); } TEST_F(VPathTest, addPolystar) { ASSERT_FALSE(pathPolystar.empty()); ASSERT_EQ(pathPolystar.segments() , 1); ASSERT_EQ(pathPolystar.elements().size() , pathPolystar.elements().capacity()); ASSERT_EQ(pathPolystar.points().size() , pathPolystar.points().capacity()); } TEST_F(VPathTest, addPolystarZeroRoundness) { ASSERT_FALSE(pathPolystarZero.empty()); ASSERT_EQ(pathPolystarZero.segments() , 1); ASSERT_EQ(pathPolystarZero.elements().size() , pathPolystarZero.elements().capacity()); ASSERT_EQ(pathPolystarZero.points().size() , pathPolystarZero.points().capacity()); }
7,171
test_vpath
cpp
en
cpp
code
{"qsc_code_num_words": 758, "qsc_code_num_chars": 7171.0, "qsc_code_mean_word_length": 6.48416887, "qsc_code_frac_words_unique": 0.09762533, "qsc_code_frac_chars_top_2grams": 0.09928789, "qsc_code_frac_chars_top_3grams": 0.05696846, "qsc_code_frac_chars_top_4grams": 0.04883011, "qsc_code_frac_chars_dupe_5grams": 0.32695829, "qsc_code_frac_chars_dupe_6grams": 0.13733469, "qsc_code_frac_chars_dupe_7grams": 0.1076297, "qsc_code_frac_chars_dupe_8grams": 0.03621567, "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.02274912, "qsc_code_frac_chars_whitespace": 0.12954957, "qsc_code_size_file_byte": 7171.0, "qsc_code_num_lines": 190.0, "qsc_code_num_chars_line_max": 106.0, "qsc_code_num_chars_line_mean": 37.74210526, "qsc_code_frac_chars_alphabet": 0.76465876, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.05357143, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00097615, "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.5, "qsc_codecpp_frac_lines_preprocessor_directives": 0.01190476, "qsc_codecpp_frac_lines_func_ratio": 0.01190476, "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.0297619, "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": 0, "qsc_code_frac_lines_assert": 1, "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/test/wasm_test.html
<!doctype html> <html> <canvas id="rlottie" width="100" height="100"></canvas> <script> var Module = { onRuntimeInitialized: function() { class Animator { constructor(){ this.instance = new Module.RlottieWasm(); this.canvas = document.getElementById("rlottie"); this.frames = this.instance.frames(); this.curFrame = 0; this.tick_cb(); } tick_cb() { var context = this.canvas.getContext('2d'); var buffer = this.instance.render(this.curFrame, this.canvas.width, this.canvas.height); var clampedBuffer = Uint8ClampedArray.from(buffer); var imageData = new ImageData(clampedBuffer, this.canvas.width, this.canvas.height); context.putImageData(imageData, 0, 0); this.curFrame += 1; if (this.curFrame >= this.frames) this.curFrame = 0; window.requestAnimationFrame(()=>{ this.tick_cb();}); } } var instance = new Animator(); } }; </script> <script src="rlottie-wasm.js"></script> </html>
1,131
wasm_test
html
en
html
code
{"qsc_code_num_words": 110, "qsc_code_num_chars": 1131.0, "qsc_code_mean_word_length": 5.8, "qsc_code_frac_words_unique": 0.4, "qsc_code_frac_chars_top_2grams": 0.09404389, "qsc_code_frac_chars_top_3grams": 0.04388715, "qsc_code_frac_chars_top_4grams": 0.05956113, "qsc_code_frac_chars_dupe_5grams": 0.09717868, "qsc_code_frac_chars_dupe_6grams": 0.09717868, "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.01629073, "qsc_code_frac_chars_whitespace": 0.29442971, "qsc_code_size_file_byte": 1131.0, "qsc_code_num_lines": 32.0, "qsc_code_num_chars_line_max": 101.0, "qsc_code_num_chars_line_mean": 35.34375, "qsc_code_frac_chars_alphabet": 0.78320802, "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.03268551, "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_codehtml_cate_ast": 1.0, "qsc_codehtml_frac_words_text": 0.00442087, "qsc_codehtml_num_chars_text": 5.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": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_codehtml_cate_ast": 0, "qsc_codehtml_frac_words_text": 1, "qsc_codehtml_num_chars_text": 1}
0015/esp_rlottie
rlottie/test/meson.build
override_default = ['warning_level=2', 'werror=false'] gtest_dep = dependency('gtest') vector_test_sources = [ 'testsuite.cpp', 'test_vrect.cpp', 'test_vpath.cpp', ] vector_testsuite = executable('vectorTestSuite', vector_test_sources, include_directories : inc, override_options : override_default, dependencies : [gtest_dep, rlottie_lib_dep], ) test('Vector Testsuite', vector_testsuite) animation_test_sources = [ 'testsuite.cpp', 'test_lottieanimation.cpp', 'test_lottieanimation_capi.cpp' ] animation_testsuite = executable('animationTestSuite', animation_test_sources, include_directories : inc, override_options : override_default, link_with : rlottie_lib, dependencies : gtest_dep, ) test('Animation Testsuite', animation_testsuite)
1,113
meson
build
en
unknown
unknown
{}
0
{}
003random/003Recon
install.sh
#!/usr/bin/env bash dependencies_dir="dependencies" output_dir="output" mkdir $output_dir; #mkdir -p $dependencies_dir/phantomjs; # Install sublis3r git clone https://github.com/aboul3la/Sublist3r.git $dependencies_dir/sublister; # Install wpscan git clone https://github.com/wpscanteam/wpscan.git $dependencies_dir/wpscan; # Install Relative-URL-Extractor git clone https://github.com/jobertabma/relative-url-extractor.git $dependencies_dir/relative-url-extractor; # Install WebScreenShot git clone https://github.com/maaaaz/webscreenshot.git $dependencies_dir/webscreenshot; # Install PhantomJS #wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2 -O $dependencies_dir/phantomjs/phantomjs-2.1.1-linux-x86_64.tar.bz2 #tar xvjf $dependencies_dir/phantomjs/phantomjs-2.1.1-linux-x86_64.tar.bz2 -C /usr/local/share/ #ln -s /usr/local/share/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin/ # Install Nmap git clone https://github.com/nmap/nmap.git $dependencies_dir/nmap cd $dependencies_dir/nmap; ./configure; make; make install; cd ../../;
1,113
install
sh
en
shell
code
{"qsc_code_num_words": 164, "qsc_code_num_chars": 1113.0, "qsc_code_mean_word_length": 5.17682927, "qsc_code_frac_words_unique": 0.31097561, "qsc_code_frac_chars_top_2grams": 0.17667845, "qsc_code_frac_chars_top_3grams": 0.07656066, "qsc_code_frac_chars_top_4grams": 0.11189635, "qsc_code_frac_chars_dupe_5grams": 0.31095406, "qsc_code_frac_chars_dupe_6grams": 0.18138987, "qsc_code_frac_chars_dupe_7grams": 0.18138987, "qsc_code_frac_chars_dupe_8grams": 0.15547703, "qsc_code_frac_chars_dupe_9grams": 0.15547703, "qsc_code_frac_chars_dupe_10grams": 0.12249706, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03336605, "qsc_code_frac_chars_whitespace": 0.08445642, "qsc_code_size_file_byte": 1113.0, "qsc_code_num_lines": 32.0, "qsc_code_num_chars_line_max": 159.0, "qsc_code_num_chars_line_mean": 34.78125, "qsc_code_frac_chars_alphabet": 0.79980373, "qsc_code_frac_chars_comments": 0.475292, "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.03082192, "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_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}
003random/003Recon
README.md
## 📌 Description This repository contains some of my scripts that i created to automate some recon processes. It performs the following things; 1. Get subdomains of a domain 2. Filter out only online domains 3. Scan the domains for CRLF 4. Check for a CORS misconfigurations 5. Test for open redirects 6. Grab sensitive headers 7. Get sensitive info from error pages 8. Check for subdomain takeovers 9. Extract javascript files 10. Feed the javascript files into 'relative-url-extractor' 11. Screenshot all domains 12. Check if sites run wordpress 13. Start a wpscan on the wordpress sites 14. Do a nmap service scan More tools in comming soon / in progress :wink: All output will get saved in a folder named by the domain, in the output folder. In this folder it will create files with the discovered content. ## Install: git clone https://github.com/003random/003Recon.git; cd 003Recon; ./install.sh; #Or if you have some tools already installed, edit the paths in recon.sh and comment those tools out here. And then call it with: ./recon.sh example.com ### Also, you might need to install some python modules like 'requests'. 👌 *Created by [003random](http://hackerone.com/003random) - [@003random](https://twitter.com/rub003) - [003random.com](https://poc-server.com/blog/)*
1,365
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.25524476, "qsc_doc_num_sentences": 32.0, "qsc_doc_num_words": 212, "qsc_doc_num_chars": 1365.0, "qsc_doc_num_lines": 37.0, "qsc_doc_mean_word_length": 4.6745283, "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.6509434, "qsc_doc_entropy_unigram": 4.74013454, "qsc_doc_frac_words_all_caps": 0.00699301, "qsc_doc_frac_lines_dupe_lines": 0.0, "qsc_doc_frac_chars_dupe_lines": 0.0, "qsc_doc_frac_chars_top_2grams": 0.01614531, "qsc_doc_frac_chars_top_3grams": 0.0, "qsc_doc_frac_chars_top_4grams": 0.0, "qsc_doc_frac_chars_dupe_5grams": 0.0, "qsc_doc_frac_chars_dupe_6grams": 0.0, "qsc_doc_frac_chars_dupe_7grams": 0.0, "qsc_doc_frac_chars_dupe_8grams": 0.0, "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": 18.79710145, "qsc_doc_frac_chars_hyperlink_html_tag": 0.06593407, "qsc_doc_frac_chars_alphabet": 0.87108656, "qsc_doc_frac_chars_digital": 0.03959484, "qsc_doc_frac_chars_whitespace": 0.2043956, "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}
003random/003Recon
recon.sh
#This little script chains all the tools together. please read it through before using, so there wont be any unexpected results. tput setaf 3; echo "Please read through this script before executing, to prevent unexpected things from happening." home_dir=$(pwd) output_dir="output" tools_dir="tools" payloads_dir="payloads" dependencies_dir="dependencies" screenshots_dir="$output_dir/$@/screenshots" all_domains_file="$output_dir/$@/domains-all.txt" domains_file="$output_dir/$@/domains.txt" crlf_file="$output_dir/$@/crlf.txt" open_redirects_file="$output_dir/$@/open_redirects.txt" nmap_scan_file="$output_dir/$@/nmap_scans.txt" wordpress_file="$output_dir/$@/wordpress_sites.txt" headers_file="$output_dir/$@/sensitive_headers.txt" subdomain_take_over_file="$output_dir/$@/sub_take_over.txt" javascript_files_file="$output_dir/$@/javascript_files.txt" javascript_extracted_urls="$output_dir/$@/extracted_urls.txt" error_page_info_file="$output_dir/$@/error_page_info.txt" cors_file="$output_dir/$@/misconfigured_cors.txt" crlf_payload_file="$payloads_dir/crlf.txt" error_pages_payload_file="$payloads_dir/error_pages.txt" headers_payload_file="$payloads_dir/sensitive_headers.txt" open_redirect_payload_file="$payloads_dir/open_redirects.txt" wpscan_location="dependencies/wpscan" url_extractor_location="dependencies/relative-url-extractor" sublister_location="dependencies/sublister" webscreenshot_location="dependencies/webscreenshot" nmap_location="dependencies/nmap" cd $home_dir/$output_dir; # Uncomment on own risk. this will first clean the old results. #rm -rf $@; mkdir $@; cd ../ printf "\n -- $@ Started -- \n" python $sublister_location/sublist3r.py -o $all_domains_file -d $@; python $tools_dir/online.py $all_domains_file $domains_file; $tools_dir/crlf.sh $domains_file $crlf_file $crlf_payload_file; $tools_dir/cors_misconfiguration_scan.sh $domains_file $cors_file; python $tools_dir/open_redirect.py $domains_file $open_redirects_file $open_redirect_payload_file; python $tools_dir/header_scan.py $domains_file $headers_file $headers_payload_file; python $tools_dir/error_page_info_check.py $domains_file $error_page_info_file $error_pages_payload_file; python $tools_dir/subdomain_takeover_scan.py $domains_file $subdomain_take_over_file; python $tools_dir/javascript_files_extractor.py $domains_file $javascript_files_file; $tools_dir/javascript_files_link_extractor.sh $javascript_files_file $javascript_extracted_urls $url_extractor_location/extract.rb; python $webscreenshot_location/webscreenshot.py -i $domains_file -o $screenshots_dir; python $tools_dir/wordpress_check.py $domains_file $wordpress_file; $wpscan_location/wpscan.rb --update; $tools_dir/wpscan_domains.sh $wordpress_file; $tools_dir/nmap_scan.sh $domains_file $nmap_scan_file $nmap_location; printf "\n -- $@ Finished -- \n"
3,055
recon
sh
en
shell
code
{"qsc_code_num_words": 410, "qsc_code_num_chars": 3055.0, "qsc_code_mean_word_length": 5.29512195, "qsc_code_frac_words_unique": 0.25853659, "qsc_code_frac_chars_top_2grams": 0.06218333, "qsc_code_frac_chars_top_3grams": 0.06586826, "qsc_code_frac_chars_top_4grams": 0.04145555, "qsc_code_frac_chars_dupe_5grams": 0.05941962, "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.00075273, "qsc_code_frac_chars_whitespace": 0.13027823, "qsc_code_size_file_byte": 3055.0, "qsc_code_num_lines": 63.0, "qsc_code_num_chars_line_max": 136.0, "qsc_code_num_chars_line_mean": 48.49206349, "qsc_code_frac_chars_alphabet": 0.81633421, "qsc_code_frac_chars_comments": 0.06710311, "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.28596491, "qsc_code_frac_chars_long_word_length": 0.21368421, "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}
001SPARTaN/aggressor_scripts
visualizations/logvis.cna
# Beacon Log visualization # 001SPARTaN (for r3dqu1nn) import ui.*; import table.*; import java.awt.*; import javax.swing.*; import javax.swing.table.*; global('$model $console $table'); sub updateTable { fork({ local('$entry'); # Clear the model so we can put new stuff in it. [$model clear: 1024]; # For each entry in beaconlog, populate a row in the table foreach @entry (data_query('beaconlog')) { # We only care about beacon_input events because those are commands run by operators if (@entry[0] eq "beacon_input") { # Get operator who ran the command %modelEntry['operator'] = @entry[2]; # Get bid of command $bid = @entry[1]; # Get internal IP of system %modelEntry['ip'] = binfo($bid, "internal"); # Get hostname of system %modelEntry['hostname'] = binfo($bid, "computer"); # Get username beacon is runnning as %modelEntry['user'] = binfo($bid, "user"); # Get pid of beacon %modelEntry['pid'] = binfo($bid, "pid"); # Get command run on the beacon %modelEntry['command'] = @entry[3]; # Get timestamp of command %modelEntry['timestamp'] = formatDate(@entry[4], "MMM dd HH:mm:ss z"); # Add the new entry to $model [$model addEntry: %modelEntry]; } } # Update with the new table [$model fireListeners]; }, \$model); } # based on setupPopupMenu provided by Raphael Mudge # https://gist.github.com/rsmudge/87ce80cd8d8d185c5870d559af2dc0c2 sub setupClickListener { # we're using fork({}) to run this in a separate Aggressor Script environment. # This reduces deadlock potential due to Sleep's global interpreter lock # this especially matters as our mouse listener will be fired for *everything* # to include mouse movements. fork({ [$component addMouseListener: lambda({ if ([$1 isPopupTrigger]) { # If right click, show popup show_popup($1, $name, $component); } else if ([$1 getClickCount] == 2) { foreach $row ([$table getSelectedRows]) { # Compare pid from selected row to pid of all beacons to find correct beacon foreach %beacon (beacons()) { if (%beacon['pid'] eq [$model getValueAt: $row, 4]) { openOrActivate(%beacon['id']); } } } } }, \$component, \$name)]; }, $component => $1, $name => $2, $model => $model, $table => $table); } sub createVisualization { this('$client'); # GenericTableModel from table.* # Has columns for email and token, defaults to sorting by token $model = [new GenericTableModel: @("operator", "ip", "hostname", "user", "pid", "command", "timestamp"), "beacon", 16]; # Create a table from the GenericTableModel $table = [new ATable: $model]; # Controls how the column headers will sort the table $sorter = [new TableRowSorter: $model]; [$sorter toggleSortOrder: 3]; # setComparator for email [$sorter setComparator: 0, { return $1 cmp $2; }]; # setComparator for token [$sorter setComparator: 1, { return $1 cmp $2; }]; # setComparator for timestamp [$sorter setComparator: 2, { return $1 cmp $2; }]; # setComparator for click count [$sorter setComparator: 3, { return $1 <=> $2; }]; # Set $sorter as the row sorter for $table [$table setRowSorter: $sorter]; # Change resize mode for columns to make the layout a bit nicer. # [$table setAutoResizeMode: [JTable AUTO_RESIZE_ON]]; # Create a scroll pane $scrollPane = [new JScrollPane: $table]; $bottom = [new JPanel]; [$bottom setLayout: [new BoxLayout: $bottom, [BoxLayout Y_AXIS]]]; [$bottom setLayout: [new GridLayout: 1, 1]]; $copyButton = [new JButton: "Copy"]; [$copyButton addActionListener: lambda({ println("Copy action captured!"); $selected = ""; foreach $row ([$table getSelectedRows]) { # Get values from table # operator [ip_hostname] user/proc | timestamp> command $operator = [$table getValueAt: $row, 0]; $ip = [$table getValueAt: $row, 1]; $hostname = [$table getValueAt: $row, 2]; $user = [$table getValueAt: $row, 3]; $proc = [$table getValueAt: $row, 4]; $time = [$table getValueAt: $row, 6]; $command = [$table getValueAt: $row, 5]; $selected .= "$operator \[$ip\_$hostname\] $user\/$proc | $time\> $command\n"; } add_to_clipboard($selected); }, \$table)]; [$bottom add: $copyButton]; $content = [new JPanel]; [$content setLayout: [new BorderLayout]]; [$content add: $scrollPane, [BorderLayout CENTER]]; [$content add: $bottom, [BorderLayout SOUTH]]; # Set popup menu for the table setupClickListener($table, "command_log"); # Update table contents updateTable(); # Return the JScrollPane return $scrollPane; } popup command_log { item "Copy" { # Copy log entry to clipboard println("Right click captured!"); $selected = ""; foreach $row ([$table getSelectedRows]) { # Get values from table # operator [ip_hostname] user/proc | timestamp> command $operator = [$table getValueAt: $row, 0]; $ip = [$table getValueAt: $row, 1]; $hostname = [$table getValueAt: $row, 2]; $user = [$table getValueAt: $row, 3]; $proc = [$table getValueAt: $row, 4]; $time = [$table getValueAt: $row, 6]; $command = [$table getValueAt: $row, 5]; $selected .= "$operator \[$ip\_$hostname\] $user\/$proc | $time\> $command\n"; } add_to_clipboard($selected); } item "Beacon console" { # Open corresponding beacon console $selected = ""; foreach $row ([$table getSelectedRows]) { # Compare pid from selected row to pid of all beacons to find correct beacon foreach %beacon (beacons()) { if (%beacon['pid'] eq [$table getValueAt: $row, 4]) { openBeaconConsole(%beacon['id']); } } } } } popup view { item "Command Log" { # Add a tab with the table $tab = createVisualization(); addTab("Command Log", $tab, "A table of commands that have been run on all beacons."); } } on beacon_input { updateTable(); }
6,900
logvis
cna
en
unknown
unknown
{}
0
{}
001SPARTaN/aggressor_scripts
visualizations/vis.cna
# vis.cna # Experimenting with custom visualizations in Aggressor Script # Doesn't really do much right now # @001SPARTaN import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; import ui.*; import table.*; global('$model $console'); sub updateHosts { fork({ local('$entry'); # Clear the model so we can put new stuff in it. [$model clear: 256]; foreach $b (beacons()) { %entry["user"] = $b['user']; %entry["host"] = $b['computer']; %entry["bid"] = $b['id']; # Add the new entry to $model [$model addEntry: %entry]; } # Update with the new table [$model fireListeners]; }, \$model); } sub updateConsole { $msg = $1; # Append our message to $console [$console append: $msg]; } sub createVisualization { # GenericTableModel from table.* $model = [new GenericTableModel: @("user", "host", "bid"), "bid", 16]; # Create a table from the GenericTableModel $table = [new ATable: $model]; # Controls how the column headers will sort the table $sorter = [new TableRowSorter: $model]; [$sorter toggleSortOrder: 0]; # We have to use cmp for comparing user, because it's a text string [$sorter setComparator: 0, { return $1 cmp $2; }]; # Builtin compareHosts function allows us to sort by host [$sorter setComparator: 1, &compareHosts]; # <=> works fine to compare bid, because they're just numbers [$sorter setComparator: 2, { return $1 <=> $2; }]; # Set $sorter as the row sorter for $table [$table setRowSorter: $sorter]; # console.Display from ui.* # Because it looks better than a boring text area $console = [new console.Display]; # Create a split pane (divider you can drag around) $content = [new JSplitPane: [JSplitPane HORIZONTAL_SPLIT], [new JScrollPane: $table], $console]; # Make spacing look nice by adjusting the split location [$content setDividerLocation: 450]; updateHosts(); # Register the visualization with CS addVisualization("Custom", $content); } createVisualization(); on beacon_initial { updateHosts(); $user = beacon_info($1, "user"); $host = beacon_info($1, "computer"); updateConsole("[BEACON] - ID: \c3$1\c\n"); updateConsole("[BEACON] - USER: \c3$user\c\n"); } on web_hit { updateConsole("[WEB] - Source: \c4$3\c\n"); } # Add an item to the View menu to show our new visualization popup view { item "Custom" { # Show the visualization showVisualization("Custom"); } }
2,681
vis
cna
en
unknown
unknown
{}
0
{}
0015/esp_rlottie
rlottie/src/lottie/rapidjson/internal/meta.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_INTERNAL_META_H_ #define RAPIDJSON_INTERNAL_META_H_ #include "../rapidjson.h" #ifdef __GNUC__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(effc++) #endif #if defined(_MSC_VER) && !defined(__clang__) RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(6334) #endif #if RAPIDJSON_HAS_CXX11_TYPETRAITS #include <type_traits> #endif //@cond RAPIDJSON_INTERNAL RAPIDJSON_NAMESPACE_BEGIN namespace internal { // Helper to wrap/convert arbitrary types to void, useful for arbitrary type matching template <typename T> struct Void { typedef void Type; }; /////////////////////////////////////////////////////////////////////////////// // BoolType, TrueType, FalseType // template <bool Cond> struct BoolType { static const bool Value = Cond; typedef BoolType Type; }; typedef BoolType<true> TrueType; typedef BoolType<false> FalseType; /////////////////////////////////////////////////////////////////////////////// // SelectIf, BoolExpr, NotExpr, AndExpr, OrExpr // template <bool C> struct SelectIfImpl { template <typename T1, typename T2> struct Apply { typedef T1 Type; }; }; template <> struct SelectIfImpl<false> { template <typename T1, typename T2> struct Apply { typedef T2 Type; }; }; template <bool C, typename T1, typename T2> struct SelectIfCond : SelectIfImpl<C>::template Apply<T1,T2> {}; template <typename C, typename T1, typename T2> struct SelectIf : SelectIfCond<C::Value, T1, T2> {}; template <bool Cond1, bool Cond2> struct AndExprCond : FalseType {}; template <> struct AndExprCond<true, true> : TrueType {}; template <bool Cond1, bool Cond2> struct OrExprCond : TrueType {}; template <> struct OrExprCond<false, false> : FalseType {}; template <typename C> struct BoolExpr : SelectIf<C,TrueType,FalseType>::Type {}; template <typename C> struct NotExpr : SelectIf<C,FalseType,TrueType>::Type {}; template <typename C1, typename C2> struct AndExpr : AndExprCond<C1::Value, C2::Value>::Type {}; template <typename C1, typename C2> struct OrExpr : OrExprCond<C1::Value, C2::Value>::Type {}; /////////////////////////////////////////////////////////////////////////////// // AddConst, MaybeAddConst, RemoveConst template <typename T> struct AddConst { typedef const T Type; }; template <bool Constify, typename T> struct MaybeAddConst : SelectIfCond<Constify, const T, T> {}; template <typename T> struct RemoveConst { typedef T Type; }; template <typename T> struct RemoveConst<const T> { typedef T Type; }; /////////////////////////////////////////////////////////////////////////////// // IsSame, IsConst, IsMoreConst, IsPointer // template <typename T, typename U> struct IsSame : FalseType {}; template <typename T> struct IsSame<T, T> : TrueType {}; template <typename T> struct IsConst : FalseType {}; template <typename T> struct IsConst<const T> : TrueType {}; template <typename CT, typename T> struct IsMoreConst : AndExpr<IsSame<typename RemoveConst<CT>::Type, typename RemoveConst<T>::Type>, BoolType<IsConst<CT>::Value >= IsConst<T>::Value> >::Type {}; template <typename T> struct IsPointer : FalseType {}; template <typename T> struct IsPointer<T*> : TrueType {}; /////////////////////////////////////////////////////////////////////////////// // IsBaseOf // #if RAPIDJSON_HAS_CXX11_TYPETRAITS template <typename B, typename D> struct IsBaseOf : BoolType< ::std::is_base_of<B,D>::value> {}; #else // simplified version adopted from Boost template<typename B, typename D> struct IsBaseOfImpl { RAPIDJSON_STATIC_ASSERT(sizeof(B) != 0); RAPIDJSON_STATIC_ASSERT(sizeof(D) != 0); typedef char (&Yes)[1]; typedef char (&No) [2]; template <typename T> static Yes Check(const D*, T); static No Check(const B*, int); struct Host { operator const B*() const; operator const D*(); }; enum { Value = (sizeof(Check(Host(), 0)) == sizeof(Yes)) }; }; template <typename B, typename D> struct IsBaseOf : OrExpr<IsSame<B, D>, BoolExpr<IsBaseOfImpl<B, D> > >::Type {}; #endif // RAPIDJSON_HAS_CXX11_TYPETRAITS ////////////////////////////////////////////////////////////////////////// // EnableIf / DisableIf // template <bool Condition, typename T = void> struct EnableIfCond { typedef T Type; }; template <typename T> struct EnableIfCond<false, T> { /* empty */ }; template <bool Condition, typename T = void> struct DisableIfCond { typedef T Type; }; template <typename T> struct DisableIfCond<true, T> { /* empty */ }; template <typename Condition, typename T = void> struct EnableIf : EnableIfCond<Condition::Value, T> {}; template <typename Condition, typename T = void> struct DisableIf : DisableIfCond<Condition::Value, T> {}; // SFINAE helpers struct SfinaeTag {}; template <typename T> struct RemoveSfinaeTag; template <typename T> struct RemoveSfinaeTag<SfinaeTag&(*)(T)> { typedef T Type; }; #define RAPIDJSON_REMOVEFPTR_(type) \ typename ::RAPIDJSON_NAMESPACE::internal::RemoveSfinaeTag \ < ::RAPIDJSON_NAMESPACE::internal::SfinaeTag&(*) type>::Type #define RAPIDJSON_ENABLEIF(cond) \ typename ::RAPIDJSON_NAMESPACE::internal::EnableIf \ <RAPIDJSON_REMOVEFPTR_(cond)>::Type * = NULL #define RAPIDJSON_DISABLEIF(cond) \ typename ::RAPIDJSON_NAMESPACE::internal::DisableIf \ <RAPIDJSON_REMOVEFPTR_(cond)>::Type * = NULL #define RAPIDJSON_ENABLEIF_RETURN(cond,returntype) \ typename ::RAPIDJSON_NAMESPACE::internal::EnableIf \ <RAPIDJSON_REMOVEFPTR_(cond), \ RAPIDJSON_REMOVEFPTR_(returntype)>::Type #define RAPIDJSON_DISABLEIF_RETURN(cond,returntype) \ typename ::RAPIDJSON_NAMESPACE::internal::DisableIf \ <RAPIDJSON_REMOVEFPTR_(cond), \ RAPIDJSON_REMOVEFPTR_(returntype)>::Type } // namespace internal RAPIDJSON_NAMESPACE_END //@endcond #if defined(_MSC_VER) && !defined(__clang__) RAPIDJSON_DIAG_POP #endif #ifdef __GNUC__ RAPIDJSON_DIAG_POP #endif #endif // RAPIDJSON_INTERNAL_META_H_
6,641
meta
h
en
c
code
{"qsc_code_num_words": 754, "qsc_code_num_chars": 6641.0, "qsc_code_mean_word_length": 5.82891247, "qsc_code_frac_words_unique": 0.25729443, "qsc_code_frac_chars_top_2grams": 0.10193402, "qsc_code_frac_chars_top_3grams": 0.05802048, "qsc_code_frac_chars_top_4grams": 0.06803185, "qsc_code_frac_chars_dupe_5grams": 0.36746303, "qsc_code_frac_chars_dupe_6grams": 0.27713311, "qsc_code_frac_chars_dupe_7grams": 0.23094425, "qsc_code_frac_chars_dupe_8grams": 0.09874858, "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.00826592, "qsc_code_frac_chars_whitespace": 0.14380364, "qsc_code_size_file_byte": 6641.0, "qsc_code_num_lines": 186.0, "qsc_code_num_chars_line_max": 115.0, "qsc_code_num_chars_line_mean": 35.70430108, "qsc_code_frac_chars_alphabet": 0.76468519, "qsc_code_frac_chars_comments": 0.25523265, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.32075472, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00283057, "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.01886792, "qsc_codec_frac_lines_func_ratio": 0.10377358, "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.12264151, "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/internal/swap.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_INTERNAL_SWAP_H_ #define RAPIDJSON_INTERNAL_SWAP_H_ #include "../rapidjson.h" #if defined(__clang__) RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(c++98-compat) #endif RAPIDJSON_NAMESPACE_BEGIN namespace internal { //! Custom swap() to avoid dependency on C++ <algorithm> header /*! \tparam T Type of the arguments to swap, should be instantiated with primitive C++ types only. \note This has the same semantics as std::swap(). */ template <typename T> inline void Swap(T& a, T& b) RAPIDJSON_NOEXCEPT { T tmp = a; a = b; b = tmp; } } // namespace internal RAPIDJSON_NAMESPACE_END #if defined(__clang__) RAPIDJSON_DIAG_POP #endif #endif // RAPIDJSON_INTERNAL_SWAP_H_
1,419
swap
h
en
c
code
{"qsc_code_num_words": 209, "qsc_code_num_chars": 1419.0, "qsc_code_mean_word_length": 4.94258373, "qsc_code_frac_words_unique": 0.58851675, "qsc_code_frac_chars_top_2grams": 0.05808325, "qsc_code_frac_chars_top_3grams": 0.06098742, "qsc_code_frac_chars_top_4grams": 0.06389158, "qsc_code_frac_chars_dupe_5grams": 0.05227493, "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.00675105, "qsc_code_frac_chars_whitespace": 0.16490486, "qsc_code_size_file_byte": 1419.0, "qsc_code_num_lines": 46.0, "qsc_code_num_chars_line_max": 99.0, "qsc_code_num_chars_line_mean": 30.84782609, "qsc_code_frac_chars_alphabet": 0.8649789, "qsc_code_frac_chars_comments": 0.69133192, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.25, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.03196347, "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.2, "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.25, "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/internal/biginteger.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_BIGINTEGER_H_ #define RAPIDJSON_BIGINTEGER_H_ #include "../rapidjson.h" #if defined(_MSC_VER) && !defined(__INTEL_COMPILER) && defined(_M_AMD64) #include <intrin.h> // for _umul128 #pragma intrinsic(_umul128) #endif RAPIDJSON_NAMESPACE_BEGIN namespace internal { class BigInteger { public: typedef uint64_t Type; BigInteger(const BigInteger& rhs) : count_(rhs.count_) { std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type)); } explicit BigInteger(uint64_t u) : count_(1) { digits_[0] = u; } BigInteger(const char* decimals, size_t length) : count_(1) { RAPIDJSON_ASSERT(length > 0); digits_[0] = 0; size_t i = 0; const size_t kMaxDigitPerIteration = 19; // 2^64 = 18446744073709551616 > 10^19 while (length >= kMaxDigitPerIteration) { AppendDecimal64(decimals + i, decimals + i + kMaxDigitPerIteration); length -= kMaxDigitPerIteration; i += kMaxDigitPerIteration; } if (length > 0) AppendDecimal64(decimals + i, decimals + i + length); } BigInteger& operator=(const BigInteger &rhs) { if (this != &rhs) { count_ = rhs.count_; std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type)); } return *this; } BigInteger& operator=(uint64_t u) { digits_[0] = u; count_ = 1; return *this; } BigInteger& operator+=(uint64_t u) { Type backup = digits_[0]; digits_[0] += u; for (size_t i = 0; i < count_ - 1; i++) { if (digits_[i] >= backup) return *this; // no carry backup = digits_[i + 1]; digits_[i + 1] += 1; } // Last carry if (digits_[count_ - 1] < backup) PushBack(1); return *this; } BigInteger& operator*=(uint64_t u) { if (u == 0) return *this = 0; if (u == 1) return *this; if (*this == 1) return *this = u; uint64_t k = 0; for (size_t i = 0; i < count_; i++) { uint64_t hi; digits_[i] = MulAdd64(digits_[i], u, k, &hi); k = hi; } if (k > 0) PushBack(k); return *this; } BigInteger& operator*=(uint32_t u) { if (u == 0) return *this = 0; if (u == 1) return *this; if (*this == 1) return *this = u; uint64_t k = 0; for (size_t i = 0; i < count_; i++) { const uint64_t c = digits_[i] >> 32; const uint64_t d = digits_[i] & 0xFFFFFFFF; const uint64_t uc = u * c; const uint64_t ud = u * d; const uint64_t p0 = ud + k; const uint64_t p1 = uc + (p0 >> 32); digits_[i] = (p0 & 0xFFFFFFFF) | (p1 << 32); k = p1 >> 32; } if (k > 0) PushBack(k); return *this; } BigInteger& operator<<=(size_t shift) { if (IsZero() || shift == 0) return *this; size_t offset = shift / kTypeBit; size_t interShift = shift % kTypeBit; RAPIDJSON_ASSERT(count_ + offset <= kCapacity); if (interShift == 0) { std::memmove(digits_ + offset, digits_, count_ * sizeof(Type)); count_ += offset; } else { digits_[count_] = 0; for (size_t i = count_; i > 0; i--) digits_[i + offset] = (digits_[i] << interShift) | (digits_[i - 1] >> (kTypeBit - interShift)); digits_[offset] = digits_[0] << interShift; count_ += offset; if (digits_[count_]) count_++; } std::memset(digits_, 0, offset * sizeof(Type)); return *this; } bool operator==(const BigInteger& rhs) const { return count_ == rhs.count_ && std::memcmp(digits_, rhs.digits_, count_ * sizeof(Type)) == 0; } bool operator==(const Type rhs) const { return count_ == 1 && digits_[0] == rhs; } BigInteger& MultiplyPow5(unsigned exp) { static const uint32_t kPow5[12] = { 5, 5 * 5, 5 * 5 * 5, 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 }; if (exp == 0) return *this; for (; exp >= 27; exp -= 27) *this *= RAPIDJSON_UINT64_C2(0X6765C793, 0XFA10079D); // 5^27 for (; exp >= 13; exp -= 13) *this *= static_cast<uint32_t>(1220703125u); // 5^13 if (exp > 0) *this *= kPow5[exp - 1]; return *this; } // Compute absolute difference of this and rhs. // Assume this != rhs bool Difference(const BigInteger& rhs, BigInteger* out) const { int cmp = Compare(rhs); RAPIDJSON_ASSERT(cmp != 0); const BigInteger *a, *b; // Makes a > b bool ret; if (cmp < 0) { a = &rhs; b = this; ret = true; } else { a = this; b = &rhs; ret = false; } Type borrow = 0; for (size_t i = 0; i < a->count_; i++) { Type d = a->digits_[i] - borrow; if (i < b->count_) d -= b->digits_[i]; borrow = (d > a->digits_[i]) ? 1 : 0; out->digits_[i] = d; if (d != 0) out->count_ = i + 1; } return ret; } int Compare(const BigInteger& rhs) const { if (count_ != rhs.count_) return count_ < rhs.count_ ? -1 : 1; for (size_t i = count_; i-- > 0;) if (digits_[i] != rhs.digits_[i]) return digits_[i] < rhs.digits_[i] ? -1 : 1; return 0; } size_t GetCount() const { return count_; } Type GetDigit(size_t index) const { RAPIDJSON_ASSERT(index < count_); return digits_[index]; } bool IsZero() const { return count_ == 1 && digits_[0] == 0; } private: void AppendDecimal64(const char* begin, const char* end) { uint64_t u = ParseUint64(begin, end); if (IsZero()) *this = u; else { unsigned exp = static_cast<unsigned>(end - begin); (MultiplyPow5(exp) <<= exp) += u; // *this = *this * 10^exp + u } } void PushBack(Type digit) { RAPIDJSON_ASSERT(count_ < kCapacity); digits_[count_++] = digit; } static uint64_t ParseUint64(const char* begin, const char* end) { uint64_t r = 0; for (const char* p = begin; p != end; ++p) { RAPIDJSON_ASSERT(*p >= '0' && *p <= '9'); r = r * 10u + static_cast<unsigned>(*p - '0'); } return r; } // Assume a * b + k < 2^128 static uint64_t MulAdd64(uint64_t a, uint64_t b, uint64_t k, uint64_t* outHigh) { #if defined(_MSC_VER) && defined(_M_AMD64) uint64_t low = _umul128(a, b, outHigh) + k; if (low < k) (*outHigh)++; return low; #elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__) __extension__ typedef unsigned __int128 uint128; uint128 p = static_cast<uint128>(a) * static_cast<uint128>(b); p += k; *outHigh = static_cast<uint64_t>(p >> 64); return static_cast<uint64_t>(p); #else const uint64_t a0 = a & 0xFFFFFFFF, a1 = a >> 32, b0 = b & 0xFFFFFFFF, b1 = b >> 32; uint64_t x0 = a0 * b0, x1 = a0 * b1, x2 = a1 * b0, x3 = a1 * b1; x1 += (x0 >> 32); // can't give carry x1 += x2; if (x1 < x2) x3 += (static_cast<uint64_t>(1) << 32); uint64_t lo = (x1 << 32) + (x0 & 0xFFFFFFFF); uint64_t hi = x3 + (x1 >> 32); lo += k; if (lo < k) hi++; *outHigh = hi; return lo; #endif } static const size_t kBitCount = 3328; // 64bit * 54 > 10^1000 static const size_t kCapacity = kBitCount / sizeof(Type); static const size_t kTypeBit = sizeof(Type) * 8; Type digits_[kCapacity]; size_t count_; }; } // namespace internal RAPIDJSON_NAMESPACE_END #endif // RAPIDJSON_BIGINTEGER_H_
9,143
biginteger
h
en
c
code
{"qsc_code_num_words": 1139, "qsc_code_num_chars": 9143.0, "qsc_code_mean_word_length": 3.96488147, "qsc_code_frac_words_unique": 0.19929763, "qsc_code_frac_chars_top_2grams": 0.03410097, "qsc_code_frac_chars_top_3grams": 0.05048716, "qsc_code_frac_chars_top_4grams": 0.06643047, "qsc_code_frac_chars_dupe_5grams": 0.20217006, "qsc_code_frac_chars_dupe_6grams": 0.16209035, "qsc_code_frac_chars_dupe_7grams": 0.14481842, "qsc_code_frac_chars_dupe_8grams": 0.12356067, "qsc_code_frac_chars_dupe_9grams": 0.09300266, "qsc_code_frac_chars_dupe_10grams": 0.074845, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.07169303, "qsc_code_frac_chars_whitespace": 0.3501039, "qsc_code_size_file_byte": 9143.0, "qsc_code_num_lines": 290.0, "qsc_code_num_chars_line_max": 112.0, "qsc_code_num_chars_line_mean": 31.52758621, "qsc_code_frac_chars_alphabet": 0.68832043, "qsc_code_frac_chars_comments": 0.11451384, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.1559633, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0020998, "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.00864625, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.02752294, "qsc_codec_frac_lines_func_ratio": 0.08256881, "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.11926606, "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/map_tiles_projects
README.md
# Local Map Viewer Demo - Independent ESP32 Example Projects This project demonstrates how to use the **0015__map_tiles** component([ESP Registry](https://components.espressif.com/components/0015/map_tiles)) across multiple independent ESP-IDF projects. It showcases different use cases of interactive map display on ESP32 devices with LVGL 9.x, providing complete examples of GPS-based map navigation with various interaction patterns. <div align="center"> [![espressif_esp32_p4_function_ev_board](./misc/espressif_esp32_p4_function_ev_board_demo.gif)](https://youtu.be/Kyjf24e-Poo) <p>esp32_p4_function_ev_board</p> </div> ## Project Structure This contains ESP-IDF projects that share a common map component: ``` map_tiles_projects/ ├── shared_components/ │ └── simple_map/ # Shared SimpleMap component │ ├── simple_map.hpp │ ├── simple_map.cpp │ └── CMakeLists.txt ├── espressif_esp32_p4_function_ev_board/ # Demo for espressif_esp32_p4_function_ev_board │ ├── main/ │ │ ├── main.cpp │ │ └── CMakeLists.txt │ └── CMakeLists.txt ├── waveshare_esp32_s3_touch_amoled_1_75/ # Demo for waveshare_esp32_s3_touch_amoled_1_75 │ ├── main/ │ │ ├── main.cpp │ │ └── CMakeLists.txt │ └── CMakeLists.txt ├── waveshare_esp32_p4_wifi6_touch_lcd_xc/ # Demo for waveshare_esp32_p4_wifi6_touch_lcd_xc │ ├── main/ │ │ ├── main.cpp │ │ └── CMakeLists.txt │ └── CMakeLists.txt ├── components/ # Device-specific components └── CMakeLists.txt # Shared components only ``` ## Features - **Interactive Map Display**: Touch-scrollable map with smooth tile loading - **Real-time GPS Coordinates**: Automatically updates latitude/longitude as you scroll - **Zoom Control**: Adjustable zoom levels (X-19) with dynamic tile reloading - **GPS Input Panel**: Manual coordinate entry with on-screen keyboard - **Smart Tile Loading**: Preserves old tiles during updates for smooth transitions - **Multiple Tile Types**: Support for different map styles (street, satellite, etc.) - **Touch-optimized UI**: Designed for touchscreen interaction ## Hardware Requirements - ESP32-S3 with at least 8MB PSRAM (recommended) - Display with LVGL 9.x support - Touch panel support - SD card for map tile storage - Minimum 4MB flash memory ## Dependencies - **ESP-IDF 5.0+**: ESP32 development framework - **LVGL 9.3+**: Graphics library - **0015__map_tiles**: Map tiles component (included in managed_components) - **SD card support**: For tile storage (FAT filesystem) ## Map Tiles Format The map tiles should be stored on SD card in the following format: - **Format**: RGB565 binary files - **Size**: 256x256 pixels per tile - **Structure**: `/sdcard/tiles1/zoom/x/y.bin` - **Zoom levels**: 10-19 (configurable) Example directory structure: ``` /sdcard/ ├── tiles1/ │ ├── 15/ │ │ ├── 10485/ │ │ │ ├── 12733.bin │ │ │ ├── 12734.bin │ │ │ └── ... │ │ └── ... │ ├── 16/ │ └── ... ``` ## Usage ### Basic Operation 1. **Power on**: The map initializes and displays a default location 2. **Scroll**: Touch and drag to pan around the map 3. **View coordinates**: Current GPS coordinates are shown in the input panel 4. **Zoom**: Use the slider to select zoom level, then press "Update Map" 5. **Go to location**: Enter coordinates manually and press "Update Map" ### Map Controls - **Touch scrolling**: Drag to move around the map - **GPS coordinates**: Real-time updates as you scroll - **Zoom slider**: Select zoom level (10-19) - **Update button**: Apply coordinate/zoom changes - **Keyboard**: Appears when editing coordinates ### Key Features #### Real-time GPS Updates ```cpp // GPS coordinates update automatically as you scroll void SimpleMap::update_current_gps_from_map_center(); ``` #### Smooth Tile Loading - Old tiles remain visible during updates - Loading indicators show progress - Automatic tile caching and management #### Touch-optimized Interface - Debounced scroll events for smooth performance - Responsive coordinate updates - User-friendly input validation ## Code Structure ### Shared Components - **`SimpleMap` class** (`shared_components/simple_map/`): Main map interface and logic - **`map_tiles` component**: Low-level tile management (managed component) - **Input panel**: GPS coordinate entry and zoom control - **Event handlers**: Touch, scroll, and button events ### Main Task Stack Size This project requires a larger main task stack size than the ESP-IDF default to function correctly. The application loads and displays map tiles directly from an SD card while updating the LVGL graphical interface. The call stack for these operations—including file I/O (VFS/FATFS), image decoding, and LVGL object updates—can be quite deep. The default main task stack is insufficient for these nested function calls and will likely result in a stack overflow and a system crash. To ensure stability, you **must** increase the main task stack size to a minimum of **10,240 bytes (10 KB)**. If you plan to enable long filenames or complex decoders, or if you add more features, we recommend a safer size of 12–16 KB. #### How to set it - **menuconfig** - `idf.py menuconfig` → **Component config → ESP System Settings → Main task stack size** - Set to **10240** (or higher). - **sdkconfig** ```ini CONFIG_ESP_MAIN_TASK_STACK_SIZE=10240 ``` ### Key Functions ```cpp // Initialize the map system bool SimpleMap::init(lv_obj_t* parent_screen); // Display map at specific location void SimpleMap::show_location(double lat, double lon, int zoom); // Handle user interactions void SimpleMap::map_scroll_event_cb(lv_event_t *e); void SimpleMap::update_button_event_cb(lv_event_t *e); // GPS coordinate management void SimpleMap::update_current_gps_from_map_center(); void SimpleMap::get_current_location(double* lat, double* lon); ``` ### Configuration The map system is configured in `SimpleMap::init()`: ```cpp map_tiles_config_t config = { .base_path = "/sdcard", // SD card mount point .tile_folders = {"tiles1"}, // Tile directory names .tile_type_count = 1, // Number of tile types .grid_cols = 5, // Tile grid width .grid_rows = 5, // Tile grid height .default_zoom = 18, // Initial zoom level .use_spiram = true, // Use PSRAM for tiles .default_tile_type = 0 // Default tile type }; ``` ## Performance Optimization ### Memory Management - Uses PSRAM for tile storage when available - Efficient tile caching and cleanup - Minimal memory fragmentation ### Rendering Optimization - Preserves old tiles during updates - Debounced scroll events (50ms for GPS updates) - Optimized LVGL object management ### Touch Response - Smooth scrolling with momentum disabled - Real-time coordinate feedback - Responsive zoom controls ## API Reference ### Public Methods ```cpp class SimpleMap { public: // Core functionality static bool init(lv_obj_t* parent_screen); static void show_location(double lat, double lon, int zoom = 18); static void update_location(double lat, double lon); static void cleanup(); // Tile management static bool set_tile_type(int tile_type); static int get_tile_type(); static int get_tile_type_count(); // Coordinate access static void get_current_location(double* lat, double* lon); static int get_current_zoom(); // Map positioning static void center_map_on_gps(); }; ``` ### Configuration Options - **Grid size**: 5x5 to 9x9 tiles (5x5 recommended) - **Zoom range**: 10-19 (standard map zoom levels) - **Tile types**: Up to 8 different tile sets - **Memory**: PSRAM or regular RAM for tile storage ## Troubleshooting ### Common Issues 1. **Map not displaying**: - Check SD card mount and tile directory structure - Verify tile format (RGB565, 256x256 pixels) - Ensure sufficient PSRAM/memory 2. **Slow performance**: - Enable PSRAM in menuconfig - Reduce grid size if memory limited - Check SD card speed class 3. **Touch not working**: - Verify touch panel configuration - Check LVGL input device setup - Ensure proper touch calibration 4. **Coordinates incorrect**: - Verify tile coordinate system matches your map data - Check zoom level calculations - Ensure proper GPS coordinate conversion ### Debug Output Enable debug output to troubleshoot issues: ```cpp // Key debug messages "SimpleMap: Initialized with grid size %dx%d" "SimpleMap: Loading %dx%d grid at position (%d,%d)" "SimpleMap: Updated GPS from map center: %.6f, %.6f" "SimpleMap: Zoom changed from %d to %d" ``` ## Example Integration ### Device A Implementation (Interactive) ```cpp #include "simple_map.hpp" extern "C" void app_main(void) { // Standard ESP32 initialization... // Initialize interactive map if (!SimpleMap::init(lv_screen_active())) { ESP_LOGE(TAG, "Failed to initialize map"); return; } // Show initial location with full controls SimpleMap::show_location(37.77490, -122.41942, 16); SimpleMap::center_map_on_gps(); } ``` ### Device B Implementation (GPS Tracking) ```cpp #include "simple_map.hpp" // Predefined locations for demo static const struct { double lat, lon; const char* name; } demo_locations[] = { {40.7128, -74.0060, "New York City"}, {51.5074, -0.1278, "London"}, {35.6762, 139.6503, "Tokyo"} }; void location_cycle_task(void *pvParameters) { while (1) { vTaskDelay(pdMS_TO_TICKS(10000)); // 10 second intervals // Cycle through locations current_location_index = (current_location_index + 1) % 3; SimpleMap::show_location( demo_locations[current_location_index].lat, demo_locations[current_location_index].lon, 15 ); } } extern "C" void app_main(void) { // Standard ESP32 initialization... // Initialize map for tracking mode SimpleMap::init(lv_screen_active()); SimpleMap::show_location(demo_locations[0].lat, demo_locations[0].lon, 15); // Start location cycling task xTaskCreate(location_cycle_task, "location_cycle", 4096, NULL, 5, NULL); } ``` ### Shared Component Usage Both devices use the same SimpleMap API: ```cpp // Change tile type (e.g., satellite view) SimpleMap::set_tile_type(1); // Get current position double lat, lon; SimpleMap::get_current_location(&lat, &lon); // Update to new location SimpleMap::update_location(40.7128, -74.0060); ``` ## Creating Custom Device Projects ### Step 1: Create New Project Directory ```bash mkdir device_custom_project cd device_custom_project ``` ### Step 2: Create CMakeLists.txt ```cmake # Device Custom - Your Demo cmake_minimum_required(VERSION 3.5) # Add shared components from parent directory set(EXTRA_COMPONENT_DIRS "../shared_components") include($ENV{IDF_PATH}/tools/cmake/project.cmake) project(simple_map_device_custom) ``` ### Step 3: Create main/ directory and files ```bash mkdir main ``` **main/CMakeLists.txt:** ```cmake idf_component_register(SRCS "main.cpp" INCLUDE_DIRS "." REQUIRES simple_map) ``` **main/main.cpp:** ```cpp #include "simple_map.hpp" extern "C" void app_main(void) { // Your device-specific initialization // Initialize shared map component if (!SimpleMap::init(lv_screen_active())) { return; } // Your custom map configuration SimpleMap::show_location(your_lat, your_lon, your_zoom); } ``` ### Step 4: Build and Test ```bash idf.py build flash monitor ``` ## Contributing This is a multi-device example project demonstrating the 0015__map_tiles component. For improvements or bug fixes: - **Shared SimpleMap component**: Contribute to `shared_components/simple_map/` - **Device-specific features**: Create new device configurations - **Core map functionality**: Contribute to the main 0015__map_tiles component repository ## Acknowledgments - **LVGL Team**: For the excellent graphics library - **Espressif**: For the ESP-IDF framework - **Map tile providers**: For map data (ensure proper attribution) ## Support For questions and support: 1. Check the troubleshooting section above 2. Review the 0015__map_tiles component documentation 3. Post issues with full debug output and hardware configuration ## License This project is provided as an example for the 0015__map_tiles component. Check individual component licenses for specific terms.
12,625
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.00253465, "qsc_doc_frac_words_redpajama_stop": 0.09122203, "qsc_doc_num_sentences": 96.0, "qsc_doc_num_words": 1733, "qsc_doc_num_chars": 12625.0, "qsc_doc_num_lines": 430.0, "qsc_doc_mean_word_length": 5.07212926, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.01162791, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.30294287, "qsc_doc_entropy_unigram": 5.66343508, "qsc_doc_frac_words_all_caps": 0.03700516, "qsc_doc_frac_lines_dupe_lines": 0.21712538, "qsc_doc_frac_chars_dupe_lines": 0.07497028, "qsc_doc_frac_chars_top_2grams": 0.01274175, "qsc_doc_frac_chars_top_3grams": 0.014562, "qsc_doc_frac_chars_top_4grams": 0.01353811, "qsc_doc_frac_chars_dupe_5grams": 0.16268487, "qsc_doc_frac_chars_dupe_6grams": 0.12081911, "qsc_doc_frac_chars_dupe_7grams": 0.09419795, "qsc_doc_frac_chars_dupe_8grams": 0.06188851, "qsc_doc_frac_chars_dupe_9grams": 0.04391354, "qsc_doc_frac_chars_dupe_10grams": 0.04391354, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 22.46840149, "qsc_doc_frac_chars_hyperlink_html_tag": 0.00982178, "qsc_doc_frac_chars_alphabet": 0.81559454, "qsc_doc_frac_chars_digital": 0.02777778, "qsc_doc_frac_chars_whitespace": 0.18732673, "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/map_tiles_projects
waveshare_esp32_s3_touch_amoled_1_75/sdkconfig
# # Automatically generated file. DO NOT EDIT. # Espressif IoT Development Framework (ESP-IDF) 5.4.2 Project Configuration # CONFIG_SOC_MPU_MIN_REGION_SIZE=0x20000000 CONFIG_SOC_MPU_REGIONS_MAX_NUM=8 CONFIG_SOC_ADC_SUPPORTED=y CONFIG_SOC_UART_SUPPORTED=y CONFIG_SOC_PCNT_SUPPORTED=y CONFIG_SOC_PHY_SUPPORTED=y CONFIG_SOC_WIFI_SUPPORTED=y CONFIG_SOC_TWAI_SUPPORTED=y CONFIG_SOC_GDMA_SUPPORTED=y CONFIG_SOC_AHB_GDMA_SUPPORTED=y CONFIG_SOC_GPTIMER_SUPPORTED=y CONFIG_SOC_LCDCAM_SUPPORTED=y CONFIG_SOC_LCDCAM_I80_LCD_SUPPORTED=y CONFIG_SOC_LCDCAM_RGB_LCD_SUPPORTED=y CONFIG_SOC_MCPWM_SUPPORTED=y CONFIG_SOC_DEDICATED_GPIO_SUPPORTED=y CONFIG_SOC_CACHE_SUPPORT_WRAP=y CONFIG_SOC_ULP_SUPPORTED=y CONFIG_SOC_ULP_FSM_SUPPORTED=y CONFIG_SOC_RISCV_COPROC_SUPPORTED=y CONFIG_SOC_BT_SUPPORTED=y CONFIG_SOC_USB_OTG_SUPPORTED=y CONFIG_SOC_USB_SERIAL_JTAG_SUPPORTED=y CONFIG_SOC_CCOMP_TIMER_SUPPORTED=y CONFIG_SOC_ASYNC_MEMCPY_SUPPORTED=y CONFIG_SOC_SUPPORTS_SECURE_DL_MODE=y CONFIG_SOC_EFUSE_KEY_PURPOSE_FIELD=y CONFIG_SOC_EFUSE_SUPPORTED=y CONFIG_SOC_SDMMC_HOST_SUPPORTED=y CONFIG_SOC_RTC_FAST_MEM_SUPPORTED=y CONFIG_SOC_RTC_SLOW_MEM_SUPPORTED=y CONFIG_SOC_RTC_MEM_SUPPORTED=y CONFIG_SOC_PSRAM_DMA_CAPABLE=y CONFIG_SOC_XT_WDT_SUPPORTED=y CONFIG_SOC_I2S_SUPPORTED=y CONFIG_SOC_RMT_SUPPORTED=y CONFIG_SOC_SDM_SUPPORTED=y CONFIG_SOC_GPSPI_SUPPORTED=y CONFIG_SOC_LEDC_SUPPORTED=y CONFIG_SOC_I2C_SUPPORTED=y CONFIG_SOC_SYSTIMER_SUPPORTED=y CONFIG_SOC_SUPPORT_COEXISTENCE=y CONFIG_SOC_TEMP_SENSOR_SUPPORTED=y CONFIG_SOC_AES_SUPPORTED=y CONFIG_SOC_MPI_SUPPORTED=y CONFIG_SOC_SHA_SUPPORTED=y CONFIG_SOC_HMAC_SUPPORTED=y CONFIG_SOC_DIG_SIGN_SUPPORTED=y CONFIG_SOC_FLASH_ENC_SUPPORTED=y CONFIG_SOC_SECURE_BOOT_SUPPORTED=y CONFIG_SOC_MEMPROT_SUPPORTED=y CONFIG_SOC_TOUCH_SENSOR_SUPPORTED=y CONFIG_SOC_BOD_SUPPORTED=y CONFIG_SOC_CLK_TREE_SUPPORTED=y CONFIG_SOC_MPU_SUPPORTED=y CONFIG_SOC_WDT_SUPPORTED=y CONFIG_SOC_SPI_FLASH_SUPPORTED=y CONFIG_SOC_RNG_SUPPORTED=y CONFIG_SOC_LIGHT_SLEEP_SUPPORTED=y CONFIG_SOC_DEEP_SLEEP_SUPPORTED=y CONFIG_SOC_LP_PERIPH_SHARE_INTERRUPT=y CONFIG_SOC_PM_SUPPORTED=y CONFIG_SOC_SIMD_INSTRUCTION_SUPPORTED=y CONFIG_SOC_XTAL_SUPPORT_40M=y CONFIG_SOC_APPCPU_HAS_CLOCK_GATING_BUG=y CONFIG_SOC_ADC_RTC_CTRL_SUPPORTED=y CONFIG_SOC_ADC_DIG_CTRL_SUPPORTED=y CONFIG_SOC_ADC_ARBITER_SUPPORTED=y CONFIG_SOC_ADC_DIG_IIR_FILTER_SUPPORTED=y CONFIG_SOC_ADC_MONITOR_SUPPORTED=y CONFIG_SOC_ADC_DMA_SUPPORTED=y CONFIG_SOC_ADC_PERIPH_NUM=2 CONFIG_SOC_ADC_MAX_CHANNEL_NUM=10 CONFIG_SOC_ADC_ATTEN_NUM=4 CONFIG_SOC_ADC_DIGI_CONTROLLER_NUM=2 CONFIG_SOC_ADC_PATT_LEN_MAX=24 CONFIG_SOC_ADC_DIGI_MIN_BITWIDTH=12 CONFIG_SOC_ADC_DIGI_MAX_BITWIDTH=12 CONFIG_SOC_ADC_DIGI_RESULT_BYTES=4 CONFIG_SOC_ADC_DIGI_DATA_BYTES_PER_CONV=4 CONFIG_SOC_ADC_DIGI_IIR_FILTER_NUM=2 CONFIG_SOC_ADC_DIGI_MONITOR_NUM=2 CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH=83333 CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW=611 CONFIG_SOC_ADC_RTC_MIN_BITWIDTH=12 CONFIG_SOC_ADC_RTC_MAX_BITWIDTH=12 CONFIG_SOC_ADC_CALIBRATION_V1_SUPPORTED=y CONFIG_SOC_ADC_SELF_HW_CALI_SUPPORTED=y CONFIG_SOC_ADC_SHARED_POWER=y CONFIG_SOC_APB_BACKUP_DMA=y CONFIG_SOC_BROWNOUT_RESET_SUPPORTED=y CONFIG_SOC_CACHE_WRITEBACK_SUPPORTED=y CONFIG_SOC_CACHE_FREEZE_SUPPORTED=y CONFIG_SOC_CPU_CORES_NUM=2 CONFIG_SOC_CPU_INTR_NUM=32 CONFIG_SOC_CPU_HAS_FPU=y CONFIG_SOC_HP_CPU_HAS_MULTIPLE_CORES=y CONFIG_SOC_CPU_BREAKPOINTS_NUM=2 CONFIG_SOC_CPU_WATCHPOINTS_NUM=2 CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE=64 CONFIG_SOC_SIMD_PREFERRED_DATA_ALIGNMENT=16 CONFIG_SOC_DS_SIGNATURE_MAX_BIT_LEN=4096 CONFIG_SOC_DS_KEY_PARAM_MD_IV_LENGTH=16 CONFIG_SOC_DS_KEY_CHECK_MAX_WAIT_US=1100 CONFIG_SOC_AHB_GDMA_VERSION=1 CONFIG_SOC_GDMA_NUM_GROUPS_MAX=1 CONFIG_SOC_GDMA_PAIRS_PER_GROUP=5 CONFIG_SOC_GDMA_PAIRS_PER_GROUP_MAX=5 CONFIG_SOC_AHB_GDMA_SUPPORT_PSRAM=y CONFIG_SOC_GPIO_PORT=1 CONFIG_SOC_GPIO_PIN_COUNT=49 CONFIG_SOC_GPIO_SUPPORT_PIN_GLITCH_FILTER=y CONFIG_SOC_GPIO_FILTER_CLK_SUPPORT_APB=y CONFIG_SOC_GPIO_SUPPORT_RTC_INDEPENDENT=y CONFIG_SOC_GPIO_SUPPORT_FORCE_HOLD=y CONFIG_SOC_GPIO_VALID_GPIO_MASK=0x1FFFFFFFFFFFF CONFIG_SOC_GPIO_IN_RANGE_MAX=48 CONFIG_SOC_GPIO_OUT_RANGE_MAX=48 CONFIG_SOC_GPIO_VALID_DIGITAL_IO_PAD_MASK=0x0001FFFFFC000000 CONFIG_SOC_GPIO_CLOCKOUT_BY_IO_MUX=y CONFIG_SOC_GPIO_CLOCKOUT_CHANNEL_NUM=3 CONFIG_SOC_GPIO_SUPPORT_HOLD_IO_IN_DSLP=y CONFIG_SOC_DEDIC_GPIO_OUT_CHANNELS_NUM=8 CONFIG_SOC_DEDIC_GPIO_IN_CHANNELS_NUM=8 CONFIG_SOC_DEDIC_GPIO_OUT_AUTO_ENABLE=y CONFIG_SOC_I2C_NUM=2 CONFIG_SOC_HP_I2C_NUM=2 CONFIG_SOC_I2C_FIFO_LEN=32 CONFIG_SOC_I2C_CMD_REG_NUM=8 CONFIG_SOC_I2C_SUPPORT_SLAVE=y CONFIG_SOC_I2C_SUPPORT_HW_CLR_BUS=y CONFIG_SOC_I2C_SUPPORT_XTAL=y CONFIG_SOC_I2C_SUPPORT_RTC=y CONFIG_SOC_I2C_SUPPORT_10BIT_ADDR=y CONFIG_SOC_I2C_SLAVE_SUPPORT_BROADCAST=y CONFIG_SOC_I2C_SLAVE_SUPPORT_I2CRAM_ACCESS=y CONFIG_SOC_I2C_SLAVE_CAN_GET_STRETCH_CAUSE=y CONFIG_SOC_I2S_NUM=2 CONFIG_SOC_I2S_HW_VERSION_2=y CONFIG_SOC_I2S_SUPPORTS_XTAL=y CONFIG_SOC_I2S_SUPPORTS_PLL_F160M=y CONFIG_SOC_I2S_SUPPORTS_PCM=y CONFIG_SOC_I2S_SUPPORTS_PDM=y CONFIG_SOC_I2S_SUPPORTS_PDM_TX=y CONFIG_SOC_I2S_PDM_MAX_TX_LINES=2 CONFIG_SOC_I2S_SUPPORTS_PDM_RX=y CONFIG_SOC_I2S_PDM_MAX_RX_LINES=4 CONFIG_SOC_I2S_SUPPORTS_TDM=y CONFIG_SOC_LEDC_SUPPORT_APB_CLOCK=y CONFIG_SOC_LEDC_SUPPORT_XTAL_CLOCK=y CONFIG_SOC_LEDC_TIMER_NUM=4 CONFIG_SOC_LEDC_CHANNEL_NUM=8 CONFIG_SOC_LEDC_TIMER_BIT_WIDTH=14 CONFIG_SOC_LEDC_SUPPORT_FADE_STOP=y CONFIG_SOC_MCPWM_GROUPS=2 CONFIG_SOC_MCPWM_TIMERS_PER_GROUP=3 CONFIG_SOC_MCPWM_OPERATORS_PER_GROUP=3 CONFIG_SOC_MCPWM_COMPARATORS_PER_OPERATOR=2 CONFIG_SOC_MCPWM_GENERATORS_PER_OPERATOR=2 CONFIG_SOC_MCPWM_TRIGGERS_PER_OPERATOR=2 CONFIG_SOC_MCPWM_GPIO_FAULTS_PER_GROUP=3 CONFIG_SOC_MCPWM_CAPTURE_TIMERS_PER_GROUP=y CONFIG_SOC_MCPWM_CAPTURE_CHANNELS_PER_TIMER=3 CONFIG_SOC_MCPWM_GPIO_SYNCHROS_PER_GROUP=3 CONFIG_SOC_MCPWM_SWSYNC_CAN_PROPAGATE=y CONFIG_SOC_MMU_LINEAR_ADDRESS_REGION_NUM=1 CONFIG_SOC_MMU_PERIPH_NUM=1 CONFIG_SOC_PCNT_GROUPS=1 CONFIG_SOC_PCNT_UNITS_PER_GROUP=4 CONFIG_SOC_PCNT_CHANNELS_PER_UNIT=2 CONFIG_SOC_PCNT_THRES_POINT_PER_UNIT=2 CONFIG_SOC_RMT_GROUPS=1 CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP=4 CONFIG_SOC_RMT_RX_CANDIDATES_PER_GROUP=4 CONFIG_SOC_RMT_CHANNELS_PER_GROUP=8 CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL=48 CONFIG_SOC_RMT_SUPPORT_RX_PINGPONG=y CONFIG_SOC_RMT_SUPPORT_RX_DEMODULATION=y CONFIG_SOC_RMT_SUPPORT_TX_ASYNC_STOP=y CONFIG_SOC_RMT_SUPPORT_TX_LOOP_COUNT=y CONFIG_SOC_RMT_SUPPORT_TX_LOOP_AUTO_STOP=y CONFIG_SOC_RMT_SUPPORT_TX_SYNCHRO=y CONFIG_SOC_RMT_SUPPORT_TX_CARRIER_DATA_ONLY=y CONFIG_SOC_RMT_SUPPORT_XTAL=y CONFIG_SOC_RMT_SUPPORT_RC_FAST=y CONFIG_SOC_RMT_SUPPORT_APB=y CONFIG_SOC_RMT_SUPPORT_DMA=y CONFIG_SOC_LCD_I80_SUPPORTED=y CONFIG_SOC_LCD_RGB_SUPPORTED=y CONFIG_SOC_LCD_I80_BUSES=1 CONFIG_SOC_LCD_RGB_PANELS=1 CONFIG_SOC_LCD_I80_BUS_WIDTH=16 CONFIG_SOC_LCD_RGB_DATA_WIDTH=16 CONFIG_SOC_LCD_SUPPORT_RGB_YUV_CONV=y CONFIG_SOC_LCDCAM_I80_NUM_BUSES=1 CONFIG_SOC_LCDCAM_I80_BUS_WIDTH=16 CONFIG_SOC_LCDCAM_RGB_NUM_PANELS=1 CONFIG_SOC_LCDCAM_RGB_DATA_WIDTH=16 CONFIG_SOC_RTC_CNTL_CPU_PD_DMA_BUS_WIDTH=128 CONFIG_SOC_RTC_CNTL_CPU_PD_REG_FILE_NUM=549 CONFIG_SOC_RTC_CNTL_TAGMEM_PD_DMA_BUS_WIDTH=128 CONFIG_SOC_RTCIO_PIN_COUNT=22 CONFIG_SOC_RTCIO_INPUT_OUTPUT_SUPPORTED=y CONFIG_SOC_RTCIO_HOLD_SUPPORTED=y CONFIG_SOC_RTCIO_WAKE_SUPPORTED=y CONFIG_SOC_LP_IO_CLOCK_IS_INDEPENDENT=y CONFIG_SOC_SDM_GROUPS=y CONFIG_SOC_SDM_CHANNELS_PER_GROUP=8 CONFIG_SOC_SDM_CLK_SUPPORT_APB=y CONFIG_SOC_SPI_PERIPH_NUM=3 CONFIG_SOC_SPI_MAX_CS_NUM=6 CONFIG_SOC_SPI_MAXIMUM_BUFFER_SIZE=64 CONFIG_SOC_SPI_SUPPORT_DDRCLK=y CONFIG_SOC_SPI_SLAVE_SUPPORT_SEG_TRANS=y CONFIG_SOC_SPI_SUPPORT_CD_SIG=y CONFIG_SOC_SPI_SUPPORT_CONTINUOUS_TRANS=y CONFIG_SOC_SPI_SUPPORT_SLAVE_HD_VER2=y CONFIG_SOC_SPI_SUPPORT_CLK_APB=y CONFIG_SOC_SPI_SUPPORT_CLK_XTAL=y CONFIG_SOC_SPI_PERIPH_SUPPORT_CONTROL_DUMMY_OUT=y CONFIG_SOC_MEMSPI_IS_INDEPENDENT=y CONFIG_SOC_SPI_MAX_PRE_DIVIDER=16 CONFIG_SOC_SPI_SUPPORT_OCT=y CONFIG_SOC_SPI_SCT_SUPPORTED=y CONFIG_SOC_SPI_SCT_REG_NUM=14 CONFIG_SOC_SPI_SCT_BUFFER_NUM_MAX=y CONFIG_SOC_SPI_SCT_CONF_BITLEN_MAX=0x3FFFA CONFIG_SOC_MEMSPI_SRC_FREQ_120M=y CONFIG_SOC_MEMSPI_SRC_FREQ_80M_SUPPORTED=y CONFIG_SOC_MEMSPI_SRC_FREQ_40M_SUPPORTED=y CONFIG_SOC_MEMSPI_SRC_FREQ_20M_SUPPORTED=y CONFIG_SOC_SPIRAM_SUPPORTED=y CONFIG_SOC_SPIRAM_XIP_SUPPORTED=y CONFIG_SOC_SYSTIMER_COUNTER_NUM=2 CONFIG_SOC_SYSTIMER_ALARM_NUM=3 CONFIG_SOC_SYSTIMER_BIT_WIDTH_LO=32 CONFIG_SOC_SYSTIMER_BIT_WIDTH_HI=20 CONFIG_SOC_SYSTIMER_FIXED_DIVIDER=y CONFIG_SOC_SYSTIMER_INT_LEVEL=y CONFIG_SOC_SYSTIMER_ALARM_MISS_COMPENSATE=y CONFIG_SOC_TIMER_GROUPS=2 CONFIG_SOC_TIMER_GROUP_TIMERS_PER_GROUP=2 CONFIG_SOC_TIMER_GROUP_COUNTER_BIT_WIDTH=54 CONFIG_SOC_TIMER_GROUP_SUPPORT_XTAL=y CONFIG_SOC_TIMER_GROUP_SUPPORT_APB=y CONFIG_SOC_TIMER_GROUP_TOTAL_TIMERS=4 CONFIG_SOC_LP_TIMER_BIT_WIDTH_LO=32 CONFIG_SOC_LP_TIMER_BIT_WIDTH_HI=16 CONFIG_SOC_TOUCH_SENSOR_VERSION=2 CONFIG_SOC_TOUCH_SENSOR_NUM=15 CONFIG_SOC_TOUCH_SUPPORT_SLEEP_WAKEUP=y CONFIG_SOC_TOUCH_SUPPORT_WATERPROOF=y CONFIG_SOC_TOUCH_SUPPORT_PROX_SENSING=y CONFIG_SOC_TOUCH_PROXIMITY_CHANNEL_NUM=3 CONFIG_SOC_TOUCH_PROXIMITY_MEAS_DONE_SUPPORTED=y CONFIG_SOC_TOUCH_SAMPLE_CFG_NUM=1 CONFIG_SOC_TWAI_CONTROLLER_NUM=1 CONFIG_SOC_TWAI_CLK_SUPPORT_APB=y CONFIG_SOC_TWAI_BRP_MIN=2 CONFIG_SOC_TWAI_BRP_MAX=16384 CONFIG_SOC_TWAI_SUPPORTS_RX_STATUS=y CONFIG_SOC_UART_NUM=3 CONFIG_SOC_UART_HP_NUM=3 CONFIG_SOC_UART_FIFO_LEN=128 CONFIG_SOC_UART_BITRATE_MAX=5000000 CONFIG_SOC_UART_SUPPORT_FSM_TX_WAIT_SEND=y CONFIG_SOC_UART_SUPPORT_WAKEUP_INT=y CONFIG_SOC_UART_SUPPORT_APB_CLK=y CONFIG_SOC_UART_SUPPORT_RTC_CLK=y CONFIG_SOC_UART_SUPPORT_XTAL_CLK=y CONFIG_SOC_USB_OTG_PERIPH_NUM=1 CONFIG_SOC_SHA_DMA_MAX_BUFFER_SIZE=3968 CONFIG_SOC_SHA_SUPPORT_DMA=y CONFIG_SOC_SHA_SUPPORT_RESUME=y CONFIG_SOC_SHA_GDMA=y CONFIG_SOC_SHA_SUPPORT_SHA1=y CONFIG_SOC_SHA_SUPPORT_SHA224=y CONFIG_SOC_SHA_SUPPORT_SHA256=y CONFIG_SOC_SHA_SUPPORT_SHA384=y CONFIG_SOC_SHA_SUPPORT_SHA512=y CONFIG_SOC_SHA_SUPPORT_SHA512_224=y CONFIG_SOC_SHA_SUPPORT_SHA512_256=y CONFIG_SOC_SHA_SUPPORT_SHA512_T=y CONFIG_SOC_MPI_MEM_BLOCKS_NUM=4 CONFIG_SOC_MPI_OPERATIONS_NUM=3 CONFIG_SOC_RSA_MAX_BIT_LEN=4096 CONFIG_SOC_AES_SUPPORT_DMA=y CONFIG_SOC_AES_GDMA=y CONFIG_SOC_AES_SUPPORT_AES_128=y CONFIG_SOC_AES_SUPPORT_AES_256=y CONFIG_SOC_PM_SUPPORT_EXT0_WAKEUP=y CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP=y CONFIG_SOC_PM_SUPPORT_EXT_WAKEUP=y CONFIG_SOC_PM_SUPPORT_WIFI_WAKEUP=y CONFIG_SOC_PM_SUPPORT_BT_WAKEUP=y CONFIG_SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP=y CONFIG_SOC_PM_SUPPORT_CPU_PD=y CONFIG_SOC_PM_SUPPORT_TAGMEM_PD=y CONFIG_SOC_PM_SUPPORT_RTC_PERIPH_PD=y CONFIG_SOC_PM_SUPPORT_RC_FAST_PD=y CONFIG_SOC_PM_SUPPORT_VDDSDIO_PD=y CONFIG_SOC_PM_SUPPORT_MAC_BB_PD=y CONFIG_SOC_PM_SUPPORT_MODEM_PD=y CONFIG_SOC_CONFIGURABLE_VDDSDIO_SUPPORTED=y CONFIG_SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY=y CONFIG_SOC_PM_CPU_RETENTION_BY_RTCCNTL=y CONFIG_SOC_PM_MODEM_RETENTION_BY_BACKUPDMA=y CONFIG_SOC_PM_MODEM_PD_BY_SW=y CONFIG_SOC_CLK_RC_FAST_D256_SUPPORTED=y CONFIG_SOC_RTC_SLOW_CLK_SUPPORT_RC_FAST_D256=y CONFIG_SOC_CLK_RC_FAST_SUPPORT_CALIBRATION=y CONFIG_SOC_CLK_XTAL32K_SUPPORTED=y CONFIG_SOC_EFUSE_DIS_DOWNLOAD_ICACHE=y CONFIG_SOC_EFUSE_DIS_DOWNLOAD_DCACHE=y CONFIG_SOC_EFUSE_HARD_DIS_JTAG=y CONFIG_SOC_EFUSE_DIS_USB_JTAG=y CONFIG_SOC_EFUSE_SOFT_DIS_JTAG=y CONFIG_SOC_EFUSE_DIS_DIRECT_BOOT=y CONFIG_SOC_EFUSE_DIS_ICACHE=y CONFIG_SOC_EFUSE_BLOCK9_KEY_PURPOSE_QUIRK=y CONFIG_SOC_SECURE_BOOT_V2_RSA=y CONFIG_SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS=3 CONFIG_SOC_EFUSE_REVOKE_BOOT_KEY_DIGESTS=y CONFIG_SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY=y CONFIG_SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX=64 CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES=y CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_OPTIONS=y CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_128=y CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_256=y CONFIG_SOC_MEMPROT_CPU_PREFETCH_PAD_SIZE=16 CONFIG_SOC_MEMPROT_MEM_ALIGN_SIZE=256 CONFIG_SOC_PHY_DIG_REGS_MEM_SIZE=21 CONFIG_SOC_MAC_BB_PD_MEM_SIZE=192 CONFIG_SOC_WIFI_LIGHT_SLEEP_CLK_WIDTH=12 CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_WAIT_IDLE=y CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_SUSPEND=y CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_RESUME=y CONFIG_SOC_SPI_MEM_SUPPORT_SW_SUSPEND=y CONFIG_SOC_SPI_MEM_SUPPORT_OPI_MODE=y CONFIG_SOC_SPI_MEM_SUPPORT_TIMING_TUNING=y CONFIG_SOC_SPI_MEM_SUPPORT_CONFIG_GPIO_BY_EFUSE=y CONFIG_SOC_SPI_MEM_SUPPORT_WRAP=y CONFIG_SOC_MEMSPI_TIMING_TUNING_BY_MSPI_DELAY=y CONFIG_SOC_MEMSPI_CORE_CLK_SHARED_WITH_PSRAM=y CONFIG_SOC_SPI_MEM_SUPPORT_CACHE_32BIT_ADDR_MAP=y CONFIG_SOC_COEX_HW_PTI=y CONFIG_SOC_EXTERNAL_COEX_LEADER_TX_LINE=y CONFIG_SOC_SDMMC_USE_GPIO_MATRIX=y CONFIG_SOC_SDMMC_NUM_SLOTS=2 CONFIG_SOC_SDMMC_SUPPORT_XTAL_CLOCK=y CONFIG_SOC_SDMMC_DELAY_PHASE_NUM=4 CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_FAST_RC=y CONFIG_SOC_WIFI_HW_TSF=y CONFIG_SOC_WIFI_FTM_SUPPORT=y CONFIG_SOC_WIFI_GCMP_SUPPORT=y CONFIG_SOC_WIFI_WAPI_SUPPORT=y CONFIG_SOC_WIFI_CSI_SUPPORT=y CONFIG_SOC_WIFI_MESH_SUPPORT=y CONFIG_SOC_WIFI_SUPPORT_VARIABLE_BEACON_WINDOW=y CONFIG_SOC_WIFI_PHY_NEEDS_USB_WORKAROUND=y CONFIG_SOC_BLE_SUPPORTED=y CONFIG_SOC_BLE_MESH_SUPPORTED=y CONFIG_SOC_BLE_50_SUPPORTED=y CONFIG_SOC_BLE_DEVICE_PRIVACY_SUPPORTED=y CONFIG_SOC_BLUFI_SUPPORTED=y CONFIG_SOC_ULP_HAS_ADC=y CONFIG_SOC_PHY_COMBO_MODULE=y CONFIG_IDF_CMAKE=y CONFIG_IDF_TOOLCHAIN="gcc" CONFIG_IDF_TOOLCHAIN_GCC=y CONFIG_IDF_TARGET_ARCH_XTENSA=y CONFIG_IDF_TARGET_ARCH="xtensa" CONFIG_IDF_TARGET="esp32s3" CONFIG_IDF_INIT_VERSION="5.4.2" CONFIG_IDF_TARGET_ESP32S3=y CONFIG_IDF_FIRMWARE_CHIP_ID=0x0009 # # Build type # CONFIG_APP_BUILD_TYPE_APP_2NDBOOT=y # CONFIG_APP_BUILD_TYPE_RAM is not set CONFIG_APP_BUILD_GENERATE_BINARIES=y CONFIG_APP_BUILD_BOOTLOADER=y CONFIG_APP_BUILD_USE_FLASH_SECTIONS=y # CONFIG_APP_REPRODUCIBLE_BUILD is not set # CONFIG_APP_NO_BLOBS is not set # end of Build type # # Bootloader config # # # Bootloader manager # CONFIG_BOOTLOADER_COMPILE_TIME_DATE=y CONFIG_BOOTLOADER_PROJECT_VER=1 # end of Bootloader manager CONFIG_BOOTLOADER_OFFSET_IN_FLASH=0x0 CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG is not set # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF is not set # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_NONE is not set # # Log # # CONFIG_BOOTLOADER_LOG_LEVEL_NONE is not set # CONFIG_BOOTLOADER_LOG_LEVEL_ERROR is not set # CONFIG_BOOTLOADER_LOG_LEVEL_WARN is not set CONFIG_BOOTLOADER_LOG_LEVEL_INFO=y # CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG is not set # CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE is not set CONFIG_BOOTLOADER_LOG_LEVEL=3 # # Format # # CONFIG_BOOTLOADER_LOG_COLORS is not set CONFIG_BOOTLOADER_LOG_TIMESTAMP_SOURCE_CPU_TICKS=y # end of Format # end of Log # # Serial Flash Configurations # # CONFIG_BOOTLOADER_FLASH_DC_AWARE is not set CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT=y # end of Serial Flash Configurations CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_9V=y # CONFIG_BOOTLOADER_FACTORY_RESET is not set # CONFIG_BOOTLOADER_APP_TEST is not set CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE=y CONFIG_BOOTLOADER_WDT_ENABLE=y # CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE is not set CONFIG_BOOTLOADER_WDT_TIME_MS=9000 # CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS is not set CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0 # CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC is not set # end of Bootloader config # # Security features # CONFIG_SECURE_BOOT_V2_RSA_SUPPORTED=y CONFIG_SECURE_BOOT_V2_PREFERRED=y # CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT is not set # CONFIG_SECURE_BOOT is not set # CONFIG_SECURE_FLASH_ENC_ENABLED is not set CONFIG_SECURE_ROM_DL_MODE_ENABLED=y # end of Security features # # Application manager # CONFIG_APP_COMPILE_TIME_DATE=y # CONFIG_APP_EXCLUDE_PROJECT_VER_VAR is not set # CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR is not set # CONFIG_APP_PROJECT_VER_FROM_CONFIG is not set CONFIG_APP_RETRIEVE_LEN_ELF_SHA=9 # end of Application manager CONFIG_ESP_ROM_HAS_CRC_LE=y CONFIG_ESP_ROM_HAS_CRC_BE=y CONFIG_ESP_ROM_HAS_MZ_CRC32=y CONFIG_ESP_ROM_HAS_JPEG_DECODE=y CONFIG_ESP_ROM_UART_CLK_IS_XTAL=y CONFIG_ESP_ROM_HAS_RETARGETABLE_LOCKING=y CONFIG_ESP_ROM_USB_OTG_NUM=3 CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM=4 CONFIG_ESP_ROM_HAS_ERASE_0_REGION_BUG=y CONFIG_ESP_ROM_HAS_ENCRYPTED_WRITES_USING_LEGACY_DRV=y CONFIG_ESP_ROM_GET_CLK_FREQ=y CONFIG_ESP_ROM_HAS_HAL_WDT=y CONFIG_ESP_ROM_NEEDS_SWSETUP_WORKAROUND=y CONFIG_ESP_ROM_HAS_LAYOUT_TABLE=y CONFIG_ESP_ROM_HAS_SPI_FLASH=y CONFIG_ESP_ROM_HAS_ETS_PRINTF_BUG=y CONFIG_ESP_ROM_HAS_NEWLIB=y CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT=y CONFIG_ESP_ROM_HAS_NEWLIB_32BIT_TIME=y CONFIG_ESP_ROM_NEEDS_SET_CACHE_MMU_SIZE=y CONFIG_ESP_ROM_RAM_APP_NEEDS_MMU_INIT=y CONFIG_ESP_ROM_HAS_FLASH_COUNT_PAGES_BUG=y CONFIG_ESP_ROM_HAS_CACHE_SUSPEND_WAITI_BUG=y CONFIG_ESP_ROM_HAS_CACHE_WRITEBACK_BUG=y CONFIG_ESP_ROM_HAS_SW_FLOAT=y CONFIG_ESP_ROM_HAS_VERSION=y CONFIG_ESP_ROM_SUPPORT_DEEP_SLEEP_WAKEUP_STUB=y CONFIG_ESP_ROM_HAS_OUTPUT_PUTC_FUNC=y # # Boot ROM Behavior # CONFIG_BOOT_ROM_LOG_ALWAYS_ON=y # CONFIG_BOOT_ROM_LOG_ALWAYS_OFF is not set # CONFIG_BOOT_ROM_LOG_ON_GPIO_HIGH is not set # CONFIG_BOOT_ROM_LOG_ON_GPIO_LOW is not set # end of Boot ROM Behavior # # Serial flasher config # # CONFIG_ESPTOOLPY_NO_STUB is not set # CONFIG_ESPTOOLPY_OCT_FLASH is not set CONFIG_ESPTOOLPY_FLASH_MODE_AUTO_DETECT=y # CONFIG_ESPTOOLPY_FLASHMODE_QIO is not set # CONFIG_ESPTOOLPY_FLASHMODE_QOUT is not set CONFIG_ESPTOOLPY_FLASHMODE_DIO=y # CONFIG_ESPTOOLPY_FLASHMODE_DOUT is not set CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR=y CONFIG_ESPTOOLPY_FLASHMODE="dio" # CONFIG_ESPTOOLPY_FLASHFREQ_120M is not set CONFIG_ESPTOOLPY_FLASHFREQ_80M=y # CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set # CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set CONFIG_ESPTOOLPY_FLASHFREQ="80m" # CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y # CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set CONFIG_ESPTOOLPY_FLASHSIZE="2MB" # CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set CONFIG_ESPTOOLPY_BEFORE_RESET=y # CONFIG_ESPTOOLPY_BEFORE_NORESET is not set CONFIG_ESPTOOLPY_BEFORE="default_reset" CONFIG_ESPTOOLPY_AFTER_RESET=y # CONFIG_ESPTOOLPY_AFTER_NORESET is not set CONFIG_ESPTOOLPY_AFTER="hard_reset" CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 # end of Serial flasher config # # Partition Table # CONFIG_PARTITION_TABLE_SINGLE_APP=y # CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set # CONFIG_PARTITION_TABLE_TWO_OTA is not set # CONFIG_PARTITION_TABLE_TWO_OTA_LARGE is not set # CONFIG_PARTITION_TABLE_CUSTOM is not set CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" CONFIG_PARTITION_TABLE_FILENAME="partitions_singleapp.csv" CONFIG_PARTITION_TABLE_OFFSET=0x8000 CONFIG_PARTITION_TABLE_MD5=y # end of Partition Table # # Compiler options # CONFIG_COMPILER_OPTIMIZATION_DEBUG=y # CONFIG_COMPILER_OPTIMIZATION_SIZE is not set # CONFIG_COMPILER_OPTIMIZATION_PERF is not set # CONFIG_COMPILER_OPTIMIZATION_NONE is not set CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE=y # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT is not set # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set CONFIG_COMPILER_ASSERT_NDEBUG_EVALUATE=y CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB=y CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL=2 # CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT is not set CONFIG_COMPILER_HIDE_PATHS_MACROS=y # CONFIG_COMPILER_CXX_EXCEPTIONS is not set # CONFIG_COMPILER_CXX_RTTI is not set CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y # CONFIG_COMPILER_STACK_CHECK_MODE_NORM is not set # CONFIG_COMPILER_STACK_CHECK_MODE_STRONG is not set # CONFIG_COMPILER_STACK_CHECK_MODE_ALL is not set # CONFIG_COMPILER_NO_MERGE_CONSTANTS is not set # CONFIG_COMPILER_WARN_WRITE_STRINGS is not set CONFIG_COMPILER_DISABLE_DEFAULT_ERRORS=y # CONFIG_COMPILER_DISABLE_GCC12_WARNINGS is not set # CONFIG_COMPILER_DISABLE_GCC13_WARNINGS is not set # CONFIG_COMPILER_DISABLE_GCC14_WARNINGS is not set # CONFIG_COMPILER_DUMP_RTL_FILES is not set CONFIG_COMPILER_RT_LIB_GCCLIB=y CONFIG_COMPILER_RT_LIB_NAME="gcc" CONFIG_COMPILER_ORPHAN_SECTIONS_WARNING=y # CONFIG_COMPILER_ORPHAN_SECTIONS_PLACE is not set # CONFIG_COMPILER_STATIC_ANALYZER is not set # end of Compiler options # # Component config # # # Application Level Tracing # # CONFIG_APPTRACE_DEST_JTAG is not set CONFIG_APPTRACE_DEST_NONE=y # CONFIG_APPTRACE_DEST_UART1 is not set # CONFIG_APPTRACE_DEST_UART2 is not set # CONFIG_APPTRACE_DEST_USB_CDC is not set CONFIG_APPTRACE_DEST_UART_NONE=y CONFIG_APPTRACE_UART_TASK_PRIO=1 CONFIG_APPTRACE_LOCK_ENABLE=y # end of Application Level Tracing # # Bluetooth # # CONFIG_BT_ENABLED is not set # # Common Options # # CONFIG_BT_BLE_LOG_SPI_OUT_ENABLED is not set # end of Common Options # end of Bluetooth # # Console Library # # CONFIG_CONSOLE_SORTED_HELP is not set # end of Console Library # # Driver Configurations # # # TWAI Configuration # # CONFIG_TWAI_ISR_IN_IRAM is not set CONFIG_TWAI_ERRATA_FIX_LISTEN_ONLY_DOM=y # end of TWAI Configuration # # Legacy ADC Driver Configuration # # CONFIG_ADC_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_ADC_SKIP_LEGACY_CONFLICT_CHECK is not set # # Legacy ADC Calibration Configuration # # CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN is not set # end of Legacy ADC Calibration Configuration # end of Legacy ADC Driver Configuration # # Legacy MCPWM Driver Configurations # # CONFIG_MCPWM_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_MCPWM_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy MCPWM Driver Configurations # # Legacy Timer Group Driver Configurations # # CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_GPTIMER_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy Timer Group Driver Configurations # # Legacy RMT Driver Configurations # # CONFIG_RMT_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_RMT_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy RMT Driver Configurations # # Legacy I2S Driver Configurations # # CONFIG_I2S_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_I2S_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy I2S Driver Configurations # # Legacy I2C Driver Configurations # # CONFIG_I2C_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy I2C Driver Configurations # # Legacy PCNT Driver Configurations # # CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_PCNT_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy PCNT Driver Configurations # # Legacy SDM Driver Configurations # # CONFIG_SDM_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_SDM_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy SDM Driver Configurations # # Legacy Temperature Sensor Driver Configurations # # CONFIG_TEMP_SENSOR_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_TEMP_SENSOR_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy Temperature Sensor Driver Configurations # end of Driver Configurations # # eFuse Bit Manager # # CONFIG_EFUSE_CUSTOM_TABLE is not set # CONFIG_EFUSE_VIRTUAL is not set CONFIG_EFUSE_MAX_BLK_LEN=256 # end of eFuse Bit Manager # # ESP-TLS # CONFIG_ESP_TLS_USING_MBEDTLS=y CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y # CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is not set # CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is not set # CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK is not set # CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL is not set # CONFIG_ESP_TLS_PSK_VERIFICATION is not set # CONFIG_ESP_TLS_INSECURE is not set # end of ESP-TLS # # ADC and ADC Calibration # # CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM is not set # CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is not set # CONFIG_ADC_CONTINUOUS_FORCE_USE_ADC2_ON_C3_S3 is not set # CONFIG_ADC_ENABLE_DEBUG_LOG is not set # end of ADC and ADC Calibration # # Wireless Coexistence # CONFIG_ESP_COEX_ENABLED=y # CONFIG_ESP_COEX_EXTERNAL_COEXIST_ENABLE is not set # CONFIG_ESP_COEX_GPIO_DEBUG is not set # end of Wireless Coexistence # # Common ESP-related # CONFIG_ESP_ERR_TO_NAME_LOOKUP=y # end of Common ESP-related # # ESP-Driver:GPIO Configurations # # CONFIG_GPIO_CTRL_FUNC_IN_IRAM is not set # end of ESP-Driver:GPIO Configurations # # ESP-Driver:GPTimer Configurations # CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set # CONFIG_GPTIMER_ISR_IRAM_SAFE is not set CONFIG_GPTIMER_OBJ_CACHE_SAFE=y # CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:GPTimer Configurations # # ESP-Driver:I2C Configurations # # CONFIG_I2C_ISR_IRAM_SAFE is not set # CONFIG_I2C_ENABLE_DEBUG_LOG is not set # CONFIG_I2C_ENABLE_SLAVE_DRIVER_VERSION_2 is not set # end of ESP-Driver:I2C Configurations # # ESP-Driver:I2S Configurations # # CONFIG_I2S_ISR_IRAM_SAFE is not set # CONFIG_I2S_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:I2S Configurations # # ESP-Driver:LEDC Configurations # # CONFIG_LEDC_CTRL_FUNC_IN_IRAM is not set # end of ESP-Driver:LEDC Configurations # # ESP-Driver:MCPWM Configurations # # CONFIG_MCPWM_ISR_IRAM_SAFE is not set # CONFIG_MCPWM_CTRL_FUNC_IN_IRAM is not set # CONFIG_MCPWM_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:MCPWM Configurations # # ESP-Driver:PCNT Configurations # # CONFIG_PCNT_CTRL_FUNC_IN_IRAM is not set # CONFIG_PCNT_ISR_IRAM_SAFE is not set # CONFIG_PCNT_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:PCNT Configurations # # ESP-Driver:RMT Configurations # # CONFIG_RMT_ISR_IRAM_SAFE is not set # CONFIG_RMT_RECV_FUNC_IN_IRAM is not set # CONFIG_RMT_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:RMT Configurations # # ESP-Driver:Sigma Delta Modulator Configurations # # CONFIG_SDM_CTRL_FUNC_IN_IRAM is not set # CONFIG_SDM_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:Sigma Delta Modulator Configurations # # ESP-Driver:SPI Configurations # # CONFIG_SPI_MASTER_IN_IRAM is not set CONFIG_SPI_MASTER_ISR_IN_IRAM=y # CONFIG_SPI_SLAVE_IN_IRAM is not set CONFIG_SPI_SLAVE_ISR_IN_IRAM=y # end of ESP-Driver:SPI Configurations # # ESP-Driver:Touch Sensor Configurations # # CONFIG_TOUCH_CTRL_FUNC_IN_IRAM is not set # CONFIG_TOUCH_ISR_IRAM_SAFE is not set # CONFIG_TOUCH_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:Touch Sensor Configurations # # ESP-Driver:Temperature Sensor Configurations # # CONFIG_TEMP_SENSOR_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:Temperature Sensor Configurations # # ESP-Driver:UART Configurations # # CONFIG_UART_ISR_IN_IRAM is not set # end of ESP-Driver:UART Configurations # # ESP-Driver:USB Serial/JTAG Configuration # CONFIG_USJ_ENABLE_USB_SERIAL_JTAG=y # end of ESP-Driver:USB Serial/JTAG Configuration # # Ethernet # CONFIG_ETH_ENABLED=y CONFIG_ETH_USE_SPI_ETHERNET=y # CONFIG_ETH_SPI_ETHERNET_DM9051 is not set # CONFIG_ETH_SPI_ETHERNET_W5500 is not set # CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL is not set # CONFIG_ETH_USE_OPENETH is not set # CONFIG_ETH_TRANSMIT_MUTEX is not set # end of Ethernet # # Event Loop Library # # CONFIG_ESP_EVENT_LOOP_PROFILING is not set CONFIG_ESP_EVENT_POST_FROM_ISR=y CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR=y # end of Event Loop Library # # GDB Stub # CONFIG_ESP_GDBSTUB_ENABLED=y # CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME is not set CONFIG_ESP_GDBSTUB_SUPPORT_TASKS=y CONFIG_ESP_GDBSTUB_MAX_TASKS=32 # end of GDB Stub # # ESP HID # CONFIG_ESPHID_TASK_SIZE_BT=2048 CONFIG_ESPHID_TASK_SIZE_BLE=4096 # end of ESP HID # # ESP HTTP client # CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y # CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH is not set # CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH is not set # CONFIG_ESP_HTTP_CLIENT_ENABLE_CUSTOM_TRANSPORT is not set CONFIG_ESP_HTTP_CLIENT_EVENT_POST_TIMEOUT=2000 # end of ESP HTTP client # # HTTP Server # CONFIG_HTTPD_MAX_REQ_HDR_LEN=512 CONFIG_HTTPD_MAX_URI_LEN=512 CONFIG_HTTPD_ERR_RESP_NO_DELAY=y CONFIG_HTTPD_PURGE_BUF_LEN=32 # CONFIG_HTTPD_LOG_PURGE_DATA is not set # CONFIG_HTTPD_WS_SUPPORT is not set # CONFIG_HTTPD_QUEUE_WORK_BLOCKING is not set CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT=2000 # end of HTTP Server # # ESP HTTPS OTA # # CONFIG_ESP_HTTPS_OTA_DECRYPT_CB is not set # CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP is not set CONFIG_ESP_HTTPS_OTA_EVENT_POST_TIMEOUT=2000 # end of ESP HTTPS OTA # # ESP HTTPS server # # CONFIG_ESP_HTTPS_SERVER_ENABLE is not set CONFIG_ESP_HTTPS_SERVER_EVENT_POST_TIMEOUT=2000 # end of ESP HTTPS server # # Hardware Settings # # # Chip revision # CONFIG_ESP32S3_REV_MIN_0=y # CONFIG_ESP32S3_REV_MIN_1 is not set # CONFIG_ESP32S3_REV_MIN_2 is not set CONFIG_ESP32S3_REV_MIN_FULL=0 CONFIG_ESP_REV_MIN_FULL=0 # # Maximum Supported ESP32-S3 Revision (Rev v0.99) # CONFIG_ESP32S3_REV_MAX_FULL=99 CONFIG_ESP_REV_MAX_FULL=99 CONFIG_ESP_EFUSE_BLOCK_REV_MIN_FULL=0 CONFIG_ESP_EFUSE_BLOCK_REV_MAX_FULL=199 # # Maximum Supported ESP32-S3 eFuse Block Revision (eFuse Block Rev v1.99) # # end of Chip revision # # MAC Config # CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_STA=y CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP=y CONFIG_ESP_MAC_ADDR_UNIVERSE_BT=y CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH=y CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES_FOUR=y CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES=4 # CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES_TWO is not set CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES_FOUR=y CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES=4 # CONFIG_ESP_MAC_USE_CUSTOM_MAC_AS_BASE_MAC is not set # end of MAC Config # # Sleep Config # CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND=y CONFIG_ESP_SLEEP_PSRAM_LEAKAGE_WORKAROUND=y CONFIG_ESP_SLEEP_MSPI_NEED_ALL_IO_PU=y CONFIG_ESP_SLEEP_RTC_BUS_ISO_WORKAROUND=y CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND=y CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY=2000 # CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION is not set # CONFIG_ESP_SLEEP_DEBUG is not set CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS=y # end of Sleep Config # # RTC Clock Config # CONFIG_RTC_CLK_SRC_INT_RC=y # CONFIG_RTC_CLK_SRC_EXT_CRYS is not set # CONFIG_RTC_CLK_SRC_EXT_OSC is not set # CONFIG_RTC_CLK_SRC_INT_8MD256 is not set CONFIG_RTC_CLK_CAL_CYCLES=1024 # end of RTC Clock Config # # Peripheral Control # CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y # end of Peripheral Control # # GDMA Configurations # CONFIG_GDMA_CTRL_FUNC_IN_IRAM=y CONFIG_GDMA_ISR_HANDLER_IN_IRAM=y CONFIG_GDMA_OBJ_DRAM_SAFE=y # CONFIG_GDMA_ENABLE_DEBUG_LOG is not set # CONFIG_GDMA_ISR_IRAM_SAFE is not set # end of GDMA Configurations # # Main XTAL Config # CONFIG_XTAL_FREQ_40=y CONFIG_XTAL_FREQ=40 # end of Main XTAL Config CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y # end of Hardware Settings # # ESP-Driver:LCD Controller Configurations # # CONFIG_LCD_ENABLE_DEBUG_LOG is not set # CONFIG_LCD_RGB_ISR_IRAM_SAFE is not set # CONFIG_LCD_RGB_RESTART_IN_VSYNC is not set # end of ESP-Driver:LCD Controller Configurations # # ESP-MM: Memory Management Configurations # # CONFIG_ESP_MM_CACHE_MSYNC_C2M_CHUNKED_OPS is not set # end of ESP-MM: Memory Management Configurations # # ESP NETIF Adapter # CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL=120 # CONFIG_ESP_NETIF_PROVIDE_CUSTOM_IMPLEMENTATION is not set CONFIG_ESP_NETIF_TCPIP_LWIP=y # CONFIG_ESP_NETIF_LOOPBACK is not set CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y CONFIG_ESP_NETIF_REPORT_DATA_TRAFFIC=y # CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS is not set # CONFIG_ESP_NETIF_L2_TAP is not set # CONFIG_ESP_NETIF_BRIDGE_EN is not set # CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF is not set # end of ESP NETIF Adapter # # Partition API Configuration # # end of Partition API Configuration # # PHY # CONFIG_ESP_PHY_ENABLED=y CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE=y # CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION is not set CONFIG_ESP_PHY_MAX_WIFI_TX_POWER=20 CONFIG_ESP_PHY_MAX_TX_POWER=20 # CONFIG_ESP_PHY_REDUCE_TX_POWER is not set CONFIG_ESP_PHY_ENABLE_USB=y # CONFIG_ESP_PHY_ENABLE_CERT_TEST is not set CONFIG_ESP_PHY_RF_CAL_PARTIAL=y # CONFIG_ESP_PHY_RF_CAL_NONE is not set # CONFIG_ESP_PHY_RF_CAL_FULL is not set CONFIG_ESP_PHY_CALIBRATION_MODE=0 # CONFIG_ESP_PHY_PLL_TRACK_DEBUG is not set # CONFIG_ESP_PHY_RECORD_USED_TIME is not set # end of PHY # # Power Management # # CONFIG_PM_ENABLE is not set # CONFIG_PM_SLP_IRAM_OPT is not set CONFIG_PM_POWER_DOWN_CPU_IN_LIGHT_SLEEP=y CONFIG_PM_RESTORE_CACHE_TAGMEM_AFTER_LIGHT_SLEEP=y # end of Power Management # # ESP PSRAM # CONFIG_SPIRAM=y # # SPI RAM config # # CONFIG_SPIRAM_MODE_QUAD is not set CONFIG_SPIRAM_MODE_OCT=y CONFIG_SPIRAM_TYPE_AUTO=y # CONFIG_SPIRAM_TYPE_ESPPSRAM64 is not set CONFIG_SPIRAM_CLK_IO=30 CONFIG_SPIRAM_CS_IO=26 # CONFIG_SPIRAM_XIP_FROM_PSRAM is not set # CONFIG_SPIRAM_FETCH_INSTRUCTIONS is not set # CONFIG_SPIRAM_RODATA is not set # CONFIG_SPIRAM_SPEED_80M is not set CONFIG_SPIRAM_SPEED_40M=y CONFIG_SPIRAM_SPEED=40 # CONFIG_SPIRAM_ECC_ENABLE is not set CONFIG_SPIRAM_BOOT_INIT=y CONFIG_SPIRAM_PRE_CONFIGURE_MEMORY_PROTECTION=y # CONFIG_SPIRAM_IGNORE_NOTFOUND is not set # CONFIG_SPIRAM_USE_MEMMAP is not set # CONFIG_SPIRAM_USE_CAPS_ALLOC is not set CONFIG_SPIRAM_USE_MALLOC=y CONFIG_SPIRAM_MEMTEST=y CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=16384 # CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP is not set CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL=32768 # CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY is not set # CONFIG_SPIRAM_ALLOW_NOINIT_SEG_EXTERNAL_MEMORY is not set # end of SPI RAM config # end of ESP PSRAM # # ESP Ringbuf # # CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH is not set # end of ESP Ringbuf # # ESP Security Specific # # end of ESP Security Specific # # ESP System Settings # # CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_80 is not set # CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160 is not set CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240=y CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=240 # # Cache config # CONFIG_ESP32S3_INSTRUCTION_CACHE_16KB=y # CONFIG_ESP32S3_INSTRUCTION_CACHE_32KB is not set CONFIG_ESP32S3_INSTRUCTION_CACHE_SIZE=0x4000 # CONFIG_ESP32S3_INSTRUCTION_CACHE_4WAYS is not set CONFIG_ESP32S3_INSTRUCTION_CACHE_8WAYS=y CONFIG_ESP32S3_ICACHE_ASSOCIATED_WAYS=8 # CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_16B is not set CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_32B=y CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_SIZE=32 # CONFIG_ESP32S3_DATA_CACHE_16KB is not set CONFIG_ESP32S3_DATA_CACHE_32KB=y # CONFIG_ESP32S3_DATA_CACHE_64KB is not set CONFIG_ESP32S3_DATA_CACHE_SIZE=0x8000 # CONFIG_ESP32S3_DATA_CACHE_4WAYS is not set CONFIG_ESP32S3_DATA_CACHE_8WAYS=y CONFIG_ESP32S3_DCACHE_ASSOCIATED_WAYS=8 # CONFIG_ESP32S3_DATA_CACHE_LINE_16B is not set CONFIG_ESP32S3_DATA_CACHE_LINE_32B=y # CONFIG_ESP32S3_DATA_CACHE_LINE_64B is not set CONFIG_ESP32S3_DATA_CACHE_LINE_SIZE=32 # end of Cache config # # Memory # # CONFIG_ESP32S3_RTCDATA_IN_FAST_MEM is not set # CONFIG_ESP32S3_USE_FIXED_STATIC_RAM_SIZE is not set # end of Memory # # Trace memory # # CONFIG_ESP32S3_TRAX is not set CONFIG_ESP32S3_TRACEMEM_RESERVE_DRAM=0x0 # end of Trace memory # CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT is not set CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y # CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set # CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=0 CONFIG_ESP_SYSTEM_RTC_FAST_MEM_AS_HEAP_DEPCHECK=y CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP=y # # Memory protection # CONFIG_ESP_SYSTEM_MEMPROT_FEATURE=y CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK=y # end of Memory protection CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=2304 CONFIG_ESP_MAIN_TASK_STACK_SIZE=10240 CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0=y # CONFIG_ESP_MAIN_TASK_AFFINITY_CPU1 is not set # CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY is not set CONFIG_ESP_MAIN_TASK_AFFINITY=0x0 CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE=2048 CONFIG_ESP_CONSOLE_UART_DEFAULT=y # CONFIG_ESP_CONSOLE_USB_CDC is not set # CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG is not set # CONFIG_ESP_CONSOLE_UART_CUSTOM is not set # CONFIG_ESP_CONSOLE_NONE is not set # CONFIG_ESP_CONSOLE_SECONDARY_NONE is not set CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y CONFIG_ESP_CONSOLE_UART=y CONFIG_ESP_CONSOLE_UART_NUM=0 CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0 CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200 CONFIG_ESP_INT_WDT=y CONFIG_ESP_INT_WDT_TIMEOUT_MS=300 CONFIG_ESP_INT_WDT_CHECK_CPU1=y CONFIG_ESP_TASK_WDT_EN=y CONFIG_ESP_TASK_WDT_INIT=y # CONFIG_ESP_TASK_WDT_PANIC is not set CONFIG_ESP_TASK_WDT_TIMEOUT_S=5 CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=y CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1=y # CONFIG_ESP_PANIC_HANDLER_IRAM is not set # CONFIG_ESP_DEBUG_STUBS_ENABLE is not set CONFIG_ESP_DEBUG_OCDAWARE=y CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4=y # # Brownout Detector # CONFIG_ESP_BROWNOUT_DET=y CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7=y # CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set # CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set # CONFIG_ESP_BROWNOUT_DET_LVL_SEL_4 is not set # CONFIG_ESP_BROWNOUT_DET_LVL_SEL_3 is not set # CONFIG_ESP_BROWNOUT_DET_LVL_SEL_2 is not set # CONFIG_ESP_BROWNOUT_DET_LVL_SEL_1 is not set CONFIG_ESP_BROWNOUT_DET_LVL=7 # end of Brownout Detector CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y CONFIG_ESP_SYSTEM_BBPLL_RECALIB=y # end of ESP System Settings # # IPC (Inter-Processor Call) # CONFIG_ESP_IPC_TASK_STACK_SIZE=1280 CONFIG_ESP_IPC_USES_CALLERS_PRIORITY=y CONFIG_ESP_IPC_ISR_ENABLE=y # end of IPC (Inter-Processor Call) # # ESP Timer (High Resolution Timer) # # CONFIG_ESP_TIMER_PROFILING is not set CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER=y CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER=y CONFIG_ESP_TIMER_TASK_STACK_SIZE=3584 CONFIG_ESP_TIMER_INTERRUPT_LEVEL=1 # CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL is not set CONFIG_ESP_TIMER_TASK_AFFINITY=0x0 CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0=y CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0=y # CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is not set CONFIG_ESP_TIMER_IMPL_SYSTIMER=y # end of ESP Timer (High Resolution Timer) # # Wi-Fi # CONFIG_ESP_WIFI_ENABLED=y CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=10 CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32 # CONFIG_ESP_WIFI_STATIC_TX_BUFFER is not set CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER=y CONFIG_ESP_WIFI_TX_BUFFER_TYPE=1 CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=32 CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER=y # CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUFFER is not set CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF=0 CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF=5 # CONFIG_ESP_WIFI_CSI_ENABLED is not set CONFIG_ESP_WIFI_AMPDU_TX_ENABLED=y CONFIG_ESP_WIFI_TX_BA_WIN=6 CONFIG_ESP_WIFI_AMPDU_RX_ENABLED=y CONFIG_ESP_WIFI_RX_BA_WIN=6 CONFIG_ESP_WIFI_NVS_ENABLED=y CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0=y # CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_1 is not set CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN=752 CONFIG_ESP_WIFI_MGMT_SBUF_NUM=32 CONFIG_ESP_WIFI_IRAM_OPT=y # CONFIG_ESP_WIFI_EXTRA_IRAM_OPT is not set CONFIG_ESP_WIFI_RX_IRAM_OPT=y CONFIG_ESP_WIFI_ENABLE_WPA3_SAE=y CONFIG_ESP_WIFI_ENABLE_SAE_PK=y CONFIG_ESP_WIFI_SOFTAP_SAE_SUPPORT=y CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA=y # CONFIG_ESP_WIFI_SLP_IRAM_OPT is not set CONFIG_ESP_WIFI_SLP_DEFAULT_MIN_ACTIVE_TIME=50 CONFIG_ESP_WIFI_SLP_DEFAULT_MAX_ACTIVE_TIME=10 CONFIG_ESP_WIFI_SLP_DEFAULT_WAIT_BROADCAST_DATA_TIME=15 # CONFIG_ESP_WIFI_FTM_ENABLE is not set CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE=y # CONFIG_ESP_WIFI_GCMP_SUPPORT is not set CONFIG_ESP_WIFI_GMAC_SUPPORT=y CONFIG_ESP_WIFI_SOFTAP_SUPPORT=y # CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT is not set CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM=7 CONFIG_ESP_WIFI_MBEDTLS_CRYPTO=y CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT=y # CONFIG_ESP_WIFI_WAPI_PSK is not set # CONFIG_ESP_WIFI_SUITE_B_192 is not set # CONFIG_ESP_WIFI_11KV_SUPPORT is not set # CONFIG_ESP_WIFI_MBO_SUPPORT is not set # CONFIG_ESP_WIFI_DPP_SUPPORT is not set # CONFIG_ESP_WIFI_11R_SUPPORT is not set # CONFIG_ESP_WIFI_WPS_SOFTAP_REGISTRAR is not set # # WPS Configuration Options # # CONFIG_ESP_WIFI_WPS_STRICT is not set # CONFIG_ESP_WIFI_WPS_PASSPHRASE is not set # end of WPS Configuration Options # CONFIG_ESP_WIFI_DEBUG_PRINT is not set # CONFIG_ESP_WIFI_TESTING_OPTIONS is not set CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT=y # CONFIG_ESP_WIFI_ENT_FREE_DYNAMIC_BUFFER is not set # end of Wi-Fi # # Core dump # # CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH is not set # CONFIG_ESP_COREDUMP_ENABLE_TO_UART is not set CONFIG_ESP_COREDUMP_ENABLE_TO_NONE=y # end of Core dump # # FAT Filesystem support # CONFIG_FATFS_VOLUME_COUNT=2 CONFIG_FATFS_LFN_NONE=y # CONFIG_FATFS_LFN_HEAP is not set # CONFIG_FATFS_LFN_STACK is not set # CONFIG_FATFS_SECTOR_512 is not set CONFIG_FATFS_SECTOR_4096=y # CONFIG_FATFS_CODEPAGE_DYNAMIC is not set CONFIG_FATFS_CODEPAGE_437=y # CONFIG_FATFS_CODEPAGE_720 is not set # CONFIG_FATFS_CODEPAGE_737 is not set # CONFIG_FATFS_CODEPAGE_771 is not set # CONFIG_FATFS_CODEPAGE_775 is not set # CONFIG_FATFS_CODEPAGE_850 is not set # CONFIG_FATFS_CODEPAGE_852 is not set # CONFIG_FATFS_CODEPAGE_855 is not set # CONFIG_FATFS_CODEPAGE_857 is not set # CONFIG_FATFS_CODEPAGE_860 is not set # CONFIG_FATFS_CODEPAGE_861 is not set # CONFIG_FATFS_CODEPAGE_862 is not set # CONFIG_FATFS_CODEPAGE_863 is not set # CONFIG_FATFS_CODEPAGE_864 is not set # CONFIG_FATFS_CODEPAGE_865 is not set # CONFIG_FATFS_CODEPAGE_866 is not set # CONFIG_FATFS_CODEPAGE_869 is not set # CONFIG_FATFS_CODEPAGE_932 is not set # CONFIG_FATFS_CODEPAGE_936 is not set # CONFIG_FATFS_CODEPAGE_949 is not set # CONFIG_FATFS_CODEPAGE_950 is not set CONFIG_FATFS_CODEPAGE=437 CONFIG_FATFS_FS_LOCK=0 CONFIG_FATFS_TIMEOUT_MS=10000 CONFIG_FATFS_PER_FILE_CACHE=y CONFIG_FATFS_ALLOC_PREFER_EXTRAM=y # CONFIG_FATFS_USE_FASTSEEK is not set CONFIG_FATFS_USE_STRFUNC_NONE=y # CONFIG_FATFS_USE_STRFUNC_WITHOUT_CRLF_CONV is not set # CONFIG_FATFS_USE_STRFUNC_WITH_CRLF_CONV is not set CONFIG_FATFS_VFS_FSTAT_BLKSIZE=0 # CONFIG_FATFS_IMMEDIATE_FSYNC is not set # CONFIG_FATFS_USE_LABEL is not set CONFIG_FATFS_LINK_LOCK=y # CONFIG_FATFS_USE_DYN_BUFFERS is not set # # File system free space calculation behavior # CONFIG_FATFS_DONT_TRUST_FREE_CLUSTER_CNT=0 CONFIG_FATFS_DONT_TRUST_LAST_ALLOC=0 # end of File system free space calculation behavior # end of FAT Filesystem support # # FreeRTOS # # # Kernel # # CONFIG_FREERTOS_SMP is not set # CONFIG_FREERTOS_UNICORE is not set CONFIG_FREERTOS_HZ=100 # CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE is not set # CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL is not set CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY=y CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=1 CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536 # CONFIG_FREERTOS_USE_IDLE_HOOK is not set # CONFIG_FREERTOS_USE_TICK_HOOK is not set CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16 # CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY is not set CONFIG_FREERTOS_USE_TIMERS=y CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME="Tmr Svc" # CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU0 is not set # CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU1 is not set CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY=y CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY=0x7FFFFFFF CONFIG_FREERTOS_TIMER_TASK_PRIORITY=1 CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048 CONFIG_FREERTOS_TIMER_QUEUE_LENGTH=10 CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE=0 CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=1 # CONFIG_FREERTOS_USE_TRACE_FACILITY is not set # CONFIG_FREERTOS_USE_LIST_DATA_INTEGRITY_CHECK_BYTES is not set # CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS is not set # CONFIG_FREERTOS_USE_APPLICATION_TASK_TAG is not set # end of Kernel # # Port # CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER=y # CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK is not set CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS=y # CONFIG_FREERTOS_TASK_PRE_DELETION_HOOK is not set # CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP is not set CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER=y CONFIG_FREERTOS_ISR_STACKSIZE=1536 CONFIG_FREERTOS_INTERRUPT_BACKTRACE=y # CONFIG_FREERTOS_FPU_IN_ISR is not set CONFIG_FREERTOS_TICK_SUPPORT_SYSTIMER=y CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1=y # CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL3 is not set CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER=y # CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH is not set # CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE is not set # end of Port # # Extra # CONFIG_FREERTOS_TASK_CREATE_ALLOW_EXT_MEM=y # end of Extra CONFIG_FREERTOS_PORT=y CONFIG_FREERTOS_NO_AFFINITY=0x7FFFFFFF CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y CONFIG_FREERTOS_DEBUG_OCDAWARE=y CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT=y CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y CONFIG_FREERTOS_NUMBER_OF_CORES=2 # end of FreeRTOS # # Hardware Abstraction Layer (HAL) and Low Level (LL) # CONFIG_HAL_ASSERTION_EQUALS_SYSTEM=y # CONFIG_HAL_ASSERTION_DISABLE is not set # CONFIG_HAL_ASSERTION_SILENT is not set # CONFIG_HAL_ASSERTION_ENABLE is not set CONFIG_HAL_DEFAULT_ASSERTION_LEVEL=2 CONFIG_HAL_WDT_USE_ROM_IMPL=y CONFIG_HAL_SPI_MASTER_FUNC_IN_IRAM=y CONFIG_HAL_SPI_SLAVE_FUNC_IN_IRAM=y # end of Hardware Abstraction Layer (HAL) and Low Level (LL) # # Heap memory debugging # CONFIG_HEAP_POISONING_DISABLED=y # CONFIG_HEAP_POISONING_LIGHT is not set # CONFIG_HEAP_POISONING_COMPREHENSIVE is not set CONFIG_HEAP_TRACING_OFF=y # CONFIG_HEAP_TRACING_STANDALONE is not set # CONFIG_HEAP_TRACING_TOHOST is not set # CONFIG_HEAP_USE_HOOKS is not set # CONFIG_HEAP_TASK_TRACKING is not set # CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS is not set # CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH is not set # end of Heap memory debugging # # Log # # # Log Level # # CONFIG_LOG_DEFAULT_LEVEL_NONE is not set # CONFIG_LOG_DEFAULT_LEVEL_ERROR is not set # CONFIG_LOG_DEFAULT_LEVEL_WARN is not set CONFIG_LOG_DEFAULT_LEVEL_INFO=y # CONFIG_LOG_DEFAULT_LEVEL_DEBUG is not set # CONFIG_LOG_DEFAULT_LEVEL_VERBOSE is not set CONFIG_LOG_DEFAULT_LEVEL=3 CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT=y # CONFIG_LOG_MAXIMUM_LEVEL_DEBUG is not set # CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE is not set CONFIG_LOG_MAXIMUM_LEVEL=3 # # Level Settings # # CONFIG_LOG_MASTER_LEVEL is not set CONFIG_LOG_DYNAMIC_LEVEL_CONTROL=y # CONFIG_LOG_TAG_LEVEL_IMPL_NONE is not set # CONFIG_LOG_TAG_LEVEL_IMPL_LINKED_LIST is not set CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_AND_LINKED_LIST=y # CONFIG_LOG_TAG_LEVEL_CACHE_ARRAY is not set CONFIG_LOG_TAG_LEVEL_CACHE_BINARY_MIN_HEAP=y CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_SIZE=31 # end of Level Settings # end of Log Level # # Format # # CONFIG_LOG_COLORS is not set CONFIG_LOG_TIMESTAMP_SOURCE_RTOS=y # CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM is not set # end of Format # end of Log # # LWIP # CONFIG_LWIP_ENABLE=y CONFIG_LWIP_LOCAL_HOSTNAME="espressif" # CONFIG_LWIP_NETIF_API is not set CONFIG_LWIP_TCPIP_TASK_PRIO=18 # CONFIG_LWIP_TCPIP_CORE_LOCKING is not set # CONFIG_LWIP_CHECK_THREAD_SAFETY is not set CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y # CONFIG_LWIP_L2_TO_L3_COPY is not set # CONFIG_LWIP_IRAM_OPTIMIZATION is not set # CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION is not set CONFIG_LWIP_TIMERS_ONDEMAND=y CONFIG_LWIP_ND6=y # CONFIG_LWIP_FORCE_ROUTER_FORWARDING is not set CONFIG_LWIP_MAX_SOCKETS=10 # CONFIG_LWIP_USE_ONLY_LWIP_SELECT is not set # CONFIG_LWIP_SO_LINGER is not set CONFIG_LWIP_SO_REUSE=y CONFIG_LWIP_SO_REUSE_RXTOALL=y # CONFIG_LWIP_SO_RCVBUF is not set # CONFIG_LWIP_NETBUF_RECVINFO is not set CONFIG_LWIP_IP_DEFAULT_TTL=64 CONFIG_LWIP_IP4_FRAG=y CONFIG_LWIP_IP6_FRAG=y # CONFIG_LWIP_IP4_REASSEMBLY is not set # CONFIG_LWIP_IP6_REASSEMBLY is not set CONFIG_LWIP_IP_REASS_MAX_PBUFS=10 # CONFIG_LWIP_IP_FORWARD is not set # CONFIG_LWIP_STATS is not set CONFIG_LWIP_ESP_GRATUITOUS_ARP=y CONFIG_LWIP_GARP_TMR_INTERVAL=60 CONFIG_LWIP_ESP_MLDV6_REPORT=y CONFIG_LWIP_MLDV6_TMR_INTERVAL=40 CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32 CONFIG_LWIP_DHCP_DOES_ARP_CHECK=y # CONFIG_LWIP_DHCP_DOES_ACD_CHECK is not set # CONFIG_LWIP_DHCP_DOES_NOT_CHECK_OFFERED_IP is not set # CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID is not set CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID=y # CONFIG_LWIP_DHCP_RESTORE_LAST_IP is not set CONFIG_LWIP_DHCP_OPTIONS_LEN=68 CONFIG_LWIP_NUM_NETIF_CLIENT_DATA=0 CONFIG_LWIP_DHCP_COARSE_TIMER_SECS=1 # # DHCP server # CONFIG_LWIP_DHCPS=y CONFIG_LWIP_DHCPS_LEASE_UNIT=60 CONFIG_LWIP_DHCPS_MAX_STATION_NUM=8 CONFIG_LWIP_DHCPS_STATIC_ENTRIES=y CONFIG_LWIP_DHCPS_ADD_DNS=y # end of DHCP server # CONFIG_LWIP_AUTOIP is not set CONFIG_LWIP_IPV4=y CONFIG_LWIP_IPV6=y # CONFIG_LWIP_IPV6_AUTOCONFIG is not set CONFIG_LWIP_IPV6_NUM_ADDRESSES=3 # CONFIG_LWIP_IPV6_FORWARD is not set # CONFIG_LWIP_NETIF_STATUS_CALLBACK is not set CONFIG_LWIP_NETIF_LOOPBACK=y CONFIG_LWIP_LOOPBACK_MAX_PBUFS=8 # # TCP # CONFIG_LWIP_MAX_ACTIVE_TCP=16 CONFIG_LWIP_MAX_LISTENING_TCP=16 CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION=y CONFIG_LWIP_TCP_MAXRTX=12 CONFIG_LWIP_TCP_SYNMAXRTX=12 CONFIG_LWIP_TCP_MSS=1440 CONFIG_LWIP_TCP_TMR_INTERVAL=250 CONFIG_LWIP_TCP_MSL=60000 CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT=20000 CONFIG_LWIP_TCP_SND_BUF_DEFAULT=5760 CONFIG_LWIP_TCP_WND_DEFAULT=5760 CONFIG_LWIP_TCP_RECVMBOX_SIZE=6 CONFIG_LWIP_TCP_ACCEPTMBOX_SIZE=6 CONFIG_LWIP_TCP_QUEUE_OOSEQ=y CONFIG_LWIP_TCP_OOSEQ_TIMEOUT=6 CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS=4 # CONFIG_LWIP_TCP_SACK_OUT is not set CONFIG_LWIP_TCP_OVERSIZE_MSS=y # CONFIG_LWIP_TCP_OVERSIZE_QUARTER_MSS is not set # CONFIG_LWIP_TCP_OVERSIZE_DISABLE is not set CONFIG_LWIP_TCP_RTO_TIME=1500 # end of TCP # # UDP # CONFIG_LWIP_MAX_UDP_PCBS=16 CONFIG_LWIP_UDP_RECVMBOX_SIZE=6 # end of UDP # # Checksums # # CONFIG_LWIP_CHECKSUM_CHECK_IP is not set # CONFIG_LWIP_CHECKSUM_CHECK_UDP is not set CONFIG_LWIP_CHECKSUM_CHECK_ICMP=y # end of Checksums CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=3072 CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0 is not set # CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU1 is not set CONFIG_LWIP_TCPIP_TASK_AFFINITY=0x7FFFFFFF CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE=3 CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS=5 CONFIG_LWIP_IPV6_ND6_NUM_PREFIXES=5 CONFIG_LWIP_IPV6_ND6_NUM_ROUTERS=3 CONFIG_LWIP_IPV6_ND6_NUM_DESTINATIONS=10 # CONFIG_LWIP_PPP_SUPPORT is not set # CONFIG_LWIP_SLIP_SUPPORT is not set # # ICMP # CONFIG_LWIP_ICMP=y # CONFIG_LWIP_MULTICAST_PING is not set # CONFIG_LWIP_BROADCAST_PING is not set # end of ICMP # # LWIP RAW API # CONFIG_LWIP_MAX_RAW_PCBS=16 # end of LWIP RAW API # # SNTP # CONFIG_LWIP_SNTP_MAX_SERVERS=1 # CONFIG_LWIP_DHCP_GET_NTP_SRV is not set CONFIG_LWIP_SNTP_UPDATE_DELAY=3600000 CONFIG_LWIP_SNTP_STARTUP_DELAY=y CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY=5000 # end of SNTP # # DNS # CONFIG_LWIP_DNS_MAX_HOST_IP=1 CONFIG_LWIP_DNS_MAX_SERVERS=3 # CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT is not set # CONFIG_LWIP_DNS_SETSERVER_WITH_NETIF is not set # end of DNS CONFIG_LWIP_BRIDGEIF_MAX_PORTS=7 CONFIG_LWIP_ESP_LWIP_ASSERT=y # # Hooks # # CONFIG_LWIP_HOOK_TCP_ISN_NONE is not set CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT=y # CONFIG_LWIP_HOOK_TCP_ISN_CUSTOM is not set CONFIG_LWIP_HOOK_IP6_ROUTE_NONE=y # CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT is not set # CONFIG_LWIP_HOOK_IP6_ROUTE_CUSTOM is not set CONFIG_LWIP_HOOK_ND6_GET_GW_NONE=y # CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT is not set # CONFIG_LWIP_HOOK_ND6_GET_GW_CUSTOM is not set CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE=y # CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT is not set # CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM is not set CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE=y # CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT is not set # CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not set CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_NONE=y # CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_CUSTOM is not set # CONFIG_LWIP_HOOK_IP6_INPUT_NONE is not set CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT=y # CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM is not set # end of Hooks # CONFIG_LWIP_DEBUG is not set # end of LWIP # # mbedTLS # CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y # CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC is not set # CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC is not set # CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC is not set CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384 CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096 # CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set # CONFIG_MBEDTLS_DEBUG is not set # # mbedTLS v3.x related # # CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 is not set # CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set # CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK is not set # CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y CONFIG_MBEDTLS_PKCS7_C=y # end of mbedTLS v3.x related # # Certificate Bundle # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=y # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN is not set # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE is not set # CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE is not set # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEPRECATED_LIST is not set CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS=200 # end of Certificate Bundle # CONFIG_MBEDTLS_ECP_RESTARTABLE is not set CONFIG_MBEDTLS_CMAC_C=y CONFIG_MBEDTLS_HARDWARE_AES=y CONFIG_MBEDTLS_AES_USE_INTERRUPT=y CONFIG_MBEDTLS_AES_INTERRUPT_LEVEL=0 CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y CONFIG_MBEDTLS_HARDWARE_MPI=y # CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI is not set CONFIG_MBEDTLS_MPI_USE_INTERRUPT=y CONFIG_MBEDTLS_MPI_INTERRUPT_LEVEL=0 CONFIG_MBEDTLS_HARDWARE_SHA=y CONFIG_MBEDTLS_ROM_MD5=y # CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set # CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set CONFIG_MBEDTLS_HAVE_TIME=y # CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set # CONFIG_MBEDTLS_HAVE_TIME_DATE is not set CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y CONFIG_MBEDTLS_SHA1_C=y CONFIG_MBEDTLS_SHA512_C=y # CONFIG_MBEDTLS_SHA3_C is not set CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT=y # CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set # CONFIG_MBEDTLS_TLS_CLIENT_ONLY is not set # CONFIG_MBEDTLS_TLS_DISABLED is not set CONFIG_MBEDTLS_TLS_SERVER=y CONFIG_MBEDTLS_TLS_CLIENT=y CONFIG_MBEDTLS_TLS_ENABLED=y # # TLS Key Exchange Methods # # CONFIG_MBEDTLS_PSK_MODES is not set CONFIG_MBEDTLS_KEY_EXCHANGE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA=y # end of TLS Key Exchange Methods CONFIG_MBEDTLS_SSL_RENEGOTIATION=y CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y # CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set # CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set CONFIG_MBEDTLS_SSL_ALPN=y CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS=y CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS=y # # Symmetric Ciphers # CONFIG_MBEDTLS_AES_C=y # CONFIG_MBEDTLS_CAMELLIA_C is not set # CONFIG_MBEDTLS_DES_C is not set # CONFIG_MBEDTLS_BLOWFISH_C is not set # CONFIG_MBEDTLS_XTEA_C is not set CONFIG_MBEDTLS_CCM_C=y CONFIG_MBEDTLS_GCM_C=y # CONFIG_MBEDTLS_NIST_KW_C is not set # end of Symmetric Ciphers # CONFIG_MBEDTLS_RIPEMD160_C is not set # # Certificates # CONFIG_MBEDTLS_PEM_PARSE_C=y CONFIG_MBEDTLS_PEM_WRITE_C=y CONFIG_MBEDTLS_X509_CRL_PARSE_C=y CONFIG_MBEDTLS_X509_CSR_PARSE_C=y # end of Certificates CONFIG_MBEDTLS_ECP_C=y CONFIG_MBEDTLS_PK_PARSE_EC_EXTENDED=y CONFIG_MBEDTLS_PK_PARSE_EC_COMPRESSED=y # CONFIG_MBEDTLS_DHM_C is not set CONFIG_MBEDTLS_ECDH_C=y CONFIG_MBEDTLS_ECDSA_C=y # CONFIG_MBEDTLS_ECJPAKE_C is not set CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y CONFIG_MBEDTLS_ECP_NIST_OPTIM=y # CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM is not set # CONFIG_MBEDTLS_POLY1305_C is not set # CONFIG_MBEDTLS_CHACHA20_C is not set # CONFIG_MBEDTLS_HKDF_C is not set # CONFIG_MBEDTLS_THREADING_C is not set CONFIG_MBEDTLS_ERROR_STRINGS=y CONFIG_MBEDTLS_FS_IO=y # CONFIG_MBEDTLS_ALLOW_WEAK_CERTIFICATE_VERIFICATION is not set # end of mbedTLS # # ESP-MQTT Configurations # CONFIG_MQTT_PROTOCOL_311=y # CONFIG_MQTT_PROTOCOL_5 is not set CONFIG_MQTT_TRANSPORT_SSL=y CONFIG_MQTT_TRANSPORT_WEBSOCKET=y CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y # CONFIG_MQTT_MSG_ID_INCREMENTAL is not set # CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED is not set # CONFIG_MQTT_REPORT_DELETED_MESSAGES is not set # CONFIG_MQTT_USE_CUSTOM_CONFIG is not set # CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set # CONFIG_MQTT_CUSTOM_OUTBOX is not set # end of ESP-MQTT Configurations # # Newlib # CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y # CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set # CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set # CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set # CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y # CONFIG_NEWLIB_NANO_FORMAT is not set CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y # CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set # CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set # CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set # end of Newlib CONFIG_STDATOMIC_S32C1I_SPIRAM_WORKAROUND=y # # NVS # # CONFIG_NVS_ENCRYPTION is not set # CONFIG_NVS_ASSERT_ERROR_CHECK is not set # CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY is not set # CONFIG_NVS_ALLOCATE_CACHE_IN_SPIRAM is not set # end of NVS # # OpenThread # # CONFIG_OPENTHREAD_ENABLED is not set # # OpenThread Spinel # # CONFIG_OPENTHREAD_SPINEL_ONLY is not set # end of OpenThread Spinel # end of OpenThread # # Protocomm # CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_PATCH_VERSION=y # end of Protocomm # # PThreads # CONFIG_PTHREAD_TASK_PRIO_DEFAULT=5 CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 CONFIG_PTHREAD_STACK_MIN=768 CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY=y # CONFIG_PTHREAD_DEFAULT_CORE_0 is not set # CONFIG_PTHREAD_DEFAULT_CORE_1 is not set CONFIG_PTHREAD_TASK_CORE_DEFAULT=-1 CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread" # end of PThreads # # MMU Config # CONFIG_MMU_PAGE_SIZE_64KB=y CONFIG_MMU_PAGE_MODE="64KB" CONFIG_MMU_PAGE_SIZE=0x10000 # end of MMU Config # # Main Flash configuration # # # SPI Flash behavior when brownout # CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC=y CONFIG_SPI_FLASH_BROWNOUT_RESET=y # end of SPI Flash behavior when brownout # # Optional and Experimental Features (READ DOCS FIRST) # # # Features here require specific hardware (READ DOCS FIRST!) # # CONFIG_SPI_FLASH_HPM_ENA is not set CONFIG_SPI_FLASH_HPM_AUTO=y # CONFIG_SPI_FLASH_HPM_DIS is not set CONFIG_SPI_FLASH_HPM_ON=y CONFIG_SPI_FLASH_HPM_DC_AUTO=y # CONFIG_SPI_FLASH_HPM_DC_DISABLE is not set # CONFIG_SPI_FLASH_AUTO_SUSPEND is not set CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50 # CONFIG_SPI_FLASH_FORCE_ENABLE_XMC_C_SUSPEND is not set # CONFIG_SPI_FLASH_FORCE_ENABLE_C6_H2_SUSPEND is not set # end of Optional and Experimental Features (READ DOCS FIRST) # end of Main Flash configuration # # SPI Flash driver # # CONFIG_SPI_FLASH_VERIFY_WRITE is not set # CONFIG_SPI_FLASH_ENABLE_COUNTERS is not set CONFIG_SPI_FLASH_ROM_DRIVER_PATCH=y # CONFIG_SPI_FLASH_ROM_IMPL is not set CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS=y # CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS is not set # CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED is not set # CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE is not set CONFIG_SPI_FLASH_YIELD_DURING_ERASE=y CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS=20 CONFIG_SPI_FLASH_ERASE_YIELD_TICKS=1 CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE=8192 # CONFIG_SPI_FLASH_SIZE_OVERRIDE is not set # CONFIG_SPI_FLASH_CHECK_ERASE_TIMEOUT_DISABLED is not set # CONFIG_SPI_FLASH_OVERRIDE_CHIP_DRIVER_LIST is not set # # Auto-detect flash chips # CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORTED=y CONFIG_SPI_FLASH_VENDOR_GD_SUPPORTED=y CONFIG_SPI_FLASH_VENDOR_ISSI_SUPPORTED=y CONFIG_SPI_FLASH_VENDOR_MXIC_SUPPORTED=y CONFIG_SPI_FLASH_VENDOR_WINBOND_SUPPORTED=y CONFIG_SPI_FLASH_VENDOR_BOYA_SUPPORTED=y CONFIG_SPI_FLASH_VENDOR_TH_SUPPORTED=y CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP=y CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP=y CONFIG_SPI_FLASH_SUPPORT_GD_CHIP=y CONFIG_SPI_FLASH_SUPPORT_WINBOND_CHIP=y CONFIG_SPI_FLASH_SUPPORT_BOYA_CHIP=y CONFIG_SPI_FLASH_SUPPORT_TH_CHIP=y CONFIG_SPI_FLASH_SUPPORT_MXIC_OPI_CHIP=y # end of Auto-detect flash chips CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE=y # end of SPI Flash driver # # SPIFFS Configuration # CONFIG_SPIFFS_MAX_PARTITIONS=3 # # SPIFFS Cache Configuration # CONFIG_SPIFFS_CACHE=y CONFIG_SPIFFS_CACHE_WR=y # CONFIG_SPIFFS_CACHE_STATS is not set # end of SPIFFS Cache Configuration CONFIG_SPIFFS_PAGE_CHECK=y CONFIG_SPIFFS_GC_MAX_RUNS=10 # CONFIG_SPIFFS_GC_STATS is not set CONFIG_SPIFFS_PAGE_SIZE=256 CONFIG_SPIFFS_OBJ_NAME_LEN=32 # CONFIG_SPIFFS_FOLLOW_SYMLINKS is not set CONFIG_SPIFFS_USE_MAGIC=y CONFIG_SPIFFS_USE_MAGIC_LENGTH=y CONFIG_SPIFFS_META_LENGTH=4 CONFIG_SPIFFS_USE_MTIME=y # # Debug Configuration # # CONFIG_SPIFFS_DBG is not set # CONFIG_SPIFFS_API_DBG is not set # CONFIG_SPIFFS_GC_DBG is not set # CONFIG_SPIFFS_CACHE_DBG is not set # CONFIG_SPIFFS_CHECK_DBG is not set # CONFIG_SPIFFS_TEST_VISUALISATION is not set # end of Debug Configuration # end of SPIFFS Configuration # # TCP Transport # # # Websocket # CONFIG_WS_TRANSPORT=y CONFIG_WS_BUFFER_SIZE=1024 # CONFIG_WS_DYNAMIC_BUFFER is not set # end of Websocket # end of TCP Transport # # Ultra Low Power (ULP) Co-processor # # CONFIG_ULP_COPROC_ENABLED is not set # # ULP Debugging Options # # end of ULP Debugging Options # end of Ultra Low Power (ULP) Co-processor # # Unity unit testing library # CONFIG_UNITY_ENABLE_FLOAT=y CONFIG_UNITY_ENABLE_DOUBLE=y # CONFIG_UNITY_ENABLE_64BIT is not set # CONFIG_UNITY_ENABLE_COLOR is not set CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER=y # CONFIG_UNITY_ENABLE_FIXTURE is not set # CONFIG_UNITY_ENABLE_BACKTRACE_ON_FAIL is not set # end of Unity unit testing library # # USB-OTG # CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE=256 CONFIG_USB_HOST_HW_BUFFER_BIAS_BALANCED=y # CONFIG_USB_HOST_HW_BUFFER_BIAS_IN is not set # CONFIG_USB_HOST_HW_BUFFER_BIAS_PERIODIC_OUT is not set # # Hub Driver Configuration # # # Root Port configuration # CONFIG_USB_HOST_DEBOUNCE_DELAY_MS=250 CONFIG_USB_HOST_RESET_HOLD_MS=30 CONFIG_USB_HOST_RESET_RECOVERY_MS=30 CONFIG_USB_HOST_SET_ADDR_RECOVERY_MS=10 # end of Root Port configuration # CONFIG_USB_HOST_HUBS_SUPPORTED is not set # end of Hub Driver Configuration # CONFIG_USB_HOST_ENABLE_ENUM_FILTER_CALLBACK is not set CONFIG_USB_OTG_SUPPORTED=y # end of USB-OTG # # Virtual file system # CONFIG_VFS_SUPPORT_IO=y CONFIG_VFS_SUPPORT_DIR=y CONFIG_VFS_SUPPORT_SELECT=y CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT=y # CONFIG_VFS_SELECT_IN_RAM is not set CONFIG_VFS_SUPPORT_TERMIOS=y CONFIG_VFS_MAX_COUNT=8 # # Host File System I/O (Semihosting) # CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1 # end of Host File System I/O (Semihosting) CONFIG_VFS_INITIALIZE_DEV_NULL=y # end of Virtual file system # # Wear Levelling # # CONFIG_WL_SECTOR_SIZE_512 is not set CONFIG_WL_SECTOR_SIZE_4096=y CONFIG_WL_SECTOR_SIZE=4096 # end of Wear Levelling # # Wi-Fi Provisioning Manager # CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=16 CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=30 CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y # CONFIG_WIFI_PROV_STA_FAST_SCAN is not set # end of Wi-Fi Provisioning Manager # # Board Support Package # CONFIG_BSP_ERROR_CHECK=y # # I2C # CONFIG_BSP_I2C_NUM=1 CONFIG_BSP_I2C_FAST_MODE=y CONFIG_BSP_I2C_CLK_SPEED_HZ=400000 # end of I2C # # SPIFFS - Virtual File System # # CONFIG_BSP_SPIFFS_FORMAT_ON_MOUNT_FAIL is not set CONFIG_BSP_SPIFFS_MOUNT_POINT="/spiffs" CONFIG_BSP_SPIFFS_PARTITION_LABEL="storage" CONFIG_BSP_SPIFFS_MAX_FILES=2 # end of SPIFFS - Virtual File System # # uSD card - Virtual File System # # CONFIG_BSP_SD_FORMAT_ON_MOUNT_FAIL is not set CONFIG_BSP_SD_MOUNT_POINT="/sdcard" # end of uSD card - Virtual File System # # Display # CONFIG_BSP_LCD_RGB_BOUNCE_BUFFER_HEIGHT=20 CONFIG_BSP_LCD_RGB_BUFFER_NUMS=1 CONFIG_BSP_DISPLAY_BRIGHTNESS_LEDC_CH=1 CONFIG_BSP_DISPLAY_LVGL_BUF_HEIGHT=100 # end of Display CONFIG_BSP_I2S_NUM=1 # end of Board Support Package # # CMake Utilities # # CONFIG_CU_RELINKER_ENABLE is not set # CONFIG_CU_DIAGNOSTICS_COLOR_NEVER is not set CONFIG_CU_DIAGNOSTICS_COLOR_ALWAYS=y # CONFIG_CU_DIAGNOSTICS_COLOR_AUTO is not set # CONFIG_CU_GCC_LTO_ENABLE is not set # CONFIG_CU_GCC_STRING_1BYTE_ALIGN is not set # end of CMake Utilities # # Audio Codec Device Configuration # # CONFIG_CODEC_I2C_BACKWARD_COMPATIBLE is not set CONFIG_CODEC_ES8311_SUPPORT=y CONFIG_CODEC_ES7210_SUPPORT=y CONFIG_CODEC_ES7243_SUPPORT=y CONFIG_CODEC_ES7243E_SUPPORT=y CONFIG_CODEC_ES8156_SUPPORT=y CONFIG_CODEC_AW88298_SUPPORT=y CONFIG_CODEC_ES8389_SUPPORT=y CONFIG_CODEC_ES8374_SUPPORT=y CONFIG_CODEC_ES8388_SUPPORT=y CONFIG_CODEC_TAS5805M_SUPPORT=y # CONFIG_CODEC_ZL38063_SUPPORT is not set # CONFIG_CODEC_CJC8910_SUPPORT is not set # end of Audio Codec Device Configuration # # ESP LCD TOUCH # CONFIG_ESP_LCD_TOUCH_MAX_POINTS=5 CONFIG_ESP_LCD_TOUCH_MAX_BUTTONS=1 # end of ESP LCD TOUCH # # ESP LVGL PORT # # end of ESP LVGL PORT # # Bus Options # # # I2C Bus Options # CONFIG_I2C_BUS_DYNAMIC_CONFIG=y CONFIG_I2C_MS_TO_WAIT=200 # CONFIG_I2C_BUS_BACKWARD_CONFIG is not set # CONFIG_I2C_BUS_SUPPORT_SOFTWARE is not set # CONFIG_I2C_BUS_REMOVE_NULL_MEM_ADDR is not set # end of I2C Bus Options # end of Bus Options # # LVGL configuration # CONFIG_LV_CONF_SKIP=y # CONFIG_LV_CONF_MINIMAL is not set # # Color Settings # # CONFIG_LV_COLOR_DEPTH_32 is not set # CONFIG_LV_COLOR_DEPTH_24 is not set CONFIG_LV_COLOR_DEPTH_16=y # CONFIG_LV_COLOR_DEPTH_8 is not set # CONFIG_LV_COLOR_DEPTH_1 is not set CONFIG_LV_COLOR_DEPTH=16 # end of Color Settings # # Memory Settings # CONFIG_LV_USE_BUILTIN_MALLOC=y # CONFIG_LV_USE_CLIB_MALLOC is not set # CONFIG_LV_USE_MICROPYTHON_MALLOC is not set # CONFIG_LV_USE_RTTHREAD_MALLOC is not set # CONFIG_LV_USE_CUSTOM_MALLOC is not set CONFIG_LV_USE_BUILTIN_STRING=y # CONFIG_LV_USE_CLIB_STRING is not set # CONFIG_LV_USE_CUSTOM_STRING is not set CONFIG_LV_USE_BUILTIN_SPRINTF=y # CONFIG_LV_USE_CLIB_SPRINTF is not set # CONFIG_LV_USE_CUSTOM_SPRINTF is not set CONFIG_LV_MEM_SIZE_KILOBYTES=64 CONFIG_LV_MEM_POOL_EXPAND_SIZE_KILOBYTES=0 CONFIG_LV_MEM_ADR=0x0 # end of Memory Settings # # HAL Settings # CONFIG_LV_DEF_REFR_PERIOD=33 CONFIG_LV_DPI_DEF=130 # end of HAL Settings # # Operating System (OS) # CONFIG_LV_OS_NONE=y # CONFIG_LV_OS_PTHREAD is not set # CONFIG_LV_OS_FREERTOS is not set # CONFIG_LV_OS_CMSIS_RTOS2 is not set # CONFIG_LV_OS_RTTHREAD is not set # CONFIG_LV_OS_WINDOWS is not set # CONFIG_LV_OS_MQX is not set # CONFIG_LV_OS_CUSTOM is not set # end of Operating System (OS) # # Rendering Configuration # CONFIG_LV_DRAW_BUF_STRIDE_ALIGN=1 CONFIG_LV_DRAW_BUF_ALIGN=4 CONFIG_LV_DRAW_LAYER_SIMPLE_BUF_SIZE=24576 CONFIG_LV_DRAW_LAYER_MAX_MEMORY=0 CONFIG_LV_DRAW_THREAD_STACK_SIZE=8192 CONFIG_LV_DRAW_THREAD_PRIO=3 CONFIG_LV_USE_DRAW_SW=y CONFIG_LV_DRAW_SW_SUPPORT_RGB565=y CONFIG_LV_DRAW_SW_SUPPORT_RGB565A8=y CONFIG_LV_DRAW_SW_SUPPORT_RGB888=y CONFIG_LV_DRAW_SW_SUPPORT_XRGB8888=y CONFIG_LV_DRAW_SW_SUPPORT_ARGB8888=y CONFIG_LV_DRAW_SW_SUPPORT_L8=y CONFIG_LV_DRAW_SW_SUPPORT_AL88=y CONFIG_LV_DRAW_SW_SUPPORT_A8=y CONFIG_LV_DRAW_SW_SUPPORT_I1=y CONFIG_LV_DRAW_SW_I1_LUM_THRESHOLD=127 CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT=1 # CONFIG_LV_USE_DRAW_ARM2D_SYNC is not set # CONFIG_LV_USE_NATIVE_HELIUM_ASM is not set CONFIG_LV_DRAW_SW_COMPLEX=y # CONFIG_LV_USE_DRAW_SW_COMPLEX_GRADIENTS is not set CONFIG_LV_DRAW_SW_SHADOW_CACHE_SIZE=0 CONFIG_LV_DRAW_SW_CIRCLE_CACHE_SIZE=4 CONFIG_LV_DRAW_SW_ASM_NONE=y # CONFIG_LV_DRAW_SW_ASM_NEON is not set # CONFIG_LV_DRAW_SW_ASM_HELIUM is not set # CONFIG_LV_DRAW_SW_ASM_CUSTOM is not set CONFIG_LV_USE_DRAW_SW_ASM=0 # CONFIG_LV_USE_DRAW_VGLITE is not set # CONFIG_LV_USE_PXP is not set # CONFIG_LV_USE_DRAW_G2D is not set # CONFIG_LV_USE_DRAW_DAVE2D is not set # CONFIG_LV_USE_DRAW_SDL is not set # CONFIG_LV_USE_DRAW_VG_LITE is not set # CONFIG_LV_USE_VECTOR_GRAPHIC is not set # CONFIG_LV_USE_DRAW_DMA2D is not set # end of Rendering Configuration # # Feature Configuration # # # Logging # # CONFIG_LV_USE_LOG is not set # end of Logging # # Asserts # CONFIG_LV_USE_ASSERT_NULL=y CONFIG_LV_USE_ASSERT_MALLOC=y # CONFIG_LV_USE_ASSERT_STYLE is not set # CONFIG_LV_USE_ASSERT_MEM_INTEGRITY is not set # CONFIG_LV_USE_ASSERT_OBJ is not set CONFIG_LV_ASSERT_HANDLER_INCLUDE="assert.h" # end of Asserts # # Debug # # CONFIG_LV_USE_REFR_DEBUG is not set # CONFIG_LV_USE_LAYER_DEBUG is not set # CONFIG_LV_USE_PARALLEL_DRAW_DEBUG is not set # end of Debug # # Others # # CONFIG_LV_ENABLE_GLOBAL_CUSTOM is not set CONFIG_LV_CACHE_DEF_SIZE=0 CONFIG_LV_IMAGE_HEADER_CACHE_DEF_CNT=0 CONFIG_LV_GRADIENT_MAX_STOPS=2 CONFIG_LV_COLOR_MIX_ROUND_OFS=128 # CONFIG_LV_OBJ_STYLE_CACHE is not set # CONFIG_LV_USE_OBJ_ID is not set # CONFIG_LV_USE_OBJ_NAME is not set # CONFIG_LV_USE_OBJ_PROPERTY is not set # end of Others # end of Feature Configuration # # Compiler Settings # # CONFIG_LV_BIG_ENDIAN_SYSTEM is not set CONFIG_LV_ATTRIBUTE_MEM_ALIGN_SIZE=1 # CONFIG_LV_ATTRIBUTE_FAST_MEM_USE_IRAM is not set # CONFIG_LV_USE_FLOAT is not set # CONFIG_LV_USE_MATRIX is not set # CONFIG_LV_USE_PRIVATE_API is not set # end of Compiler Settings # # Font Usage # # # Enable built-in fonts # # CONFIG_LV_FONT_MONTSERRAT_8 is not set # CONFIG_LV_FONT_MONTSERRAT_10 is not set # CONFIG_LV_FONT_MONTSERRAT_12 is not set CONFIG_LV_FONT_MONTSERRAT_14=y CONFIG_LV_FONT_MONTSERRAT_16=y # CONFIG_LV_FONT_MONTSERRAT_18 is not set CONFIG_LV_FONT_MONTSERRAT_20=y # CONFIG_LV_FONT_MONTSERRAT_22 is not set # CONFIG_LV_FONT_MONTSERRAT_24 is not set # CONFIG_LV_FONT_MONTSERRAT_26 is not set # CONFIG_LV_FONT_MONTSERRAT_28 is not set # CONFIG_LV_FONT_MONTSERRAT_30 is not set # CONFIG_LV_FONT_MONTSERRAT_32 is not set # CONFIG_LV_FONT_MONTSERRAT_34 is not set # CONFIG_LV_FONT_MONTSERRAT_36 is not set # CONFIG_LV_FONT_MONTSERRAT_38 is not set # CONFIG_LV_FONT_MONTSERRAT_40 is not set # CONFIG_LV_FONT_MONTSERRAT_42 is not set # CONFIG_LV_FONT_MONTSERRAT_44 is not set # CONFIG_LV_FONT_MONTSERRAT_46 is not set # CONFIG_LV_FONT_MONTSERRAT_48 is not set # CONFIG_LV_FONT_MONTSERRAT_28_COMPRESSED is not set # CONFIG_LV_FONT_DEJAVU_16_PERSIAN_HEBREW is not set # CONFIG_LV_FONT_SIMSUN_14_CJK is not set # CONFIG_LV_FONT_SIMSUN_16_CJK is not set # CONFIG_LV_FONT_SOURCE_HAN_SANS_SC_14_CJK is not set # CONFIG_LV_FONT_SOURCE_HAN_SANS_SC_16_CJK is not set # CONFIG_LV_FONT_UNSCII_8 is not set # CONFIG_LV_FONT_UNSCII_16 is not set # end of Enable built-in fonts # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_8 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_10 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_12 is not set CONFIG_LV_FONT_DEFAULT_MONTSERRAT_14=y # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_16 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_18 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_20 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_22 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_24 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_26 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_30 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_32 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_34 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_36 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_38 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_40 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_42 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_44 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_46 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_48 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28_COMPRESSED is not set # CONFIG_LV_FONT_DEFAULT_DEJAVU_16_PERSIAN_HEBREW is not set # CONFIG_LV_FONT_DEFAULT_SIMSUN_14_CJK is not set # CONFIG_LV_FONT_DEFAULT_SIMSUN_16_CJK is not set # CONFIG_LV_FONT_DEFAULT_SOURCE_HAN_SANS_SC_14_CJK is not set # CONFIG_LV_FONT_DEFAULT_SOURCE_HAN_SANS_SC_16_CJK is not set # CONFIG_LV_FONT_DEFAULT_UNSCII_8 is not set # CONFIG_LV_FONT_DEFAULT_UNSCII_16 is not set # CONFIG_LV_FONT_FMT_TXT_LARGE is not set # CONFIG_LV_USE_FONT_COMPRESSED is not set CONFIG_LV_USE_FONT_PLACEHOLDER=y # # Enable static fonts # # end of Enable static fonts # end of Font Usage # # Text Settings # CONFIG_LV_TXT_ENC_UTF8=y # CONFIG_LV_TXT_ENC_ASCII is not set CONFIG_LV_TXT_BREAK_CHARS=" ,.;:-_)}" CONFIG_LV_TXT_LINE_BREAK_LONG_LEN=0 CONFIG_LV_TXT_COLOR_CMD="#" # CONFIG_LV_USE_BIDI is not set # CONFIG_LV_USE_ARABIC_PERSIAN_CHARS is not set # end of Text Settings # # Widget Usage # CONFIG_LV_WIDGETS_HAS_DEFAULT_VALUE=y CONFIG_LV_USE_ANIMIMG=y CONFIG_LV_USE_ARC=y CONFIG_LV_USE_BAR=y CONFIG_LV_USE_BUTTON=y CONFIG_LV_USE_BUTTONMATRIX=y CONFIG_LV_USE_CALENDAR=y # CONFIG_LV_CALENDAR_WEEK_STARTS_MONDAY is not set # # Days name configuration # CONFIG_LV_MONDAY_STR="Mo" CONFIG_LV_TUESDAY_STR="Tu" CONFIG_LV_WEDNESDAY_STR="We" CONFIG_LV_THURSDAY_STR="Th" CONFIG_LV_FRIDAY_STR="Fr" CONFIG_LV_SATURDAY_STR="Sa" CONFIG_LV_SUNDAY_STR="Su" # end of Days name configuration CONFIG_LV_USE_CALENDAR_HEADER_ARROW=y CONFIG_LV_USE_CALENDAR_HEADER_DROPDOWN=y # CONFIG_LV_USE_CALENDAR_CHINESE is not set CONFIG_LV_USE_CANVAS=y CONFIG_LV_USE_CHART=y CONFIG_LV_USE_CHECKBOX=y CONFIG_LV_USE_DROPDOWN=y CONFIG_LV_USE_IMAGE=y CONFIG_LV_USE_IMAGEBUTTON=y CONFIG_LV_USE_KEYBOARD=y CONFIG_LV_USE_LABEL=y CONFIG_LV_LABEL_TEXT_SELECTION=y CONFIG_LV_LABEL_LONG_TXT_HINT=y CONFIG_LV_LABEL_WAIT_CHAR_COUNT=3 CONFIG_LV_USE_LED=y CONFIG_LV_USE_LINE=y CONFIG_LV_USE_LIST=y CONFIG_LV_USE_MENU=y CONFIG_LV_USE_MSGBOX=y CONFIG_LV_USE_ROLLER=y CONFIG_LV_USE_SCALE=y CONFIG_LV_USE_SLIDER=y CONFIG_LV_USE_SPAN=y CONFIG_LV_SPAN_SNIPPET_STACK_SIZE=64 CONFIG_LV_USE_SPINBOX=y CONFIG_LV_USE_SPINNER=y CONFIG_LV_USE_SWITCH=y CONFIG_LV_USE_TEXTAREA=y CONFIG_LV_TEXTAREA_DEF_PWD_SHOW_TIME=1500 CONFIG_LV_USE_TABLE=y CONFIG_LV_USE_TABVIEW=y CONFIG_LV_USE_TILEVIEW=y CONFIG_LV_USE_WIN=y # end of Widget Usage # # Themes # CONFIG_LV_USE_THEME_DEFAULT=y # CONFIG_LV_THEME_DEFAULT_DARK is not set CONFIG_LV_THEME_DEFAULT_GROW=y CONFIG_LV_THEME_DEFAULT_TRANSITION_TIME=80 CONFIG_LV_USE_THEME_SIMPLE=y # CONFIG_LV_USE_THEME_MONO is not set # end of Themes # # Layouts # CONFIG_LV_USE_FLEX=y CONFIG_LV_USE_GRID=y # end of Layouts # # 3rd Party Libraries # CONFIG_LV_FS_DEFAULT_DRIVER_LETTER=0 # CONFIG_LV_USE_FS_STDIO is not set # CONFIG_LV_USE_FS_POSIX is not set # CONFIG_LV_USE_FS_WIN32 is not set # CONFIG_LV_USE_FS_FATFS is not set # CONFIG_LV_USE_FS_MEMFS is not set # CONFIG_LV_USE_FS_LITTLEFS is not set # CONFIG_LV_USE_FS_ARDUINO_ESP_LITTLEFS is not set # CONFIG_LV_USE_FS_ARDUINO_SD is not set # CONFIG_LV_USE_FS_UEFI is not set # CONFIG_LV_USE_LODEPNG is not set # CONFIG_LV_USE_LIBPNG is not set # CONFIG_LV_USE_BMP is not set # CONFIG_LV_USE_TJPGD is not set # CONFIG_LV_USE_LIBJPEG_TURBO is not set # CONFIG_LV_USE_GIF is not set # CONFIG_LV_BIN_DECODER_RAM_LOAD is not set # CONFIG_LV_USE_RLE is not set # CONFIG_LV_USE_QRCODE is not set # CONFIG_LV_USE_BARCODE is not set # CONFIG_LV_USE_FREETYPE is not set # CONFIG_LV_USE_TINY_TTF is not set # CONFIG_LV_USE_RLOTTIE is not set # CONFIG_LV_USE_THORVG is not set # CONFIG_LV_USE_LZ4 is not set # CONFIG_LV_USE_FFMPEG is not set # end of 3rd Party Libraries # # Others # # CONFIG_LV_USE_SNAPSHOT is not set # CONFIG_LV_USE_SYSMON is not set # CONFIG_LV_USE_PROFILER is not set # CONFIG_LV_USE_MONKEY is not set # CONFIG_LV_USE_GRIDNAV is not set # CONFIG_LV_USE_FRAGMENT is not set # CONFIG_LV_USE_IMGFONT is not set CONFIG_LV_USE_OBSERVER=y # CONFIG_LV_USE_IME_PINYIN is not set # CONFIG_LV_USE_FILE_EXPLORER is not set # CONFIG_LV_USE_FONT_MANAGER is not set # CONFIG_LV_USE_TEST is not set # CONFIG_LV_USE_XML is not set # CONFIG_LV_USE_COLOR_FILTER is not set CONFIG_LVGL_VERSION_MAJOR=9 CONFIG_LVGL_VERSION_MINOR=3 CONFIG_LVGL_VERSION_PATCH=0 # end of Others # # Devices # # CONFIG_LV_USE_SDL is not set # CONFIG_LV_USE_X11 is not set # CONFIG_LV_USE_WAYLAND is not set # CONFIG_LV_USE_LINUX_FBDEV is not set # CONFIG_LV_USE_NUTTX is not set # CONFIG_LV_USE_LINUX_DRM is not set # CONFIG_LV_USE_TFT_ESPI is not set # CONFIG_LV_USE_EVDEV is not set # CONFIG_LV_USE_LIBINPUT is not set # CONFIG_LV_USE_ST7735 is not set # CONFIG_LV_USE_ST7789 is not set # CONFIG_LV_USE_ST7796 is not set # CONFIG_LV_USE_ILI9341 is not set # CONFIG_LV_USE_GENERIC_MIPI is not set # CONFIG_LV_USE_RENESAS_GLCDC is not set # CONFIG_LV_USE_ST_LTDC is not set # CONFIG_LV_USE_FT81X is not set # CONFIG_LV_USE_UEFI is not set # CONFIG_LV_USE_OPENGLES is not set # CONFIG_LV_USE_QNX is not set # end of Devices # # Examples # CONFIG_LV_BUILD_EXAMPLES=y # end of Examples # # Demos # CONFIG_LV_BUILD_DEMOS=y # CONFIG_LV_USE_DEMO_WIDGETS is not set # CONFIG_LV_USE_DEMO_KEYPAD_AND_ENCODER is not set # CONFIG_LV_USE_DEMO_BENCHMARK is not set # CONFIG_LV_USE_DEMO_RENDER is not set # CONFIG_LV_USE_DEMO_SCROLL is not set # CONFIG_LV_USE_DEMO_STRESS is not set # CONFIG_LV_USE_DEMO_MUSIC is not set # CONFIG_LV_USE_DEMO_FLEX_LAYOUT is not set # CONFIG_LV_USE_DEMO_MULTILANG is not set # CONFIG_LV_USE_DEMO_SMARTWATCH is not set # CONFIG_LV_USE_DEMO_EBIKE is not set # CONFIG_LV_USE_DEMO_HIGH_RES is not set # end of Demos # end of LVGL configuration # end of Component config # CONFIG_IDF_EXPERIMENTAL_FEATURES is not set # Deprecated options for backward compatibility # CONFIG_APP_BUILD_TYPE_ELF_RAM is not set # CONFIG_NO_BLOBS is not set # CONFIG_LOG_BOOTLOADER_LEVEL_NONE is not set # CONFIG_LOG_BOOTLOADER_LEVEL_ERROR is not set # CONFIG_LOG_BOOTLOADER_LEVEL_WARN is not set CONFIG_LOG_BOOTLOADER_LEVEL_INFO=y # CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG is not set # CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE is not set CONFIG_LOG_BOOTLOADER_LEVEL=3 # CONFIG_APP_ROLLBACK_ENABLE is not set # CONFIG_FLASH_ENCRYPTION_ENABLED is not set # CONFIG_FLASHMODE_QIO is not set # CONFIG_FLASHMODE_QOUT is not set CONFIG_FLASHMODE_DIO=y # CONFIG_FLASHMODE_DOUT is not set CONFIG_MONITOR_BAUD=115200 CONFIG_OPTIMIZATION_LEVEL_DEBUG=y CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG=y CONFIG_COMPILER_OPTIMIZATION_DEFAULT=y # CONFIG_OPTIMIZATION_LEVEL_RELEASE is not set # CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE is not set CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED=y # CONFIG_OPTIMIZATION_ASSERTIONS_SILENT is not set # CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED is not set CONFIG_OPTIMIZATION_ASSERTION_LEVEL=2 # CONFIG_CXX_EXCEPTIONS is not set CONFIG_STACK_CHECK_NONE=y # CONFIG_STACK_CHECK_NORM is not set # CONFIG_STACK_CHECK_STRONG is not set # CONFIG_STACK_CHECK_ALL is not set # CONFIG_WARN_WRITE_STRINGS is not set # CONFIG_ESP32_APPTRACE_DEST_TRAX is not set CONFIG_ESP32_APPTRACE_DEST_NONE=y CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y # CONFIG_EXTERNAL_COEX_ENABLE is not set # CONFIG_ESP_WIFI_EXTERNAL_COEXIST_ENABLE is not set # CONFIG_MCPWM_ISR_IN_IRAM is not set # CONFIG_EVENT_LOOP_PROFILING is not set CONFIG_POST_EVENTS_FROM_ISR=y CONFIG_POST_EVENTS_FROM_IRAM_ISR=y CONFIG_GDBSTUB_SUPPORT_TASKS=y CONFIG_GDBSTUB_MAX_TASKS=32 # CONFIG_OTA_ALLOW_HTTP is not set CONFIG_ESP32S3_DEEP_SLEEP_WAKEUP_DELAY=2000 CONFIG_ESP_SLEEP_DEEP_SLEEP_WAKEUP_DELAY=2000 CONFIG_ESP32S3_RTC_CLK_SRC_INT_RC=y # CONFIG_ESP32S3_RTC_CLK_SRC_EXT_CRYS is not set # CONFIG_ESP32S3_RTC_CLK_SRC_EXT_OSC is not set # CONFIG_ESP32S3_RTC_CLK_SRC_INT_8MD256 is not set CONFIG_ESP32S3_RTC_CLK_CAL_CYCLES=1024 CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE=y # CONFIG_ESP32_PHY_INIT_DATA_IN_PARTITION is not set CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER=20 CONFIG_ESP32_PHY_MAX_TX_POWER=20 # CONFIG_REDUCE_PHY_TX_POWER is not set # CONFIG_ESP32_REDUCE_PHY_TX_POWER is not set CONFIG_ESP_SYSTEM_PM_POWER_DOWN_CPU=y CONFIG_PM_POWER_DOWN_TAGMEM_IN_LIGHT_SLEEP=y CONFIG_ESP32S3_SPIRAM_SUPPORT=y CONFIG_DEFAULT_PSRAM_CLK_IO=30 CONFIG_DEFAULT_PSRAM_CS_IO=26 # CONFIG_ESP32S3_DEFAULT_CPU_FREQ_80 is not set # CONFIG_ESP32S3_DEFAULT_CPU_FREQ_160 is not set CONFIG_ESP32S3_DEFAULT_CPU_FREQ_240=y CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ=240 CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304 CONFIG_MAIN_TASK_STACK_SIZE=10240 CONFIG_CONSOLE_UART_DEFAULT=y # CONFIG_CONSOLE_UART_CUSTOM is not set # CONFIG_CONSOLE_UART_NONE is not set # CONFIG_ESP_CONSOLE_UART_NONE is not set CONFIG_CONSOLE_UART=y CONFIG_CONSOLE_UART_NUM=0 CONFIG_CONSOLE_UART_BAUDRATE=115200 CONFIG_INT_WDT=y CONFIG_INT_WDT_TIMEOUT_MS=300 CONFIG_INT_WDT_CHECK_CPU1=y CONFIG_TASK_WDT=y CONFIG_ESP_TASK_WDT=y # CONFIG_TASK_WDT_PANIC is not set CONFIG_TASK_WDT_TIMEOUT_S=5 CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0=y CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1=y # CONFIG_ESP32_DEBUG_STUBS_ENABLE is not set CONFIG_ESP32S3_DEBUG_OCDAWARE=y CONFIG_BROWNOUT_DET=y CONFIG_ESP32S3_BROWNOUT_DET=y CONFIG_BROWNOUT_DET_LVL_SEL_7=y CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_7=y # CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set # CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_6 is not set # CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set # CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_5 is not set # CONFIG_BROWNOUT_DET_LVL_SEL_4 is not set # CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_4 is not set # CONFIG_BROWNOUT_DET_LVL_SEL_3 is not set # CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_3 is not set # CONFIG_BROWNOUT_DET_LVL_SEL_2 is not set # CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_2 is not set # CONFIG_BROWNOUT_DET_LVL_SEL_1 is not set # CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_1 is not set CONFIG_BROWNOUT_DET_LVL=7 CONFIG_ESP32S3_BROWNOUT_DET_LVL=7 CONFIG_IPC_TASK_STACK_SIZE=1280 CONFIG_TIMER_TASK_STACK_SIZE=3584 CONFIG_ESP32_WIFI_ENABLED=y CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=10 CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=32 # CONFIG_ESP32_WIFI_STATIC_TX_BUFFER is not set CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER=y CONFIG_ESP32_WIFI_TX_BUFFER_TYPE=1 CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM=32 # CONFIG_ESP32_WIFI_CSI_ENABLED is not set CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED=y CONFIG_ESP32_WIFI_TX_BA_WIN=6 CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y CONFIG_ESP32_WIFI_RX_BA_WIN=6 CONFIG_ESP32_WIFI_NVS_ENABLED=y CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0=y # CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1 is not set CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN=752 CONFIG_ESP32_WIFI_MGMT_SBUF_NUM=32 CONFIG_ESP32_WIFI_IRAM_OPT=y CONFIG_ESP32_WIFI_RX_IRAM_OPT=y CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE=y CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA=y CONFIG_WPA_MBEDTLS_CRYPTO=y CONFIG_WPA_MBEDTLS_TLS_CLIENT=y # CONFIG_WPA_WAPI_PSK is not set # CONFIG_WPA_SUITE_B_192 is not set # CONFIG_WPA_11KV_SUPPORT is not set # CONFIG_WPA_MBO_SUPPORT is not set # CONFIG_WPA_DPP_SUPPORT is not set # CONFIG_WPA_11R_SUPPORT is not set # CONFIG_WPA_WPS_SOFTAP_REGISTRAR is not set # CONFIG_WPA_WPS_STRICT is not set # CONFIG_WPA_DEBUG_PRINT is not set # CONFIG_WPA_TESTING_OPTIONS is not set # CONFIG_ESP32_ENABLE_COREDUMP_TO_FLASH is not set # CONFIG_ESP32_ENABLE_COREDUMP_TO_UART is not set CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE=y CONFIG_TIMER_TASK_PRIORITY=1 CONFIG_TIMER_TASK_STACK_DEPTH=2048 CONFIG_TIMER_QUEUE_LENGTH=10 # CONFIG_ENABLE_STATIC_TASK_CLEAN_UP_HOOK is not set CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY=y # CONFIG_HAL_ASSERTION_SILIENT is not set # CONFIG_L2_TO_L3_COPY is not set CONFIG_ESP_GRATUITOUS_ARP=y CONFIG_GARP_TMR_INTERVAL=60 CONFIG_TCPIP_RECVMBOX_SIZE=32 CONFIG_TCP_MAXRTX=12 CONFIG_TCP_SYNMAXRTX=12 CONFIG_TCP_MSS=1440 CONFIG_TCP_MSL=60000 CONFIG_TCP_SND_BUF_DEFAULT=5760 CONFIG_TCP_WND_DEFAULT=5760 CONFIG_TCP_RECVMBOX_SIZE=6 CONFIG_TCP_QUEUE_OOSEQ=y CONFIG_TCP_OVERSIZE_MSS=y # CONFIG_TCP_OVERSIZE_QUARTER_MSS is not set # CONFIG_TCP_OVERSIZE_DISABLE is not set CONFIG_UDP_RECVMBOX_SIZE=6 CONFIG_TCPIP_TASK_STACK_SIZE=3072 CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_TCPIP_TASK_AFFINITY_CPU0 is not set # CONFIG_TCPIP_TASK_AFFINITY_CPU1 is not set CONFIG_TCPIP_TASK_AFFINITY=0x7FFFFFFF # CONFIG_PPP_SUPPORT is not set CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC_SYSTIMER=y CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC_FRC1=y # CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC is not set # CONFIG_ESP32S3_TIME_SYSCALL_USE_SYSTIMER is not set # CONFIG_ESP32S3_TIME_SYSCALL_USE_FRC1 is not set # CONFIG_ESP32S3_TIME_SYSCALL_USE_NONE is not set CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5 CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 CONFIG_ESP32_PTHREAD_STACK_MIN=768 CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY=y # CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0 is not set # CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1 is not set CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT=-1 CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT="pthread" CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS=y # CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS is not set # CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED is not set CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT=y CONFIG_SUPPORT_TERMIOS=y CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS=1 # End of deprecated options
84,118
sdkconfig
en
unknown
unknown
{}
0
{}
0015/map_tiles_projects
espressif_esp32_p4_function_ev_board/sdkconfig
# # Automatically generated file. DO NOT EDIT. # Espressif IoT Development Framework (ESP-IDF) 5.4.2 Project Configuration # CONFIG_SOC_ADC_SUPPORTED=y CONFIG_SOC_ANA_CMPR_SUPPORTED=y CONFIG_SOC_DEDICATED_GPIO_SUPPORTED=y CONFIG_SOC_UART_SUPPORTED=y CONFIG_SOC_GDMA_SUPPORTED=y CONFIG_SOC_AHB_GDMA_SUPPORTED=y CONFIG_SOC_AXI_GDMA_SUPPORTED=y CONFIG_SOC_DW_GDMA_SUPPORTED=y CONFIG_SOC_DMA2D_SUPPORTED=y CONFIG_SOC_GPTIMER_SUPPORTED=y CONFIG_SOC_PCNT_SUPPORTED=y CONFIG_SOC_LCDCAM_SUPPORTED=y CONFIG_SOC_LCDCAM_CAM_SUPPORTED=y CONFIG_SOC_LCDCAM_I80_LCD_SUPPORTED=y CONFIG_SOC_LCDCAM_RGB_LCD_SUPPORTED=y CONFIG_SOC_MIPI_CSI_SUPPORTED=y CONFIG_SOC_MIPI_DSI_SUPPORTED=y CONFIG_SOC_MCPWM_SUPPORTED=y CONFIG_SOC_TWAI_SUPPORTED=y CONFIG_SOC_ETM_SUPPORTED=y CONFIG_SOC_PARLIO_SUPPORTED=y CONFIG_SOC_ASYNC_MEMCPY_SUPPORTED=y CONFIG_SOC_EMAC_SUPPORTED=y CONFIG_SOC_USB_OTG_SUPPORTED=y CONFIG_SOC_WIRELESS_HOST_SUPPORTED=y CONFIG_SOC_USB_SERIAL_JTAG_SUPPORTED=y CONFIG_SOC_TEMP_SENSOR_SUPPORTED=y CONFIG_SOC_SUPPORTS_SECURE_DL_MODE=y CONFIG_SOC_ULP_SUPPORTED=y CONFIG_SOC_LP_CORE_SUPPORTED=y CONFIG_SOC_EFUSE_KEY_PURPOSE_FIELD=y CONFIG_SOC_EFUSE_SUPPORTED=y CONFIG_SOC_RTC_FAST_MEM_SUPPORTED=y CONFIG_SOC_RTC_MEM_SUPPORTED=y CONFIG_SOC_RMT_SUPPORTED=y CONFIG_SOC_I2S_SUPPORTED=y CONFIG_SOC_SDM_SUPPORTED=y CONFIG_SOC_GPSPI_SUPPORTED=y CONFIG_SOC_LEDC_SUPPORTED=y CONFIG_SOC_ISP_SUPPORTED=y CONFIG_SOC_I2C_SUPPORTED=y CONFIG_SOC_SYSTIMER_SUPPORTED=y CONFIG_SOC_AES_SUPPORTED=y CONFIG_SOC_MPI_SUPPORTED=y CONFIG_SOC_SHA_SUPPORTED=y CONFIG_SOC_HMAC_SUPPORTED=y CONFIG_SOC_DIG_SIGN_SUPPORTED=y CONFIG_SOC_ECC_SUPPORTED=y CONFIG_SOC_ECC_EXTENDED_MODES_SUPPORTED=y CONFIG_SOC_FLASH_ENC_SUPPORTED=y CONFIG_SOC_SECURE_BOOT_SUPPORTED=y CONFIG_SOC_BOD_SUPPORTED=y CONFIG_SOC_APM_SUPPORTED=y CONFIG_SOC_PMU_SUPPORTED=y CONFIG_SOC_DCDC_SUPPORTED=y CONFIG_SOC_PAU_SUPPORTED=y CONFIG_SOC_LP_TIMER_SUPPORTED=y CONFIG_SOC_ULP_LP_UART_SUPPORTED=y CONFIG_SOC_LP_GPIO_MATRIX_SUPPORTED=y CONFIG_SOC_LP_PERIPHERALS_SUPPORTED=y CONFIG_SOC_LP_I2C_SUPPORTED=y CONFIG_SOC_LP_I2S_SUPPORTED=y CONFIG_SOC_LP_SPI_SUPPORTED=y CONFIG_SOC_LP_ADC_SUPPORTED=y CONFIG_SOC_LP_VAD_SUPPORTED=y CONFIG_SOC_SPIRAM_SUPPORTED=y CONFIG_SOC_PSRAM_DMA_CAPABLE=y CONFIG_SOC_SDMMC_HOST_SUPPORTED=y CONFIG_SOC_CLK_TREE_SUPPORTED=y CONFIG_SOC_ASSIST_DEBUG_SUPPORTED=y CONFIG_SOC_DEBUG_PROBE_SUPPORTED=y CONFIG_SOC_WDT_SUPPORTED=y CONFIG_SOC_SPI_FLASH_SUPPORTED=y CONFIG_SOC_TOUCH_SENSOR_SUPPORTED=y CONFIG_SOC_RNG_SUPPORTED=y CONFIG_SOC_GP_LDO_SUPPORTED=y CONFIG_SOC_PPA_SUPPORTED=y CONFIG_SOC_LIGHT_SLEEP_SUPPORTED=y CONFIG_SOC_DEEP_SLEEP_SUPPORTED=y CONFIG_SOC_PM_SUPPORTED=y CONFIG_SOC_SIMD_INSTRUCTION_SUPPORTED=y CONFIG_SOC_XTAL_SUPPORT_40M=y CONFIG_SOC_AES_SUPPORT_DMA=y CONFIG_SOC_AES_SUPPORT_GCM=y CONFIG_SOC_AES_GDMA=y CONFIG_SOC_AES_SUPPORT_AES_128=y CONFIG_SOC_AES_SUPPORT_AES_256=y CONFIG_SOC_ADC_RTC_CTRL_SUPPORTED=y CONFIG_SOC_ADC_DIG_CTRL_SUPPORTED=y CONFIG_SOC_ADC_DMA_SUPPORTED=y CONFIG_SOC_ADC_PERIPH_NUM=2 CONFIG_SOC_ADC_MAX_CHANNEL_NUM=8 CONFIG_SOC_ADC_ATTEN_NUM=4 CONFIG_SOC_ADC_DIGI_CONTROLLER_NUM=2 CONFIG_SOC_ADC_PATT_LEN_MAX=16 CONFIG_SOC_ADC_DIGI_MAX_BITWIDTH=12 CONFIG_SOC_ADC_DIGI_MIN_BITWIDTH=12 CONFIG_SOC_ADC_DIGI_IIR_FILTER_NUM=2 CONFIG_SOC_ADC_DIGI_MONITOR_NUM=2 CONFIG_SOC_ADC_DIGI_RESULT_BYTES=4 CONFIG_SOC_ADC_DIGI_DATA_BYTES_PER_CONV=4 CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH=83333 CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW=611 CONFIG_SOC_ADC_RTC_MIN_BITWIDTH=12 CONFIG_SOC_ADC_RTC_MAX_BITWIDTH=12 CONFIG_SOC_ADC_CALIBRATION_V1_SUPPORTED=y CONFIG_SOC_ADC_SELF_HW_CALI_SUPPORTED=y CONFIG_SOC_ADC_CALIB_CHAN_COMPENS_SUPPORTED=y CONFIG_SOC_ADC_SHARED_POWER=y CONFIG_SOC_BROWNOUT_RESET_SUPPORTED=y CONFIG_SOC_SHARED_IDCACHE_SUPPORTED=y CONFIG_SOC_CACHE_WRITEBACK_SUPPORTED=y CONFIG_SOC_CACHE_FREEZE_SUPPORTED=y CONFIG_SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE=y CONFIG_SOC_CPU_CORES_NUM=2 CONFIG_SOC_CPU_INTR_NUM=32 CONFIG_SOC_CPU_HAS_FLEXIBLE_INTC=y CONFIG_SOC_INT_CLIC_SUPPORTED=y CONFIG_SOC_INT_HW_NESTED_SUPPORTED=y CONFIG_SOC_BRANCH_PREDICTOR_SUPPORTED=y CONFIG_SOC_CPU_COPROC_NUM=3 CONFIG_SOC_CPU_HAS_FPU=y CONFIG_SOC_CPU_HAS_FPU_EXT_ILL_BUG=y CONFIG_SOC_CPU_HAS_HWLOOP=y CONFIG_SOC_CPU_HAS_HWLOOP_STATE_BUG=y CONFIG_SOC_CPU_HAS_PIE=y CONFIG_SOC_HP_CPU_HAS_MULTIPLE_CORES=y CONFIG_SOC_CPU_BREAKPOINTS_NUM=3 CONFIG_SOC_CPU_WATCHPOINTS_NUM=3 CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE=0x100 CONFIG_SOC_CPU_HAS_PMA=y CONFIG_SOC_CPU_IDRAM_SPLIT_USING_PMP=y CONFIG_SOC_CPU_PMP_REGION_GRANULARITY=128 CONFIG_SOC_CPU_HAS_LOCKUP_RESET=y CONFIG_SOC_SIMD_PREFERRED_DATA_ALIGNMENT=16 CONFIG_SOC_DS_SIGNATURE_MAX_BIT_LEN=4096 CONFIG_SOC_DS_KEY_PARAM_MD_IV_LENGTH=16 CONFIG_SOC_DS_KEY_CHECK_MAX_WAIT_US=1100 CONFIG_SOC_DMA_CAN_ACCESS_FLASH=y CONFIG_SOC_AHB_GDMA_VERSION=2 CONFIG_SOC_GDMA_SUPPORT_CRC=y CONFIG_SOC_GDMA_NUM_GROUPS_MAX=2 CONFIG_SOC_GDMA_PAIRS_PER_GROUP_MAX=3 CONFIG_SOC_AXI_GDMA_SUPPORT_PSRAM=y CONFIG_SOC_GDMA_SUPPORT_ETM=y CONFIG_SOC_GDMA_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_AXI_DMA_EXT_MEM_ENC_ALIGNMENT=16 CONFIG_SOC_DMA2D_GROUPS=1 CONFIG_SOC_DMA2D_TX_CHANNELS_PER_GROUP=3 CONFIG_SOC_DMA2D_RX_CHANNELS_PER_GROUP=2 CONFIG_SOC_ETM_GROUPS=1 CONFIG_SOC_ETM_CHANNELS_PER_GROUP=50 CONFIG_SOC_ETM_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_GPIO_PORT=1 CONFIG_SOC_GPIO_PIN_COUNT=55 CONFIG_SOC_GPIO_SUPPORT_PIN_GLITCH_FILTER=y CONFIG_SOC_GPIO_FLEX_GLITCH_FILTER_NUM=8 CONFIG_SOC_GPIO_SUPPORT_PIN_HYS_FILTER=y CONFIG_SOC_GPIO_SUPPORT_ETM=y CONFIG_SOC_GPIO_SUPPORT_RTC_INDEPENDENT=y CONFIG_SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP=y CONFIG_SOC_LP_IO_HAS_INDEPENDENT_WAKEUP_SOURCE=y CONFIG_SOC_LP_IO_CLOCK_IS_INDEPENDENT=y CONFIG_SOC_GPIO_VALID_GPIO_MASK=0x007FFFFFFFFFFFFF CONFIG_SOC_GPIO_IN_RANGE_MAX=54 CONFIG_SOC_GPIO_OUT_RANGE_MAX=54 CONFIG_SOC_GPIO_DEEP_SLEEP_WAKE_VALID_GPIO_MASK=0 CONFIG_SOC_GPIO_DEEP_SLEEP_WAKE_SUPPORTED_PIN_CNT=16 CONFIG_SOC_GPIO_VALID_DIGITAL_IO_PAD_MASK=0x007FFFFFFFFF0000 CONFIG_SOC_GPIO_CLOCKOUT_BY_GPIO_MATRIX=y CONFIG_SOC_GPIO_CLOCKOUT_CHANNEL_NUM=2 CONFIG_SOC_CLOCKOUT_SUPPORT_CHANNEL_DIVIDER=y CONFIG_SOC_DEBUG_PROBE_NUM_UNIT=1 CONFIG_SOC_DEBUG_PROBE_MAX_OUTPUT_WIDTH=16 CONFIG_SOC_GPIO_SUPPORT_FORCE_HOLD=y CONFIG_SOC_RTCIO_PIN_COUNT=16 CONFIG_SOC_RTCIO_INPUT_OUTPUT_SUPPORTED=y CONFIG_SOC_RTCIO_HOLD_SUPPORTED=y CONFIG_SOC_RTCIO_WAKE_SUPPORTED=y CONFIG_SOC_RTCIO_EDGE_WAKE_SUPPORTED=y CONFIG_SOC_DEDIC_GPIO_OUT_CHANNELS_NUM=8 CONFIG_SOC_DEDIC_GPIO_IN_CHANNELS_NUM=8 CONFIG_SOC_DEDIC_PERIPH_ALWAYS_ENABLE=y CONFIG_SOC_ANA_CMPR_NUM=2 CONFIG_SOC_ANA_CMPR_CAN_DISTINGUISH_EDGE=y CONFIG_SOC_ANA_CMPR_SUPPORT_ETM=y CONFIG_SOC_I2C_NUM=3 CONFIG_SOC_HP_I2C_NUM=2 CONFIG_SOC_I2C_FIFO_LEN=32 CONFIG_SOC_I2C_CMD_REG_NUM=8 CONFIG_SOC_I2C_SUPPORT_SLAVE=y CONFIG_SOC_I2C_SUPPORT_HW_FSM_RST=y CONFIG_SOC_I2C_SUPPORT_HW_CLR_BUS=y CONFIG_SOC_I2C_SUPPORT_XTAL=y CONFIG_SOC_I2C_SUPPORT_RTC=y CONFIG_SOC_I2C_SUPPORT_10BIT_ADDR=y CONFIG_SOC_I2C_SLAVE_SUPPORT_BROADCAST=y CONFIG_SOC_I2C_SLAVE_CAN_GET_STRETCH_CAUSE=y CONFIG_SOC_I2C_SLAVE_SUPPORT_I2CRAM_ACCESS=y CONFIG_SOC_I2C_SLAVE_SUPPORT_SLAVE_UNMATCH=y CONFIG_SOC_I2C_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_LP_I2C_NUM=1 CONFIG_SOC_LP_I2C_FIFO_LEN=16 CONFIG_SOC_I2S_NUM=3 CONFIG_SOC_I2S_HW_VERSION_2=y CONFIG_SOC_I2S_SUPPORTS_ETM=y CONFIG_SOC_I2S_SUPPORTS_XTAL=y CONFIG_SOC_I2S_SUPPORTS_APLL=y CONFIG_SOC_I2S_SUPPORTS_PCM=y CONFIG_SOC_I2S_SUPPORTS_PDM=y CONFIG_SOC_I2S_SUPPORTS_PDM_TX=y CONFIG_SOC_I2S_SUPPORTS_PDM_RX=y CONFIG_SOC_I2S_SUPPORTS_PDM_RX_HP_FILTER=y CONFIG_SOC_I2S_SUPPORTS_TX_SYNC_CNT=y CONFIG_SOC_I2S_SUPPORTS_TDM=y CONFIG_SOC_I2S_PDM_MAX_TX_LINES=2 CONFIG_SOC_I2S_PDM_MAX_RX_LINES=4 CONFIG_SOC_I2S_TDM_FULL_DATA_WIDTH=y CONFIG_SOC_I2S_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_LP_I2S_NUM=1 CONFIG_SOC_ISP_BF_SUPPORTED=y CONFIG_SOC_ISP_CCM_SUPPORTED=y CONFIG_SOC_ISP_DEMOSAIC_SUPPORTED=y CONFIG_SOC_ISP_DVP_SUPPORTED=y CONFIG_SOC_ISP_SHARPEN_SUPPORTED=y CONFIG_SOC_ISP_COLOR_SUPPORTED=y CONFIG_SOC_ISP_LSC_SUPPORTED=y CONFIG_SOC_ISP_SHARE_CSI_BRG=y CONFIG_SOC_ISP_NUMS=1 CONFIG_SOC_ISP_DVP_CTLR_NUMS=1 CONFIG_SOC_ISP_AE_CTLR_NUMS=1 CONFIG_SOC_ISP_AE_BLOCK_X_NUMS=5 CONFIG_SOC_ISP_AE_BLOCK_Y_NUMS=5 CONFIG_SOC_ISP_AF_CTLR_NUMS=1 CONFIG_SOC_ISP_AF_WINDOW_NUMS=3 CONFIG_SOC_ISP_BF_TEMPLATE_X_NUMS=3 CONFIG_SOC_ISP_BF_TEMPLATE_Y_NUMS=3 CONFIG_SOC_ISP_CCM_DIMENSION=3 CONFIG_SOC_ISP_DEMOSAIC_GRAD_RATIO_INT_BITS=2 CONFIG_SOC_ISP_DEMOSAIC_GRAD_RATIO_DEC_BITS=4 CONFIG_SOC_ISP_DEMOSAIC_GRAD_RATIO_RES_BITS=26 CONFIG_SOC_ISP_DVP_DATA_WIDTH_MAX=16 CONFIG_SOC_ISP_SHARPEN_TEMPLATE_X_NUMS=3 CONFIG_SOC_ISP_SHARPEN_TEMPLATE_Y_NUMS=3 CONFIG_SOC_ISP_SHARPEN_H_FREQ_COEF_INT_BITS=3 CONFIG_SOC_ISP_SHARPEN_H_FREQ_COEF_DEC_BITS=5 CONFIG_SOC_ISP_SHARPEN_H_FREQ_COEF_RES_BITS=24 CONFIG_SOC_ISP_SHARPEN_M_FREQ_COEF_INT_BITS=3 CONFIG_SOC_ISP_SHARPEN_M_FREQ_COEF_DEC_BITS=5 CONFIG_SOC_ISP_SHARPEN_M_FREQ_COEF_RES_BITS=24 CONFIG_SOC_ISP_HIST_CTLR_NUMS=1 CONFIG_SOC_ISP_HIST_BLOCK_X_NUMS=5 CONFIG_SOC_ISP_HIST_BLOCK_Y_NUMS=5 CONFIG_SOC_ISP_HIST_SEGMENT_NUMS=16 CONFIG_SOC_ISP_HIST_INTERVAL_NUMS=15 CONFIG_SOC_ISP_LSC_GRAD_RATIO_INT_BITS=2 CONFIG_SOC_ISP_LSC_GRAD_RATIO_DEC_BITS=8 CONFIG_SOC_ISP_LSC_GRAD_RATIO_RES_BITS=22 CONFIG_SOC_LEDC_SUPPORT_PLL_DIV_CLOCK=y CONFIG_SOC_LEDC_SUPPORT_XTAL_CLOCK=y CONFIG_SOC_LEDC_TIMER_NUM=4 CONFIG_SOC_LEDC_CHANNEL_NUM=8 CONFIG_SOC_LEDC_TIMER_BIT_WIDTH=20 CONFIG_SOC_LEDC_GAMMA_CURVE_FADE_SUPPORTED=y CONFIG_SOC_LEDC_GAMMA_CURVE_FADE_RANGE_MAX=16 CONFIG_SOC_LEDC_SUPPORT_FADE_STOP=y CONFIG_SOC_LEDC_FADE_PARAMS_BIT_WIDTH=10 CONFIG_SOC_LEDC_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_MMU_PERIPH_NUM=2 CONFIG_SOC_MMU_LINEAR_ADDRESS_REGION_NUM=2 CONFIG_SOC_MMU_DI_VADDR_SHARED=y CONFIG_SOC_MMU_PER_EXT_MEM_TARGET=y CONFIG_SOC_MPU_MIN_REGION_SIZE=0x20000000 CONFIG_SOC_MPU_REGIONS_MAX_NUM=8 CONFIG_SOC_PCNT_GROUPS=1 CONFIG_SOC_PCNT_UNITS_PER_GROUP=4 CONFIG_SOC_PCNT_CHANNELS_PER_UNIT=2 CONFIG_SOC_PCNT_THRES_POINT_PER_UNIT=2 CONFIG_SOC_PCNT_SUPPORT_RUNTIME_THRES_UPDATE=y CONFIG_SOC_PCNT_SUPPORT_CLEAR_SIGNAL=y CONFIG_SOC_PCNT_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_RMT_GROUPS=1 CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP=4 CONFIG_SOC_RMT_RX_CANDIDATES_PER_GROUP=4 CONFIG_SOC_RMT_CHANNELS_PER_GROUP=8 CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL=48 CONFIG_SOC_RMT_SUPPORT_RX_PINGPONG=y CONFIG_SOC_RMT_SUPPORT_RX_DEMODULATION=y CONFIG_SOC_RMT_SUPPORT_TX_ASYNC_STOP=y CONFIG_SOC_RMT_SUPPORT_TX_LOOP_COUNT=y CONFIG_SOC_RMT_SUPPORT_TX_LOOP_AUTO_STOP=y CONFIG_SOC_RMT_SUPPORT_TX_SYNCHRO=y CONFIG_SOC_RMT_SUPPORT_TX_CARRIER_DATA_ONLY=y CONFIG_SOC_RMT_SUPPORT_XTAL=y CONFIG_SOC_RMT_SUPPORT_RC_FAST=y CONFIG_SOC_RMT_SUPPORT_DMA=y CONFIG_SOC_RMT_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_LCD_I80_SUPPORTED=y CONFIG_SOC_LCD_RGB_SUPPORTED=y CONFIG_SOC_LCDCAM_I80_NUM_BUSES=1 CONFIG_SOC_LCDCAM_I80_BUS_WIDTH=24 CONFIG_SOC_LCDCAM_RGB_NUM_PANELS=1 CONFIG_SOC_LCDCAM_RGB_DATA_WIDTH=24 CONFIG_SOC_LCD_SUPPORT_RGB_YUV_CONV=y CONFIG_SOC_MCPWM_GROUPS=2 CONFIG_SOC_MCPWM_TIMERS_PER_GROUP=3 CONFIG_SOC_MCPWM_OPERATORS_PER_GROUP=3 CONFIG_SOC_MCPWM_COMPARATORS_PER_OPERATOR=2 CONFIG_SOC_MCPWM_EVENT_COMPARATORS_PER_OPERATOR=2 CONFIG_SOC_MCPWM_GENERATORS_PER_OPERATOR=2 CONFIG_SOC_MCPWM_TRIGGERS_PER_OPERATOR=2 CONFIG_SOC_MCPWM_GPIO_FAULTS_PER_GROUP=3 CONFIG_SOC_MCPWM_CAPTURE_TIMERS_PER_GROUP=y CONFIG_SOC_MCPWM_CAPTURE_CHANNELS_PER_TIMER=3 CONFIG_SOC_MCPWM_GPIO_SYNCHROS_PER_GROUP=3 CONFIG_SOC_MCPWM_SWSYNC_CAN_PROPAGATE=y CONFIG_SOC_MCPWM_SUPPORT_ETM=y CONFIG_SOC_MCPWM_SUPPORT_EVENT_COMPARATOR=y CONFIG_SOC_MCPWM_CAPTURE_CLK_FROM_GROUP=y CONFIG_SOC_MCPWM_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_USB_OTG_PERIPH_NUM=2 CONFIG_SOC_USB_UTMI_PHY_NUM=1 CONFIG_SOC_USB_UTMI_PHY_NO_POWER_OFF_ISO=y CONFIG_SOC_PARLIO_GROUPS=1 CONFIG_SOC_PARLIO_TX_UNITS_PER_GROUP=1 CONFIG_SOC_PARLIO_RX_UNITS_PER_GROUP=1 CONFIG_SOC_PARLIO_TX_UNIT_MAX_DATA_WIDTH=16 CONFIG_SOC_PARLIO_RX_UNIT_MAX_DATA_WIDTH=16 CONFIG_SOC_PARLIO_TX_CLK_SUPPORT_GATING=y CONFIG_SOC_PARLIO_RX_CLK_SUPPORT_GATING=y CONFIG_SOC_PARLIO_RX_CLK_SUPPORT_OUTPUT=y CONFIG_SOC_PARLIO_TRANS_BIT_ALIGN=y CONFIG_SOC_PARLIO_TX_SIZE_BY_DMA=y CONFIG_SOC_PARLIO_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_MPI_MEM_BLOCKS_NUM=4 CONFIG_SOC_MPI_OPERATIONS_NUM=3 CONFIG_SOC_RSA_MAX_BIT_LEN=4096 CONFIG_SOC_SDMMC_USE_IOMUX=y CONFIG_SOC_SDMMC_USE_GPIO_MATRIX=y CONFIG_SOC_SDMMC_NUM_SLOTS=2 CONFIG_SOC_SDMMC_DELAY_PHASE_NUM=4 CONFIG_SOC_SDMMC_IO_POWER_EXTERNAL=y CONFIG_SOC_SDMMC_PSRAM_DMA_CAPABLE=y CONFIG_SOC_SDMMC_UHS_I_SUPPORTED=y CONFIG_SOC_SHA_DMA_MAX_BUFFER_SIZE=3968 CONFIG_SOC_SHA_SUPPORT_DMA=y CONFIG_SOC_SHA_SUPPORT_RESUME=y CONFIG_SOC_SHA_GDMA=y CONFIG_SOC_SHA_SUPPORT_SHA1=y CONFIG_SOC_SHA_SUPPORT_SHA224=y CONFIG_SOC_SHA_SUPPORT_SHA256=y CONFIG_SOC_SHA_SUPPORT_SHA384=y CONFIG_SOC_SHA_SUPPORT_SHA512=y CONFIG_SOC_SHA_SUPPORT_SHA512_224=y CONFIG_SOC_SHA_SUPPORT_SHA512_256=y CONFIG_SOC_SHA_SUPPORT_SHA512_T=y CONFIG_SOC_ECDSA_SUPPORT_EXPORT_PUBKEY=y CONFIG_SOC_ECDSA_SUPPORT_DETERMINISTIC_MODE=y CONFIG_SOC_ECDSA_USES_MPI=y CONFIG_SOC_SDM_GROUPS=1 CONFIG_SOC_SDM_CHANNELS_PER_GROUP=8 CONFIG_SOC_SDM_CLK_SUPPORT_PLL_F80M=y CONFIG_SOC_SDM_CLK_SUPPORT_XTAL=y CONFIG_SOC_SPI_PERIPH_NUM=3 CONFIG_SOC_SPI_MAX_CS_NUM=6 CONFIG_SOC_SPI_MAXIMUM_BUFFER_SIZE=64 CONFIG_SOC_SPI_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_SPI_SUPPORT_SLAVE_HD_VER2=y CONFIG_SOC_SPI_SLAVE_SUPPORT_SEG_TRANS=y CONFIG_SOC_SPI_SUPPORT_DDRCLK=y CONFIG_SOC_SPI_SUPPORT_CD_SIG=y CONFIG_SOC_SPI_SUPPORT_OCT=y CONFIG_SOC_SPI_SUPPORT_CLK_XTAL=y CONFIG_SOC_SPI_SUPPORT_CLK_RC_FAST=y CONFIG_SOC_SPI_SUPPORT_CLK_SPLL=y CONFIG_SOC_MSPI_HAS_INDEPENT_IOMUX=y CONFIG_SOC_MEMSPI_IS_INDEPENDENT=y CONFIG_SOC_SPI_MAX_PRE_DIVIDER=16 CONFIG_SOC_LP_SPI_PERIPH_NUM=y CONFIG_SOC_LP_SPI_MAXIMUM_BUFFER_SIZE=64 CONFIG_SOC_SPIRAM_XIP_SUPPORTED=y CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_WAIT_IDLE=y CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_SUSPEND=y CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_RESUME=y CONFIG_SOC_SPI_MEM_SUPPORT_IDLE_INTR=y CONFIG_SOC_SPI_MEM_SUPPORT_SW_SUSPEND=y CONFIG_SOC_SPI_MEM_SUPPORT_CHECK_SUS=y CONFIG_SOC_SPI_MEM_SUPPORT_TIMING_TUNING=y CONFIG_SOC_MEMSPI_TIMING_TUNING_BY_DQS=y CONFIG_SOC_SPI_MEM_SUPPORT_CACHE_32BIT_ADDR_MAP=y CONFIG_SOC_SPI_PERIPH_SUPPORT_CONTROL_DUMMY_OUT=y CONFIG_SOC_MEMSPI_SRC_FREQ_80M_SUPPORTED=y CONFIG_SOC_MEMSPI_SRC_FREQ_40M_SUPPORTED=y CONFIG_SOC_MEMSPI_SRC_FREQ_20M_SUPPORTED=y CONFIG_SOC_MEMSPI_FLASH_PSRAM_INDEPENDENT=y CONFIG_SOC_SYSTIMER_COUNTER_NUM=2 CONFIG_SOC_SYSTIMER_ALARM_NUM=3 CONFIG_SOC_SYSTIMER_BIT_WIDTH_LO=32 CONFIG_SOC_SYSTIMER_BIT_WIDTH_HI=20 CONFIG_SOC_SYSTIMER_FIXED_DIVIDER=y CONFIG_SOC_SYSTIMER_SUPPORT_RC_FAST=y CONFIG_SOC_SYSTIMER_INT_LEVEL=y CONFIG_SOC_SYSTIMER_ALARM_MISS_COMPENSATE=y CONFIG_SOC_SYSTIMER_SUPPORT_ETM=y CONFIG_SOC_LP_TIMER_BIT_WIDTH_LO=32 CONFIG_SOC_LP_TIMER_BIT_WIDTH_HI=16 CONFIG_SOC_TIMER_GROUPS=2 CONFIG_SOC_TIMER_GROUP_TIMERS_PER_GROUP=2 CONFIG_SOC_TIMER_GROUP_COUNTER_BIT_WIDTH=54 CONFIG_SOC_TIMER_GROUP_SUPPORT_XTAL=y CONFIG_SOC_TIMER_GROUP_SUPPORT_RC_FAST=y CONFIG_SOC_TIMER_GROUP_TOTAL_TIMERS=4 CONFIG_SOC_TIMER_SUPPORT_ETM=y CONFIG_SOC_TIMER_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_MWDT_SUPPORT_XTAL=y CONFIG_SOC_MWDT_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_TOUCH_SENSOR_VERSION=3 CONFIG_SOC_TOUCH_SENSOR_NUM=14 CONFIG_SOC_TOUCH_SUPPORT_SLEEP_WAKEUP=y CONFIG_SOC_TOUCH_SUPPORT_WATERPROOF=y CONFIG_SOC_TOUCH_SUPPORT_PROX_SENSING=y CONFIG_SOC_TOUCH_PROXIMITY_CHANNEL_NUM=3 CONFIG_SOC_TOUCH_PROXIMITY_MEAS_DONE_SUPPORTED=y CONFIG_SOC_TOUCH_SUPPORT_FREQ_HOP=y CONFIG_SOC_TOUCH_SAMPLE_CFG_NUM=3 CONFIG_SOC_TWAI_CONTROLLER_NUM=3 CONFIG_SOC_TWAI_CLK_SUPPORT_XTAL=y CONFIG_SOC_TWAI_BRP_MIN=2 CONFIG_SOC_TWAI_BRP_MAX=32768 CONFIG_SOC_TWAI_SUPPORTS_RX_STATUS=y CONFIG_SOC_TWAI_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_EFUSE_DIS_PAD_JTAG=y CONFIG_SOC_EFUSE_DIS_USB_JTAG=y CONFIG_SOC_EFUSE_DIS_DIRECT_BOOT=y CONFIG_SOC_EFUSE_SOFT_DIS_JTAG=y CONFIG_SOC_EFUSE_DIS_DOWNLOAD_MSPI=y CONFIG_SOC_EFUSE_ECDSA_KEY=y CONFIG_SOC_KEY_MANAGER_ECDSA_KEY_DEPLOY=y CONFIG_SOC_KEY_MANAGER_FE_KEY_DEPLOY=y CONFIG_SOC_SECURE_BOOT_V2_RSA=y CONFIG_SOC_SECURE_BOOT_V2_ECC=y CONFIG_SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS=3 CONFIG_SOC_EFUSE_REVOKE_BOOT_KEY_DIGESTS=y CONFIG_SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY=y CONFIG_SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX=64 CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES=y CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_OPTIONS=y CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_128=y CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_256=y CONFIG_SOC_UART_NUM=6 CONFIG_SOC_UART_HP_NUM=5 CONFIG_SOC_UART_LP_NUM=1 CONFIG_SOC_UART_FIFO_LEN=128 CONFIG_SOC_LP_UART_FIFO_LEN=16 CONFIG_SOC_UART_BITRATE_MAX=5000000 CONFIG_SOC_UART_SUPPORT_PLL_F80M_CLK=y CONFIG_SOC_UART_SUPPORT_RTC_CLK=y CONFIG_SOC_UART_SUPPORT_XTAL_CLK=y CONFIG_SOC_UART_SUPPORT_WAKEUP_INT=y CONFIG_SOC_UART_HAS_LP_UART=y CONFIG_SOC_UART_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_UART_SUPPORT_FSM_TX_WAIT_SEND=y CONFIG_SOC_LP_I2S_SUPPORT_VAD=y CONFIG_SOC_COEX_HW_PTI=y CONFIG_SOC_PHY_DIG_REGS_MEM_SIZE=21 CONFIG_SOC_WIFI_LIGHT_SLEEP_CLK_WIDTH=12 CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP=y CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP_MODE_PER_PIN=y CONFIG_SOC_PM_EXT1_WAKEUP_BY_PMU=y CONFIG_SOC_PM_SUPPORT_WIFI_WAKEUP=y CONFIG_SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP=y CONFIG_SOC_PM_SUPPORT_XTAL32K_PD=y CONFIG_SOC_PM_SUPPORT_RC32K_PD=y CONFIG_SOC_PM_SUPPORT_RC_FAST_PD=y CONFIG_SOC_PM_SUPPORT_VDDSDIO_PD=y CONFIG_SOC_PM_SUPPORT_TOP_PD=y CONFIG_SOC_PM_SUPPORT_CNNT_PD=y CONFIG_SOC_PM_SUPPORT_RTC_PERIPH_PD=y CONFIG_SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY=y CONFIG_SOC_PM_CPU_RETENTION_BY_SW=y CONFIG_SOC_PM_CACHE_RETENTION_BY_PAU=y CONFIG_SOC_PM_PAU_LINK_NUM=4 CONFIG_SOC_PM_PAU_REGDMA_LINK_MULTI_ADDR=y CONFIG_SOC_PAU_IN_TOP_DOMAIN=y CONFIG_SOC_CPU_IN_TOP_DOMAIN=y CONFIG_SOC_PM_PAU_REGDMA_UPDATE_CACHE_BEFORE_WAIT_COMPARE=y CONFIG_SOC_SLEEP_SYSTIMER_STALL_WORKAROUND=y CONFIG_SOC_SLEEP_TGWDT_STOP_WORKAROUND=y CONFIG_SOC_PM_RETENTION_MODULE_NUM=64 CONFIG_SOC_PSRAM_VDD_POWER_MPLL=y CONFIG_SOC_CLK_RC_FAST_SUPPORT_CALIBRATION=y CONFIG_SOC_CLK_APLL_SUPPORTED=y CONFIG_SOC_CLK_MPLL_SUPPORTED=y CONFIG_SOC_CLK_SDIO_PLL_SUPPORTED=y CONFIG_SOC_CLK_XTAL32K_SUPPORTED=y CONFIG_SOC_CLK_RC32K_SUPPORTED=y CONFIG_SOC_CLK_LP_FAST_SUPPORT_LP_PLL=y CONFIG_SOC_CLK_LP_FAST_SUPPORT_XTAL=y CONFIG_SOC_PERIPH_CLK_CTRL_SHARED=y CONFIG_SOC_TEMPERATURE_SENSOR_LP_PLL_SUPPORT=y CONFIG_SOC_TEMPERATURE_SENSOR_INTR_SUPPORT=y CONFIG_SOC_TSENS_IS_INDEPENDENT_FROM_ADC=y CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_ETM=y CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_MEM_TCM_SUPPORTED=y CONFIG_SOC_MEM_NON_CONTIGUOUS_SRAM=y CONFIG_SOC_ASYNCHRONOUS_BUS_ERROR_MODE=y CONFIG_SOC_EMAC_IEEE_1588_SUPPORT=y CONFIG_SOC_EMAC_USE_MULTI_IO_MUX=y CONFIG_SOC_EMAC_MII_USE_GPIO_MATRIX=y CONFIG_SOC_JPEG_CODEC_SUPPORTED=y CONFIG_SOC_JPEG_DECODE_SUPPORTED=y CONFIG_SOC_JPEG_ENCODE_SUPPORTED=y CONFIG_SOC_LCDCAM_CAM_SUPPORT_RGB_YUV_CONV=y CONFIG_SOC_LCDCAM_CAM_PERIPH_NUM=1 CONFIG_SOC_LCDCAM_CAM_DATA_WIDTH_MAX=16 CONFIG_SOC_LP_CORE_SUPPORT_ETM=y CONFIG_SOC_LP_CORE_SUPPORT_LP_ADC=y CONFIG_SOC_LP_CORE_SUPPORT_LP_VAD=y CONFIG_IDF_CMAKE=y CONFIG_IDF_TOOLCHAIN="gcc" CONFIG_IDF_TOOLCHAIN_GCC=y CONFIG_IDF_TARGET_ARCH_RISCV=y CONFIG_IDF_TARGET_ARCH="riscv" CONFIG_IDF_TARGET="esp32p4" CONFIG_IDF_INIT_VERSION="5.4.2" CONFIG_IDF_TARGET_ESP32P4=y CONFIG_IDF_FIRMWARE_CHIP_ID=0x0012 # # Build type # CONFIG_APP_BUILD_TYPE_APP_2NDBOOT=y # CONFIG_APP_BUILD_TYPE_RAM is not set CONFIG_APP_BUILD_GENERATE_BINARIES=y CONFIG_APP_BUILD_BOOTLOADER=y CONFIG_APP_BUILD_USE_FLASH_SECTIONS=y # CONFIG_APP_REPRODUCIBLE_BUILD is not set # CONFIG_APP_NO_BLOBS is not set # end of Build type # # Bootloader config # # # Bootloader manager # CONFIG_BOOTLOADER_COMPILE_TIME_DATE=y CONFIG_BOOTLOADER_PROJECT_VER=1 # end of Bootloader manager CONFIG_BOOTLOADER_OFFSET_IN_FLASH=0x2000 CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG is not set # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF is not set # # Log # # CONFIG_BOOTLOADER_LOG_LEVEL_NONE is not set # CONFIG_BOOTLOADER_LOG_LEVEL_ERROR is not set # CONFIG_BOOTLOADER_LOG_LEVEL_WARN is not set CONFIG_BOOTLOADER_LOG_LEVEL_INFO=y # CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG is not set # CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE is not set CONFIG_BOOTLOADER_LOG_LEVEL=3 # # Format # # CONFIG_BOOTLOADER_LOG_COLORS is not set CONFIG_BOOTLOADER_LOG_TIMESTAMP_SOURCE_CPU_TICKS=y # end of Format # end of Log # # Serial Flash Configurations # # CONFIG_BOOTLOADER_FLASH_DC_AWARE is not set CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT=y # end of Serial Flash Configurations # CONFIG_BOOTLOADER_FACTORY_RESET is not set # CONFIG_BOOTLOADER_APP_TEST is not set CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE=y CONFIG_BOOTLOADER_WDT_ENABLE=y # CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE is not set CONFIG_BOOTLOADER_WDT_TIME_MS=9000 # CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS is not set CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0 # CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC is not set # end of Bootloader config # # Security features # CONFIG_SECURE_BOOT_V2_RSA_SUPPORTED=y CONFIG_SECURE_BOOT_V2_ECC_SUPPORTED=y CONFIG_SECURE_BOOT_V2_PREFERRED=y # CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT is not set # CONFIG_SECURE_BOOT is not set # CONFIG_SECURE_FLASH_ENC_ENABLED is not set CONFIG_SECURE_ROM_DL_MODE_ENABLED=y # end of Security features # # Application manager # CONFIG_APP_COMPILE_TIME_DATE=y # CONFIG_APP_EXCLUDE_PROJECT_VER_VAR is not set # CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR is not set # CONFIG_APP_PROJECT_VER_FROM_CONFIG is not set CONFIG_APP_RETRIEVE_LEN_ELF_SHA=9 # end of Application manager CONFIG_ESP_ROM_HAS_CRC_LE=y CONFIG_ESP_ROM_HAS_CRC_BE=y CONFIG_ESP_ROM_UART_CLK_IS_XTAL=y CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM=6 CONFIG_ESP_ROM_USB_OTG_NUM=5 CONFIG_ESP_ROM_HAS_RETARGETABLE_LOCKING=y CONFIG_ESP_ROM_GET_CLK_FREQ=y CONFIG_ESP_ROM_HAS_RVFPLIB=y CONFIG_ESP_ROM_HAS_HAL_WDT=y CONFIG_ESP_ROM_HAS_HAL_SYSTIMER=y CONFIG_ESP_ROM_HAS_LAYOUT_TABLE=y CONFIG_ESP_ROM_WDT_INIT_PATCH=y CONFIG_ESP_ROM_HAS_LP_ROM=y CONFIG_ESP_ROM_WITHOUT_REGI2C=y CONFIG_ESP_ROM_HAS_NEWLIB=y CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT=y CONFIG_ESP_ROM_HAS_NEWLIB_NANO_PRINTF_FLOAT_BUG=y CONFIG_ESP_ROM_HAS_VERSION=y CONFIG_ESP_ROM_CLIC_INT_TYPE_PATCH=y CONFIG_ESP_ROM_HAS_OUTPUT_PUTC_FUNC=y # # Boot ROM Behavior # CONFIG_BOOT_ROM_LOG_ALWAYS_ON=y # CONFIG_BOOT_ROM_LOG_ALWAYS_OFF is not set # CONFIG_BOOT_ROM_LOG_ON_GPIO_HIGH is not set # CONFIG_BOOT_ROM_LOG_ON_GPIO_LOW is not set # end of Boot ROM Behavior # # Serial flasher config # # CONFIG_ESPTOOLPY_NO_STUB is not set CONFIG_ESPTOOLPY_FLASHMODE_QIO=y # CONFIG_ESPTOOLPY_FLASHMODE_QOUT is not set # CONFIG_ESPTOOLPY_FLASHMODE_DIO is not set # CONFIG_ESPTOOLPY_FLASHMODE_DOUT is not set CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR=y CONFIG_ESPTOOLPY_FLASHMODE="dio" CONFIG_ESPTOOLPY_FLASHFREQ_80M=y # CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set # CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set CONFIG_ESPTOOLPY_FLASHFREQ_VAL=80 CONFIG_ESPTOOLPY_FLASHFREQ="80m" # CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y # CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set CONFIG_ESPTOOLPY_FLASHSIZE="16MB" # CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set CONFIG_ESPTOOLPY_BEFORE_RESET=y # CONFIG_ESPTOOLPY_BEFORE_NORESET is not set CONFIG_ESPTOOLPY_BEFORE="default_reset" CONFIG_ESPTOOLPY_AFTER_RESET=y # CONFIG_ESPTOOLPY_AFTER_NORESET is not set CONFIG_ESPTOOLPY_AFTER="hard_reset" CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 # end of Serial flasher config # # Partition Table # # CONFIG_PARTITION_TABLE_SINGLE_APP is not set # CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set # CONFIG_PARTITION_TABLE_TWO_OTA is not set # CONFIG_PARTITION_TABLE_TWO_OTA_LARGE is not set CONFIG_PARTITION_TABLE_CUSTOM=y CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" CONFIG_PARTITION_TABLE_OFFSET=0x8000 CONFIG_PARTITION_TABLE_MD5=y # end of Partition Table # # Compiler options # # CONFIG_COMPILER_OPTIMIZATION_DEBUG is not set # CONFIG_COMPILER_OPTIMIZATION_SIZE is not set CONFIG_COMPILER_OPTIMIZATION_PERF=y # CONFIG_COMPILER_OPTIMIZATION_NONE is not set CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE=y # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT is not set # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set CONFIG_COMPILER_ASSERT_NDEBUG_EVALUATE=y # CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB is not set CONFIG_COMPILER_FLOAT_LIB_FROM_RVFPLIB=y CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL=2 # CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT is not set CONFIG_COMPILER_HIDE_PATHS_MACROS=y # CONFIG_COMPILER_CXX_EXCEPTIONS is not set # CONFIG_COMPILER_CXX_RTTI is not set CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y # CONFIG_COMPILER_STACK_CHECK_MODE_NORM is not set # CONFIG_COMPILER_STACK_CHECK_MODE_STRONG is not set # CONFIG_COMPILER_STACK_CHECK_MODE_ALL is not set # CONFIG_COMPILER_NO_MERGE_CONSTANTS is not set # CONFIG_COMPILER_WARN_WRITE_STRINGS is not set # CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS is not set CONFIG_COMPILER_DISABLE_DEFAULT_ERRORS=y # CONFIG_COMPILER_DISABLE_GCC12_WARNINGS is not set # CONFIG_COMPILER_DISABLE_GCC13_WARNINGS is not set # CONFIG_COMPILER_DISABLE_GCC14_WARNINGS is not set # CONFIG_COMPILER_DUMP_RTL_FILES is not set CONFIG_COMPILER_RT_LIB_GCCLIB=y CONFIG_COMPILER_RT_LIB_NAME="gcc" CONFIG_COMPILER_ORPHAN_SECTIONS_WARNING=y # CONFIG_COMPILER_ORPHAN_SECTIONS_PLACE is not set # CONFIG_COMPILER_STATIC_ANALYZER is not set # end of Compiler options # # Component config # # # Application Level Tracing # # CONFIG_APPTRACE_DEST_JTAG is not set CONFIG_APPTRACE_DEST_NONE=y # CONFIG_APPTRACE_DEST_UART1 is not set # CONFIG_APPTRACE_DEST_UART2 is not set CONFIG_APPTRACE_DEST_UART_NONE=y CONFIG_APPTRACE_UART_TASK_PRIO=1 CONFIG_APPTRACE_LOCK_ENABLE=y # end of Application Level Tracing # # Bluetooth # # CONFIG_BT_ENABLED is not set # # Common Options # # CONFIG_BT_BLE_LOG_SPI_OUT_ENABLED is not set # end of Common Options # end of Bluetooth # # Console Library # # CONFIG_CONSOLE_SORTED_HELP is not set # end of Console Library # # Driver Configurations # # # TWAI Configuration # # CONFIG_TWAI_ISR_IN_IRAM is not set # end of TWAI Configuration # # Legacy ADC Driver Configuration # # CONFIG_ADC_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_ADC_SKIP_LEGACY_CONFLICT_CHECK is not set # # Legacy ADC Calibration Configuration # # CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN is not set # end of Legacy ADC Calibration Configuration # end of Legacy ADC Driver Configuration # # Legacy MCPWM Driver Configurations # # CONFIG_MCPWM_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_MCPWM_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy MCPWM Driver Configurations # # Legacy Timer Group Driver Configurations # # CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_GPTIMER_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy Timer Group Driver Configurations # # Legacy RMT Driver Configurations # # CONFIG_RMT_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_RMT_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy RMT Driver Configurations # # Legacy I2S Driver Configurations # # CONFIG_I2S_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_I2S_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy I2S Driver Configurations # # Legacy I2C Driver Configurations # # CONFIG_I2C_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy I2C Driver Configurations # # Legacy PCNT Driver Configurations # # CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_PCNT_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy PCNT Driver Configurations # # Legacy SDM Driver Configurations # # CONFIG_SDM_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_SDM_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy SDM Driver Configurations # # Legacy Temperature Sensor Driver Configurations # # CONFIG_TEMP_SENSOR_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_TEMP_SENSOR_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy Temperature Sensor Driver Configurations # end of Driver Configurations # # eFuse Bit Manager # # CONFIG_EFUSE_CUSTOM_TABLE is not set # CONFIG_EFUSE_VIRTUAL is not set CONFIG_EFUSE_MAX_BLK_LEN=256 # end of eFuse Bit Manager # # ESP-TLS # CONFIG_ESP_TLS_USING_MBEDTLS=y CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y # CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is not set # CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is not set # CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK is not set # CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL is not set # CONFIG_ESP_TLS_PSK_VERIFICATION is not set # CONFIG_ESP_TLS_INSECURE is not set # end of ESP-TLS # # ADC and ADC Calibration # # CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM is not set # CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is not set # CONFIG_ADC_ENABLE_DEBUG_LOG is not set # end of ADC and ADC Calibration # # Wireless Coexistence # # CONFIG_ESP_COEX_GPIO_DEBUG is not set # end of Wireless Coexistence # # Common ESP-related # CONFIG_ESP_ERR_TO_NAME_LOOKUP=y # end of Common ESP-related # # ESP-Driver:Analog Comparator Configurations # # CONFIG_ANA_CMPR_ISR_IRAM_SAFE is not set # CONFIG_ANA_CMPR_CTRL_FUNC_IN_IRAM is not set # CONFIG_ANA_CMPR_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:Analog Comparator Configurations # # ESP-Driver:Camera Controller Configurations # # CONFIG_CAM_CTLR_MIPI_CSI_ISR_CACHE_SAFE is not set # CONFIG_CAM_CTLR_ISP_DVP_ISR_CACHE_SAFE is not set # CONFIG_CAM_CTLR_DVP_CAM_ISR_CACHE_SAFE is not set # end of ESP-Driver:Camera Controller Configurations # # ESP-Driver:GPIO Configurations # # CONFIG_GPIO_CTRL_FUNC_IN_IRAM is not set # end of ESP-Driver:GPIO Configurations # # ESP-Driver:GPTimer Configurations # CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set # CONFIG_GPTIMER_ISR_IRAM_SAFE is not set CONFIG_GPTIMER_OBJ_CACHE_SAFE=y # CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:GPTimer Configurations # # ESP-Driver:I2C Configurations # # CONFIG_I2C_ISR_IRAM_SAFE is not set # CONFIG_I2C_ENABLE_DEBUG_LOG is not set # CONFIG_I2C_ENABLE_SLAVE_DRIVER_VERSION_2 is not set # end of ESP-Driver:I2C Configurations # # ESP-Driver:I2S Configurations # # CONFIG_I2S_ISR_IRAM_SAFE is not set # CONFIG_I2S_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:I2S Configurations # # ESP-Driver:ISP Configurations # # CONFIG_ISP_ISR_IRAM_SAFE is not set # CONFIG_ISP_CTRL_FUNC_IN_IRAM is not set # end of ESP-Driver:ISP Configurations # # ESP-Driver:JPEG-Codec Configurations # # CONFIG_JPEG_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:JPEG-Codec Configurations # # ESP-Driver:LEDC Configurations # # CONFIG_LEDC_CTRL_FUNC_IN_IRAM is not set # end of ESP-Driver:LEDC Configurations # # ESP-Driver:MCPWM Configurations # # CONFIG_MCPWM_ISR_IRAM_SAFE is not set # CONFIG_MCPWM_CTRL_FUNC_IN_IRAM is not set # CONFIG_MCPWM_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:MCPWM Configurations # # ESP-Driver:Parallel IO Configurations # # CONFIG_PARLIO_ENABLE_DEBUG_LOG is not set # CONFIG_PARLIO_ISR_IRAM_SAFE is not set # end of ESP-Driver:Parallel IO Configurations # # ESP-Driver:PCNT Configurations # # CONFIG_PCNT_CTRL_FUNC_IN_IRAM is not set # CONFIG_PCNT_ISR_IRAM_SAFE is not set # CONFIG_PCNT_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:PCNT Configurations # # ESP-Driver:RMT Configurations # # CONFIG_RMT_ISR_IRAM_SAFE is not set # CONFIG_RMT_RECV_FUNC_IN_IRAM is not set # CONFIG_RMT_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:RMT Configurations # # ESP-Driver:Sigma Delta Modulator Configurations # # CONFIG_SDM_CTRL_FUNC_IN_IRAM is not set # CONFIG_SDM_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:Sigma Delta Modulator Configurations # # ESP-Driver:SPI Configurations # # CONFIG_SPI_MASTER_IN_IRAM is not set CONFIG_SPI_MASTER_ISR_IN_IRAM=y # CONFIG_SPI_SLAVE_IN_IRAM is not set CONFIG_SPI_SLAVE_ISR_IN_IRAM=y # end of ESP-Driver:SPI Configurations # # ESP-Driver:Touch Sensor Configurations # # CONFIG_TOUCH_CTRL_FUNC_IN_IRAM is not set # CONFIG_TOUCH_ISR_IRAM_SAFE is not set # CONFIG_TOUCH_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:Touch Sensor Configurations # # ESP-Driver:Temperature Sensor Configurations # # CONFIG_TEMP_SENSOR_ENABLE_DEBUG_LOG is not set # CONFIG_TEMP_SENSOR_ISR_IRAM_SAFE is not set # end of ESP-Driver:Temperature Sensor Configurations # # ESP-Driver:UART Configurations # # CONFIG_UART_ISR_IN_IRAM is not set # end of ESP-Driver:UART Configurations # # ESP-Driver:USB Serial/JTAG Configuration # CONFIG_USJ_ENABLE_USB_SERIAL_JTAG=y # end of ESP-Driver:USB Serial/JTAG Configuration # # Ethernet # CONFIG_ETH_ENABLED=y CONFIG_ETH_USE_ESP32_EMAC=y CONFIG_ETH_PHY_INTERFACE_RMII=y CONFIG_ETH_DMA_BUFFER_SIZE=512 CONFIG_ETH_DMA_RX_BUFFER_NUM=20 CONFIG_ETH_DMA_TX_BUFFER_NUM=10 # CONFIG_ETH_SOFT_FLOW_CONTROL is not set # CONFIG_ETH_IRAM_OPTIMIZATION is not set CONFIG_ETH_USE_SPI_ETHERNET=y # CONFIG_ETH_SPI_ETHERNET_DM9051 is not set # CONFIG_ETH_SPI_ETHERNET_W5500 is not set # CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL is not set # CONFIG_ETH_USE_OPENETH is not set # CONFIG_ETH_TRANSMIT_MUTEX is not set # end of Ethernet # # Event Loop Library # # CONFIG_ESP_EVENT_LOOP_PROFILING is not set CONFIG_ESP_EVENT_POST_FROM_ISR=y CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR=y # end of Event Loop Library # # GDB Stub # CONFIG_ESP_GDBSTUB_ENABLED=y # CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME is not set CONFIG_ESP_GDBSTUB_SUPPORT_TASKS=y CONFIG_ESP_GDBSTUB_MAX_TASKS=32 # end of GDB Stub # # ESP HID # CONFIG_ESPHID_TASK_SIZE_BT=2048 CONFIG_ESPHID_TASK_SIZE_BLE=4096 # end of ESP HID # # ESP HTTP client # CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y # CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH is not set # CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH is not set # CONFIG_ESP_HTTP_CLIENT_ENABLE_CUSTOM_TRANSPORT is not set CONFIG_ESP_HTTP_CLIENT_EVENT_POST_TIMEOUT=2000 # end of ESP HTTP client # # HTTP Server # CONFIG_HTTPD_MAX_REQ_HDR_LEN=512 CONFIG_HTTPD_MAX_URI_LEN=512 CONFIG_HTTPD_ERR_RESP_NO_DELAY=y CONFIG_HTTPD_PURGE_BUF_LEN=32 # CONFIG_HTTPD_LOG_PURGE_DATA is not set # CONFIG_HTTPD_WS_SUPPORT is not set # CONFIG_HTTPD_QUEUE_WORK_BLOCKING is not set CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT=2000 # end of HTTP Server # # ESP HTTPS OTA # # CONFIG_ESP_HTTPS_OTA_DECRYPT_CB is not set # CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP is not set CONFIG_ESP_HTTPS_OTA_EVENT_POST_TIMEOUT=2000 # end of ESP HTTPS OTA # # ESP HTTPS server # # CONFIG_ESP_HTTPS_SERVER_ENABLE is not set CONFIG_ESP_HTTPS_SERVER_EVENT_POST_TIMEOUT=2000 # end of ESP HTTPS server # # Hardware Settings # # # Chip revision # # CONFIG_ESP32P4_REV_MIN_0 is not set CONFIG_ESP32P4_REV_MIN_1=y # CONFIG_ESP32P4_REV_MIN_100 is not set CONFIG_ESP32P4_REV_MIN_FULL=1 CONFIG_ESP_REV_MIN_FULL=1 # # Maximum Supported ESP32-P4 Revision (Rev v1.99) # CONFIG_ESP32P4_REV_MAX_FULL=199 CONFIG_ESP_REV_MAX_FULL=199 CONFIG_ESP_EFUSE_BLOCK_REV_MIN_FULL=0 CONFIG_ESP_EFUSE_BLOCK_REV_MAX_FULL=99 # # Maximum Supported ESP32-P4 eFuse Block Revision (eFuse Block Rev v0.99) # # end of Chip revision # # MAC Config # CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH=y CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES_ONE=y CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES=1 CONFIG_ESP32P4_UNIVERSAL_MAC_ADDRESSES_ONE=y CONFIG_ESP32P4_UNIVERSAL_MAC_ADDRESSES=1 # CONFIG_ESP_MAC_USE_CUSTOM_MAC_AS_BASE_MAC is not set # end of MAC Config # # Sleep Config # CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND=y CONFIG_ESP_SLEEP_PSRAM_LEAKAGE_WORKAROUND=y # CONFIG_ESP_SLEEP_MSPI_NEED_ALL_IO_PU is not set # CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND is not set CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY=0 # CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION is not set # CONFIG_ESP_SLEEP_DEBUG is not set CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS=y # end of Sleep Config # # RTC Clock Config # CONFIG_RTC_CLK_SRC_INT_RC=y # CONFIG_RTC_CLK_SRC_EXT_CRYS is not set CONFIG_RTC_CLK_CAL_CYCLES=1024 CONFIG_RTC_FAST_CLK_SRC_RC_FAST=y # CONFIG_RTC_FAST_CLK_SRC_XTAL is not set # end of RTC Clock Config # # Peripheral Control # # CONFIG_PERIPH_CTRL_FUNC_IN_IRAM is not set # end of Peripheral Control # # ETM Configuration # # CONFIG_ETM_ENABLE_DEBUG_LOG is not set # end of ETM Configuration # # GDMA Configurations # CONFIG_GDMA_CTRL_FUNC_IN_IRAM=y CONFIG_GDMA_ISR_HANDLER_IN_IRAM=y CONFIG_GDMA_OBJ_DRAM_SAFE=y # CONFIG_GDMA_ENABLE_DEBUG_LOG is not set # CONFIG_GDMA_ISR_IRAM_SAFE is not set # end of GDMA Configurations # # DW_GDMA Configurations # # CONFIG_DW_GDMA_ENABLE_DEBUG_LOG is not set # end of DW_GDMA Configurations # # 2D-DMA Configurations # # CONFIG_DMA2D_OPERATION_FUNC_IN_IRAM is not set # CONFIG_DMA2D_ISR_IRAM_SAFE is not set # end of 2D-DMA Configurations # # Main XTAL Config # CONFIG_XTAL_FREQ_40=y CONFIG_XTAL_FREQ=40 # end of Main XTAL Config # # DCDC Regulator Configurations # CONFIG_ESP_SLEEP_KEEP_DCDC_ALWAYS_ON=y CONFIG_ESP_SLEEP_DCM_VSET_VAL_IN_SLEEP=14 # end of DCDC Regulator Configurations # # LDO Regulator Configurations # CONFIG_ESP_LDO_RESERVE_SPI_NOR_FLASH=y CONFIG_ESP_LDO_CHAN_SPI_NOR_FLASH_DOMAIN=1 CONFIG_ESP_LDO_VOLTAGE_SPI_NOR_FLASH_3300_MV=y CONFIG_ESP_LDO_VOLTAGE_SPI_NOR_FLASH_DOMAIN=3300 CONFIG_ESP_LDO_RESERVE_PSRAM=y CONFIG_ESP_LDO_CHAN_PSRAM_DOMAIN=2 CONFIG_ESP_LDO_VOLTAGE_PSRAM_1900_MV=y CONFIG_ESP_LDO_VOLTAGE_PSRAM_DOMAIN=1900 # end of LDO Regulator Configurations CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y # end of Hardware Settings # # ESP-Driver:LCD Controller Configurations # # CONFIG_LCD_ENABLE_DEBUG_LOG is not set # CONFIG_LCD_RGB_ISR_IRAM_SAFE is not set # CONFIG_LCD_RGB_RESTART_IN_VSYNC is not set # CONFIG_LCD_DSI_ISR_IRAM_SAFE is not set # end of ESP-Driver:LCD Controller Configurations # # ESP-MM: Memory Management Configurations # # CONFIG_ESP_MM_CACHE_MSYNC_C2M_CHUNKED_OPS is not set # end of ESP-MM: Memory Management Configurations # # ESP NETIF Adapter # CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL=120 # CONFIG_ESP_NETIF_PROVIDE_CUSTOM_IMPLEMENTATION is not set CONFIG_ESP_NETIF_TCPIP_LWIP=y # CONFIG_ESP_NETIF_LOOPBACK is not set CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y CONFIG_ESP_NETIF_REPORT_DATA_TRAFFIC=y # CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS is not set # CONFIG_ESP_NETIF_L2_TAP is not set # CONFIG_ESP_NETIF_BRIDGE_EN is not set # CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF is not set # end of ESP NETIF Adapter # # Partition API Configuration # # end of Partition API Configuration # # PHY # # end of PHY # # Power Management # # CONFIG_PM_ENABLE is not set # CONFIG_PM_SLP_IRAM_OPT is not set # CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP is not set # end of Power Management # # ESP PSRAM # CONFIG_SPIRAM=y # # PSRAM config # CONFIG_SPIRAM_MODE_HEX=y CONFIG_SPIRAM_SPEED_200M=y # CONFIG_SPIRAM_SPEED_20M is not set CONFIG_SPIRAM_SPEED=200 CONFIG_SPIRAM_FETCH_INSTRUCTIONS=y CONFIG_SPIRAM_RODATA=y CONFIG_SPIRAM_XIP_FROM_PSRAM=y CONFIG_SPIRAM_FLASH_LOAD_TO_PSRAM=y # CONFIG_SPIRAM_ECC_ENABLE is not set CONFIG_SPIRAM_BOOT_INIT=y CONFIG_SPIRAM_PRE_CONFIGURE_MEMORY_PROTECTION=y # CONFIG_SPIRAM_IGNORE_NOTFOUND is not set # CONFIG_SPIRAM_USE_MEMMAP is not set # CONFIG_SPIRAM_USE_CAPS_ALLOC is not set CONFIG_SPIRAM_USE_MALLOC=y CONFIG_SPIRAM_MEMTEST=y CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=16384 # CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP is not set CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL=32768 # CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY is not set # CONFIG_SPIRAM_ALLOW_NOINIT_SEG_EXTERNAL_MEMORY is not set # end of PSRAM config # end of ESP PSRAM # # ESP Ringbuf # # CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH is not set # end of ESP Ringbuf # # ESP Security Specific # # end of ESP Security Specific # # ESP System Settings # CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_360=y CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=360 # # Cache config # # CONFIG_CACHE_L2_CACHE_128KB is not set CONFIG_CACHE_L2_CACHE_256KB=y # CONFIG_CACHE_L2_CACHE_512KB is not set CONFIG_CACHE_L2_CACHE_SIZE=0x40000 # CONFIG_CACHE_L2_CACHE_LINE_64B is not set CONFIG_CACHE_L2_CACHE_LINE_128B=y CONFIG_CACHE_L2_CACHE_LINE_SIZE=128 CONFIG_CACHE_L1_CACHE_LINE_SIZE=64 # end of Cache config # CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT is not set CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y # CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set # CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=0 CONFIG_ESP_SYSTEM_RTC_FAST_MEM_AS_HEAP_DEPCHECK=y CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP=y # CONFIG_ESP_SYSTEM_USE_EH_FRAME is not set # # Memory protection # CONFIG_ESP_SYSTEM_PMP_IDRAM_SPLIT=y # CONFIG_ESP_SYSTEM_PMP_LP_CORE_RESERVE_MEM_EXECUTABLE is not set # end of Memory protection CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=2304 CONFIG_ESP_MAIN_TASK_STACK_SIZE=10240 CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0=y # CONFIG_ESP_MAIN_TASK_AFFINITY_CPU1 is not set # CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY is not set CONFIG_ESP_MAIN_TASK_AFFINITY=0x0 CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE=2048 CONFIG_ESP_CONSOLE_UART_DEFAULT=y # CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG is not set # CONFIG_ESP_CONSOLE_UART_CUSTOM is not set # CONFIG_ESP_CONSOLE_NONE is not set # CONFIG_ESP_CONSOLE_SECONDARY_NONE is not set CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y CONFIG_ESP_CONSOLE_UART=y CONFIG_ESP_CONSOLE_UART_NUM=0 CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0 CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200 CONFIG_ESP_INT_WDT=y CONFIG_ESP_INT_WDT_TIMEOUT_MS=300 CONFIG_ESP_INT_WDT_CHECK_CPU1=y CONFIG_ESP_TASK_WDT_EN=y CONFIG_ESP_TASK_WDT_INIT=y # CONFIG_ESP_TASK_WDT_PANIC is not set CONFIG_ESP_TASK_WDT_TIMEOUT_S=5 CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=y CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1=y # CONFIG_ESP_PANIC_HANDLER_IRAM is not set # CONFIG_ESP_DEBUG_STUBS_ENABLE is not set CONFIG_ESP_DEBUG_OCDAWARE=y CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4=y # # Brownout Detector # CONFIG_ESP_BROWNOUT_DET=y CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7=y # CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set # CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set CONFIG_ESP_BROWNOUT_DET_LVL=7 # end of Brownout Detector CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y CONFIG_ESP_SYSTEM_HW_STACK_GUARD=y CONFIG_ESP_SYSTEM_HW_PC_RECORD=y # end of ESP System Settings # # IPC (Inter-Processor Call) # CONFIG_ESP_IPC_TASK_STACK_SIZE=1024 CONFIG_ESP_IPC_USES_CALLERS_PRIORITY=y CONFIG_ESP_IPC_ISR_ENABLE=y # end of IPC (Inter-Processor Call) # # ESP Timer (High Resolution Timer) # # CONFIG_ESP_TIMER_PROFILING is not set CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER=y CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER=y CONFIG_ESP_TIMER_TASK_STACK_SIZE=3584 CONFIG_ESP_TIMER_INTERRUPT_LEVEL=1 # CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL is not set CONFIG_ESP_TIMER_TASK_AFFINITY=0x0 CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0=y CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0=y # CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is not set CONFIG_ESP_TIMER_IMPL_SYSTIMER=y # end of ESP Timer (High Resolution Timer) # # Wi-Fi # # CONFIG_ESP_HOST_WIFI_ENABLED is not set # end of Wi-Fi # # Core dump # # CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH is not set # CONFIG_ESP_COREDUMP_ENABLE_TO_UART is not set CONFIG_ESP_COREDUMP_ENABLE_TO_NONE=y # end of Core dump # # FAT Filesystem support # CONFIG_FATFS_VOLUME_COUNT=2 CONFIG_FATFS_LFN_NONE=y # CONFIG_FATFS_LFN_HEAP is not set # CONFIG_FATFS_LFN_STACK is not set # CONFIG_FATFS_SECTOR_512 is not set CONFIG_FATFS_SECTOR_4096=y # CONFIG_FATFS_CODEPAGE_DYNAMIC is not set CONFIG_FATFS_CODEPAGE_437=y # CONFIG_FATFS_CODEPAGE_720 is not set # CONFIG_FATFS_CODEPAGE_737 is not set # CONFIG_FATFS_CODEPAGE_771 is not set # CONFIG_FATFS_CODEPAGE_775 is not set # CONFIG_FATFS_CODEPAGE_850 is not set # CONFIG_FATFS_CODEPAGE_852 is not set # CONFIG_FATFS_CODEPAGE_855 is not set # CONFIG_FATFS_CODEPAGE_857 is not set # CONFIG_FATFS_CODEPAGE_860 is not set # CONFIG_FATFS_CODEPAGE_861 is not set # CONFIG_FATFS_CODEPAGE_862 is not set # CONFIG_FATFS_CODEPAGE_863 is not set # CONFIG_FATFS_CODEPAGE_864 is not set # CONFIG_FATFS_CODEPAGE_865 is not set # CONFIG_FATFS_CODEPAGE_866 is not set # CONFIG_FATFS_CODEPAGE_869 is not set # CONFIG_FATFS_CODEPAGE_932 is not set # CONFIG_FATFS_CODEPAGE_936 is not set # CONFIG_FATFS_CODEPAGE_949 is not set # CONFIG_FATFS_CODEPAGE_950 is not set CONFIG_FATFS_CODEPAGE=437 CONFIG_FATFS_FS_LOCK=0 CONFIG_FATFS_TIMEOUT_MS=10000 CONFIG_FATFS_PER_FILE_CACHE=y CONFIG_FATFS_ALLOC_PREFER_EXTRAM=y # CONFIG_FATFS_USE_FASTSEEK is not set CONFIG_FATFS_USE_STRFUNC_NONE=y # CONFIG_FATFS_USE_STRFUNC_WITHOUT_CRLF_CONV is not set # CONFIG_FATFS_USE_STRFUNC_WITH_CRLF_CONV is not set CONFIG_FATFS_VFS_FSTAT_BLKSIZE=0 # CONFIG_FATFS_IMMEDIATE_FSYNC is not set # CONFIG_FATFS_USE_LABEL is not set CONFIG_FATFS_LINK_LOCK=y # CONFIG_FATFS_USE_DYN_BUFFERS is not set # # File system free space calculation behavior # CONFIG_FATFS_DONT_TRUST_FREE_CLUSTER_CNT=0 CONFIG_FATFS_DONT_TRUST_LAST_ALLOC=0 # end of File system free space calculation behavior # end of FAT Filesystem support # # FreeRTOS # # # Kernel # # CONFIG_FREERTOS_UNICORE is not set CONFIG_FREERTOS_HZ=1000 # CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE is not set # CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL is not set CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY=y CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=1 CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536 # CONFIG_FREERTOS_USE_IDLE_HOOK is not set # CONFIG_FREERTOS_USE_TICK_HOOK is not set CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16 # CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY is not set CONFIG_FREERTOS_USE_TIMERS=y CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME="Tmr Svc" # CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU0 is not set # CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU1 is not set CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY=y CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY=0x7FFFFFFF CONFIG_FREERTOS_TIMER_TASK_PRIORITY=1 CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048 CONFIG_FREERTOS_TIMER_QUEUE_LENGTH=10 CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE=0 CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=1 CONFIG_FREERTOS_USE_TRACE_FACILITY=y CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS=y # CONFIG_FREERTOS_USE_LIST_DATA_INTEGRITY_CHECK_BYTES is not set CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID=y CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS=y CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE_U32=y # CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE_U64 is not set # CONFIG_FREERTOS_USE_APPLICATION_TASK_TAG is not set # end of Kernel # # Port # # CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK is not set CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS=y # CONFIG_FREERTOS_TASK_PRE_DELETION_HOOK is not set # CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP is not set CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER=y CONFIG_FREERTOS_ISR_STACKSIZE=1536 CONFIG_FREERTOS_INTERRUPT_BACKTRACE=y CONFIG_FREERTOS_TICK_SUPPORT_SYSTIMER=y CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1=y # CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL3 is not set CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER=y CONFIG_FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER=y # CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH is not set # CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE is not set # end of Port # # Extra # CONFIG_FREERTOS_TASK_CREATE_ALLOW_EXT_MEM=y # end of Extra CONFIG_FREERTOS_PORT=y CONFIG_FREERTOS_NO_AFFINITY=0x7FFFFFFF CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y CONFIG_FREERTOS_DEBUG_OCDAWARE=y CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT=y CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y CONFIG_FREERTOS_NUMBER_OF_CORES=2 # end of FreeRTOS # # Hardware Abstraction Layer (HAL) and Low Level (LL) # CONFIG_HAL_ASSERTION_EQUALS_SYSTEM=y # CONFIG_HAL_ASSERTION_DISABLE is not set # CONFIG_HAL_ASSERTION_SILENT is not set # CONFIG_HAL_ASSERTION_ENABLE is not set CONFIG_HAL_DEFAULT_ASSERTION_LEVEL=2 CONFIG_HAL_SYSTIMER_USE_ROM_IMPL=y CONFIG_HAL_WDT_USE_ROM_IMPL=y CONFIG_HAL_SPI_MASTER_FUNC_IN_IRAM=y CONFIG_HAL_SPI_SLAVE_FUNC_IN_IRAM=y # end of Hardware Abstraction Layer (HAL) and Low Level (LL) # # Heap memory debugging # CONFIG_HEAP_POISONING_DISABLED=y # CONFIG_HEAP_POISONING_LIGHT is not set # CONFIG_HEAP_POISONING_COMPREHENSIVE is not set CONFIG_HEAP_TRACING_OFF=y # CONFIG_HEAP_TRACING_STANDALONE is not set # CONFIG_HEAP_TRACING_TOHOST is not set # CONFIG_HEAP_USE_HOOKS is not set # CONFIG_HEAP_TASK_TRACKING is not set # CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS is not set # CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH is not set # end of Heap memory debugging # # Log # # # Log Level # # CONFIG_LOG_DEFAULT_LEVEL_NONE is not set # CONFIG_LOG_DEFAULT_LEVEL_ERROR is not set # CONFIG_LOG_DEFAULT_LEVEL_WARN is not set CONFIG_LOG_DEFAULT_LEVEL_INFO=y # CONFIG_LOG_DEFAULT_LEVEL_DEBUG is not set # CONFIG_LOG_DEFAULT_LEVEL_VERBOSE is not set CONFIG_LOG_DEFAULT_LEVEL=3 CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT=y # CONFIG_LOG_MAXIMUM_LEVEL_DEBUG is not set # CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE is not set CONFIG_LOG_MAXIMUM_LEVEL=3 # # Level Settings # # CONFIG_LOG_MASTER_LEVEL is not set CONFIG_LOG_DYNAMIC_LEVEL_CONTROL=y # CONFIG_LOG_TAG_LEVEL_IMPL_NONE is not set # CONFIG_LOG_TAG_LEVEL_IMPL_LINKED_LIST is not set CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_AND_LINKED_LIST=y # CONFIG_LOG_TAG_LEVEL_CACHE_ARRAY is not set CONFIG_LOG_TAG_LEVEL_CACHE_BINARY_MIN_HEAP=y CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_SIZE=31 # end of Level Settings # end of Log Level # # Format # # CONFIG_LOG_COLORS is not set CONFIG_LOG_TIMESTAMP_SOURCE_RTOS=y # CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM is not set # end of Format # end of Log # # LWIP # CONFIG_LWIP_ENABLE=y CONFIG_LWIP_LOCAL_HOSTNAME="espressif" # CONFIG_LWIP_NETIF_API is not set CONFIG_LWIP_TCPIP_TASK_PRIO=18 # CONFIG_LWIP_TCPIP_CORE_LOCKING is not set # CONFIG_LWIP_CHECK_THREAD_SAFETY is not set CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y # CONFIG_LWIP_L2_TO_L3_COPY is not set # CONFIG_LWIP_IRAM_OPTIMIZATION is not set # CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION is not set CONFIG_LWIP_TIMERS_ONDEMAND=y CONFIG_LWIP_ND6=y # CONFIG_LWIP_FORCE_ROUTER_FORWARDING is not set CONFIG_LWIP_MAX_SOCKETS=10 # CONFIG_LWIP_USE_ONLY_LWIP_SELECT is not set # CONFIG_LWIP_SO_LINGER is not set CONFIG_LWIP_SO_REUSE=y CONFIG_LWIP_SO_REUSE_RXTOALL=y # CONFIG_LWIP_SO_RCVBUF is not set # CONFIG_LWIP_NETBUF_RECVINFO is not set CONFIG_LWIP_IP_DEFAULT_TTL=64 CONFIG_LWIP_IP4_FRAG=y CONFIG_LWIP_IP6_FRAG=y # CONFIG_LWIP_IP4_REASSEMBLY is not set # CONFIG_LWIP_IP6_REASSEMBLY is not set CONFIG_LWIP_IP_REASS_MAX_PBUFS=10 # CONFIG_LWIP_IP_FORWARD is not set # CONFIG_LWIP_STATS is not set CONFIG_LWIP_ESP_GRATUITOUS_ARP=y CONFIG_LWIP_GARP_TMR_INTERVAL=60 CONFIG_LWIP_ESP_MLDV6_REPORT=y CONFIG_LWIP_MLDV6_TMR_INTERVAL=40 CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32 CONFIG_LWIP_DHCP_DOES_ARP_CHECK=y # CONFIG_LWIP_DHCP_DOES_ACD_CHECK is not set # CONFIG_LWIP_DHCP_DOES_NOT_CHECK_OFFERED_IP is not set # CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID is not set CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID=y # CONFIG_LWIP_DHCP_RESTORE_LAST_IP is not set CONFIG_LWIP_DHCP_OPTIONS_LEN=68 CONFIG_LWIP_NUM_NETIF_CLIENT_DATA=0 CONFIG_LWIP_DHCP_COARSE_TIMER_SECS=1 # # DHCP server # CONFIG_LWIP_DHCPS=y CONFIG_LWIP_DHCPS_LEASE_UNIT=60 CONFIG_LWIP_DHCPS_MAX_STATION_NUM=8 CONFIG_LWIP_DHCPS_STATIC_ENTRIES=y CONFIG_LWIP_DHCPS_ADD_DNS=y # end of DHCP server # CONFIG_LWIP_AUTOIP is not set CONFIG_LWIP_IPV4=y CONFIG_LWIP_IPV6=y # CONFIG_LWIP_IPV6_AUTOCONFIG is not set CONFIG_LWIP_IPV6_NUM_ADDRESSES=3 # CONFIG_LWIP_IPV6_FORWARD is not set # CONFIG_LWIP_NETIF_STATUS_CALLBACK is not set CONFIG_LWIP_NETIF_LOOPBACK=y CONFIG_LWIP_LOOPBACK_MAX_PBUFS=8 # # TCP # CONFIG_LWIP_MAX_ACTIVE_TCP=16 CONFIG_LWIP_MAX_LISTENING_TCP=16 CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION=y CONFIG_LWIP_TCP_MAXRTX=12 CONFIG_LWIP_TCP_SYNMAXRTX=12 CONFIG_LWIP_TCP_MSS=1440 CONFIG_LWIP_TCP_TMR_INTERVAL=250 CONFIG_LWIP_TCP_MSL=60000 CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT=20000 CONFIG_LWIP_TCP_SND_BUF_DEFAULT=5760 CONFIG_LWIP_TCP_WND_DEFAULT=5760 CONFIG_LWIP_TCP_RECVMBOX_SIZE=6 CONFIG_LWIP_TCP_ACCEPTMBOX_SIZE=6 CONFIG_LWIP_TCP_QUEUE_OOSEQ=y CONFIG_LWIP_TCP_OOSEQ_TIMEOUT=6 CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS=4 # CONFIG_LWIP_TCP_SACK_OUT is not set CONFIG_LWIP_TCP_OVERSIZE_MSS=y # CONFIG_LWIP_TCP_OVERSIZE_QUARTER_MSS is not set # CONFIG_LWIP_TCP_OVERSIZE_DISABLE is not set CONFIG_LWIP_TCP_RTO_TIME=1500 # end of TCP # # UDP # CONFIG_LWIP_MAX_UDP_PCBS=16 CONFIG_LWIP_UDP_RECVMBOX_SIZE=6 # end of UDP # # Checksums # # CONFIG_LWIP_CHECKSUM_CHECK_IP is not set # CONFIG_LWIP_CHECKSUM_CHECK_UDP is not set CONFIG_LWIP_CHECKSUM_CHECK_ICMP=y # end of Checksums CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=3072 CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0 is not set # CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU1 is not set CONFIG_LWIP_TCPIP_TASK_AFFINITY=0x7FFFFFFF CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE=3 CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS=5 CONFIG_LWIP_IPV6_ND6_NUM_PREFIXES=5 CONFIG_LWIP_IPV6_ND6_NUM_ROUTERS=3 CONFIG_LWIP_IPV6_ND6_NUM_DESTINATIONS=10 # CONFIG_LWIP_PPP_SUPPORT is not set # CONFIG_LWIP_SLIP_SUPPORT is not set # # ICMP # CONFIG_LWIP_ICMP=y # CONFIG_LWIP_MULTICAST_PING is not set # CONFIG_LWIP_BROADCAST_PING is not set # end of ICMP # # LWIP RAW API # CONFIG_LWIP_MAX_RAW_PCBS=16 # end of LWIP RAW API # # SNTP # CONFIG_LWIP_SNTP_MAX_SERVERS=1 # CONFIG_LWIP_DHCP_GET_NTP_SRV is not set CONFIG_LWIP_SNTP_UPDATE_DELAY=3600000 CONFIG_LWIP_SNTP_STARTUP_DELAY=y CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY=5000 # end of SNTP # # DNS # CONFIG_LWIP_DNS_MAX_HOST_IP=1 CONFIG_LWIP_DNS_MAX_SERVERS=3 # CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT is not set # CONFIG_LWIP_DNS_SETSERVER_WITH_NETIF is not set # end of DNS CONFIG_LWIP_BRIDGEIF_MAX_PORTS=7 CONFIG_LWIP_ESP_LWIP_ASSERT=y # # Hooks # # CONFIG_LWIP_HOOK_TCP_ISN_NONE is not set CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT=y # CONFIG_LWIP_HOOK_TCP_ISN_CUSTOM is not set CONFIG_LWIP_HOOK_IP6_ROUTE_NONE=y # CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT is not set # CONFIG_LWIP_HOOK_IP6_ROUTE_CUSTOM is not set CONFIG_LWIP_HOOK_ND6_GET_GW_NONE=y # CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT is not set # CONFIG_LWIP_HOOK_ND6_GET_GW_CUSTOM is not set CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE=y # CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT is not set # CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM is not set CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE=y # CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT is not set # CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not set CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_NONE=y # CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_CUSTOM is not set # CONFIG_LWIP_HOOK_IP6_INPUT_NONE is not set CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT=y # CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM is not set # end of Hooks # CONFIG_LWIP_DEBUG is not set # end of LWIP # # mbedTLS # CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y # CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC is not set # CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC is not set # CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC is not set CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384 CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096 # CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set # CONFIG_MBEDTLS_DEBUG is not set # # mbedTLS v3.x related # # CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 is not set # CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set # CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK is not set # CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y CONFIG_MBEDTLS_PKCS7_C=y # end of mbedTLS v3.x related # # Certificate Bundle # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=y # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN is not set # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE is not set # CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE is not set # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEPRECATED_LIST is not set CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS=200 # end of Certificate Bundle # CONFIG_MBEDTLS_ECP_RESTARTABLE is not set # CONFIG_MBEDTLS_CMAC_C is not set CONFIG_MBEDTLS_HARDWARE_AES=y CONFIG_MBEDTLS_AES_USE_INTERRUPT=y CONFIG_MBEDTLS_AES_INTERRUPT_LEVEL=0 CONFIG_MBEDTLS_HARDWARE_GCM=y CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y CONFIG_MBEDTLS_HARDWARE_MPI=y # CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI is not set CONFIG_MBEDTLS_MPI_USE_INTERRUPT=y CONFIG_MBEDTLS_MPI_INTERRUPT_LEVEL=0 CONFIG_MBEDTLS_HARDWARE_SHA=y CONFIG_MBEDTLS_HARDWARE_ECC=y CONFIG_MBEDTLS_ECC_OTHER_CURVES_SOFT_FALLBACK=y CONFIG_MBEDTLS_ROM_MD5=y # CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set # CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set CONFIG_MBEDTLS_HAVE_TIME=y # CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set # CONFIG_MBEDTLS_HAVE_TIME_DATE is not set CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y CONFIG_MBEDTLS_SHA1_C=y CONFIG_MBEDTLS_SHA512_C=y # CONFIG_MBEDTLS_SHA3_C is not set CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT=y # CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set # CONFIG_MBEDTLS_TLS_CLIENT_ONLY is not set # CONFIG_MBEDTLS_TLS_DISABLED is not set CONFIG_MBEDTLS_TLS_SERVER=y CONFIG_MBEDTLS_TLS_CLIENT=y CONFIG_MBEDTLS_TLS_ENABLED=y # # TLS Key Exchange Methods # # CONFIG_MBEDTLS_PSK_MODES is not set CONFIG_MBEDTLS_KEY_EXCHANGE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA=y # end of TLS Key Exchange Methods CONFIG_MBEDTLS_SSL_RENEGOTIATION=y CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y # CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set # CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set CONFIG_MBEDTLS_SSL_ALPN=y CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS=y CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS=y # # Symmetric Ciphers # CONFIG_MBEDTLS_AES_C=y # CONFIG_MBEDTLS_CAMELLIA_C is not set # CONFIG_MBEDTLS_DES_C is not set # CONFIG_MBEDTLS_BLOWFISH_C is not set # CONFIG_MBEDTLS_XTEA_C is not set CONFIG_MBEDTLS_CCM_C=y CONFIG_MBEDTLS_GCM_C=y # CONFIG_MBEDTLS_NIST_KW_C is not set # end of Symmetric Ciphers # CONFIG_MBEDTLS_RIPEMD160_C is not set # # Certificates # CONFIG_MBEDTLS_PEM_PARSE_C=y CONFIG_MBEDTLS_PEM_WRITE_C=y CONFIG_MBEDTLS_X509_CRL_PARSE_C=y CONFIG_MBEDTLS_X509_CSR_PARSE_C=y # end of Certificates CONFIG_MBEDTLS_ECP_C=y CONFIG_MBEDTLS_PK_PARSE_EC_EXTENDED=y CONFIG_MBEDTLS_PK_PARSE_EC_COMPRESSED=y # CONFIG_MBEDTLS_DHM_C is not set CONFIG_MBEDTLS_ECDH_C=y CONFIG_MBEDTLS_ECDSA_C=y # CONFIG_MBEDTLS_ECJPAKE_C is not set CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y CONFIG_MBEDTLS_ECP_NIST_OPTIM=y # CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM is not set # CONFIG_MBEDTLS_POLY1305_C is not set # CONFIG_MBEDTLS_CHACHA20_C is not set # CONFIG_MBEDTLS_HKDF_C is not set # CONFIG_MBEDTLS_THREADING_C is not set CONFIG_MBEDTLS_ERROR_STRINGS=y CONFIG_MBEDTLS_FS_IO=y # CONFIG_MBEDTLS_ALLOW_WEAK_CERTIFICATE_VERIFICATION is not set # end of mbedTLS # # ESP-MQTT Configurations # CONFIG_MQTT_PROTOCOL_311=y # CONFIG_MQTT_PROTOCOL_5 is not set CONFIG_MQTT_TRANSPORT_SSL=y CONFIG_MQTT_TRANSPORT_WEBSOCKET=y CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y # CONFIG_MQTT_MSG_ID_INCREMENTAL is not set # CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED is not set # CONFIG_MQTT_REPORT_DELETED_MESSAGES is not set # CONFIG_MQTT_USE_CUSTOM_CONFIG is not set # CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set # CONFIG_MQTT_CUSTOM_OUTBOX is not set # end of ESP-MQTT Configurations # # Newlib # CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y # CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set # CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set # CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set # CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y # CONFIG_NEWLIB_NANO_FORMAT is not set CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y # CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set # CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set # CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set # end of Newlib # # NVS # # CONFIG_NVS_ENCRYPTION is not set # CONFIG_NVS_ASSERT_ERROR_CHECK is not set # CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY is not set # CONFIG_NVS_ALLOCATE_CACHE_IN_SPIRAM is not set # end of NVS # # OpenThread # # CONFIG_OPENTHREAD_ENABLED is not set # # OpenThread Spinel # # CONFIG_OPENTHREAD_SPINEL_ONLY is not set # end of OpenThread Spinel # end of OpenThread # # Protocomm # CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_PATCH_VERSION=y # end of Protocomm # # PThreads # CONFIG_PTHREAD_TASK_PRIO_DEFAULT=5 CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 CONFIG_PTHREAD_STACK_MIN=768 CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY=y # CONFIG_PTHREAD_DEFAULT_CORE_0 is not set # CONFIG_PTHREAD_DEFAULT_CORE_1 is not set CONFIG_PTHREAD_TASK_CORE_DEFAULT=-1 CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread" # end of PThreads # # MMU Config # CONFIG_MMU_PAGE_SIZE_64KB=y CONFIG_MMU_PAGE_MODE="64KB" CONFIG_MMU_PAGE_SIZE=0x10000 # end of MMU Config # # Main Flash configuration # # # SPI Flash behavior when brownout # CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC=y CONFIG_SPI_FLASH_BROWNOUT_RESET=y # end of SPI Flash behavior when brownout # # Optional and Experimental Features (READ DOCS FIRST) # # # Features here require specific hardware (READ DOCS FIRST!) # # CONFIG_SPI_FLASH_AUTO_SUSPEND is not set CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50 # CONFIG_SPI_FLASH_FORCE_ENABLE_XMC_C_SUSPEND is not set # CONFIG_SPI_FLASH_FORCE_ENABLE_C6_H2_SUSPEND is not set # end of Optional and Experimental Features (READ DOCS FIRST) # end of Main Flash configuration # # SPI Flash driver # # CONFIG_SPI_FLASH_VERIFY_WRITE is not set # CONFIG_SPI_FLASH_ENABLE_COUNTERS is not set CONFIG_SPI_FLASH_ROM_DRIVER_PATCH=y CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS=y # CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS is not set # CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED is not set # CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE is not set CONFIG_SPI_FLASH_YIELD_DURING_ERASE=y CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS=20 CONFIG_SPI_FLASH_ERASE_YIELD_TICKS=1 CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE=8192 # CONFIG_SPI_FLASH_SIZE_OVERRIDE is not set # CONFIG_SPI_FLASH_CHECK_ERASE_TIMEOUT_DISABLED is not set # CONFIG_SPI_FLASH_OVERRIDE_CHIP_DRIVER_LIST is not set # # Auto-detect flash chips # CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORTED=y # CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP is not set # CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP is not set # CONFIG_SPI_FLASH_SUPPORT_GD_CHIP is not set # CONFIG_SPI_FLASH_SUPPORT_WINBOND_CHIP is not set # CONFIG_SPI_FLASH_SUPPORT_BOYA_CHIP is not set # CONFIG_SPI_FLASH_SUPPORT_TH_CHIP is not set # end of Auto-detect flash chips CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE=y # end of SPI Flash driver # # SPIFFS Configuration # CONFIG_SPIFFS_MAX_PARTITIONS=3 # # SPIFFS Cache Configuration # CONFIG_SPIFFS_CACHE=y CONFIG_SPIFFS_CACHE_WR=y # CONFIG_SPIFFS_CACHE_STATS is not set # end of SPIFFS Cache Configuration CONFIG_SPIFFS_PAGE_CHECK=y CONFIG_SPIFFS_GC_MAX_RUNS=10 # CONFIG_SPIFFS_GC_STATS is not set CONFIG_SPIFFS_PAGE_SIZE=256 CONFIG_SPIFFS_OBJ_NAME_LEN=32 # CONFIG_SPIFFS_FOLLOW_SYMLINKS is not set CONFIG_SPIFFS_USE_MAGIC=y CONFIG_SPIFFS_USE_MAGIC_LENGTH=y CONFIG_SPIFFS_META_LENGTH=4 CONFIG_SPIFFS_USE_MTIME=y # # Debug Configuration # # CONFIG_SPIFFS_DBG is not set # CONFIG_SPIFFS_API_DBG is not set # CONFIG_SPIFFS_GC_DBG is not set # CONFIG_SPIFFS_CACHE_DBG is not set # CONFIG_SPIFFS_CHECK_DBG is not set # CONFIG_SPIFFS_TEST_VISUALISATION is not set # end of Debug Configuration # end of SPIFFS Configuration # # TCP Transport # # # Websocket # CONFIG_WS_TRANSPORT=y CONFIG_WS_BUFFER_SIZE=1024 # CONFIG_WS_DYNAMIC_BUFFER is not set # end of Websocket # end of TCP Transport # # Ultra Low Power (ULP) Co-processor # # CONFIG_ULP_COPROC_ENABLED is not set # # ULP Debugging Options # # end of ULP Debugging Options # end of Ultra Low Power (ULP) Co-processor # # Unity unit testing library # CONFIG_UNITY_ENABLE_FLOAT=y CONFIG_UNITY_ENABLE_DOUBLE=y # CONFIG_UNITY_ENABLE_64BIT is not set # CONFIG_UNITY_ENABLE_COLOR is not set CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER=y # CONFIG_UNITY_ENABLE_FIXTURE is not set # CONFIG_UNITY_ENABLE_BACKTRACE_ON_FAIL is not set # end of Unity unit testing library # # USB-OTG # CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE=256 CONFIG_USB_HOST_HW_BUFFER_BIAS_BALANCED=y # CONFIG_USB_HOST_HW_BUFFER_BIAS_IN is not set # CONFIG_USB_HOST_HW_BUFFER_BIAS_PERIODIC_OUT is not set # # Hub Driver Configuration # # # Root Port configuration # CONFIG_USB_HOST_DEBOUNCE_DELAY_MS=250 CONFIG_USB_HOST_RESET_HOLD_MS=30 CONFIG_USB_HOST_RESET_RECOVERY_MS=30 CONFIG_USB_HOST_SET_ADDR_RECOVERY_MS=10 # end of Root Port configuration # CONFIG_USB_HOST_HUBS_SUPPORTED is not set # end of Hub Driver Configuration # CONFIG_USB_HOST_ENABLE_ENUM_FILTER_CALLBACK is not set # CONFIG_USB_HOST_DWC_DMA_CAP_MEMORY_IN_PSRAM is not set CONFIG_USB_OTG_SUPPORTED=y # end of USB-OTG # # Virtual file system # CONFIG_VFS_SUPPORT_IO=y CONFIG_VFS_SUPPORT_DIR=y CONFIG_VFS_SUPPORT_SELECT=y CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT=y # CONFIG_VFS_SELECT_IN_RAM is not set CONFIG_VFS_SUPPORT_TERMIOS=y CONFIG_VFS_MAX_COUNT=8 # # Host File System I/O (Semihosting) # CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1 # end of Host File System I/O (Semihosting) CONFIG_VFS_INITIALIZE_DEV_NULL=y # end of Virtual file system # # Wear Levelling # # CONFIG_WL_SECTOR_SIZE_512 is not set CONFIG_WL_SECTOR_SIZE_4096=y CONFIG_WL_SECTOR_SIZE=4096 # end of Wear Levelling # # Wi-Fi Provisioning Manager # CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=16 CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=30 CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y # CONFIG_WIFI_PROV_STA_FAST_SCAN is not set # end of Wi-Fi Provisioning Manager # # Board Support Package # CONFIG_BSP_I2S_NUM=1 # end of Board Support Package # # Audio playback # CONFIG_AUDIO_PLAYER_ENABLE_MP3=y CONFIG_AUDIO_PLAYER_ENABLE_WAV=y CONFIG_AUDIO_PLAYER_LOG_LEVEL=0 # end of Audio playback # # CMake Utilities # # CONFIG_CU_RELINKER_ENABLE is not set # CONFIG_CU_DIAGNOSTICS_COLOR_NEVER is not set CONFIG_CU_DIAGNOSTICS_COLOR_ALWAYS=y # CONFIG_CU_DIAGNOSTICS_COLOR_AUTO is not set # CONFIG_CU_GCC_LTO_ENABLE is not set # CONFIG_CU_GCC_STRING_1BYTE_ALIGN is not set # end of CMake Utilities # # Board Support Package(ESP32-P4) # CONFIG_BSP_ERROR_CHECK=y # # I2C # CONFIG_BSP_I2C_NUM=1 CONFIG_BSP_I2C_FAST_MODE=y CONFIG_BSP_I2C_CLK_SPEED_HZ=400000 # end of I2C # # I2S # # end of I2S # # uSD card - Virtual File System # # CONFIG_BSP_SD_FORMAT_ON_MOUNT_FAIL is not set CONFIG_BSP_SD_MOUNT_POINT="/sdcard" # end of uSD card - Virtual File System # # SPIFFS - Virtual File System # # CONFIG_BSP_SPIFFS_FORMAT_ON_MOUNT_FAIL is not set CONFIG_BSP_SPIFFS_MOUNT_POINT="/spiffs" CONFIG_BSP_SPIFFS_PARTITION_LABEL="storage" CONFIG_BSP_SPIFFS_MAX_FILES=5 # end of SPIFFS - Virtual File System # # Display # CONFIG_BSP_LCD_DPI_BUFFER_NUMS=1 CONFIG_BSP_DISPLAY_BRIGHTNESS_LEDC_CH=1 CONFIG_BSP_LCD_COLOR_FORMAT_RGB565=y # CONFIG_BSP_LCD_COLOR_FORMAT_RGB888 is not set CONFIG_BSP_LCD_TYPE_1024_600=y # CONFIG_BSP_LCD_TYPE_1280_800 is not set # end of Display # end of Board Support Package(ESP32-P4) # # Audio Codec Device Configuration # CONFIG_CODEC_ES8311_SUPPORT=y CONFIG_CODEC_ES7210_SUPPORT=y CONFIG_CODEC_ES7243_SUPPORT=y CONFIG_CODEC_ES7243E_SUPPORT=y CONFIG_CODEC_ES8156_SUPPORT=y CONFIG_CODEC_AW88298_SUPPORT=y CONFIG_CODEC_ES8374_SUPPORT=y CONFIG_CODEC_ES8388_SUPPORT=y CONFIG_CODEC_TAS5805M_SUPPORT=y # CONFIG_CODEC_ZL38063_SUPPORT is not set # end of Audio Codec Device Configuration # # ESP LCD TOUCH # CONFIG_ESP_LCD_TOUCH_MAX_POINTS=5 CONFIG_ESP_LCD_TOUCH_MAX_BUTTONS=1 # end of ESP LCD TOUCH # # ESP LVGL PORT # # CONFIG_LVGL_PORT_ENABLE_PPA is not set # end of ESP LVGL PORT # # LVGL configuration # CONFIG_LV_CONF_SKIP=y # CONFIG_LV_CONF_MINIMAL is not set # # Color Settings # # CONFIG_LV_COLOR_DEPTH_32 is not set # CONFIG_LV_COLOR_DEPTH_24 is not set CONFIG_LV_COLOR_DEPTH_16=y # CONFIG_LV_COLOR_DEPTH_8 is not set # CONFIG_LV_COLOR_DEPTH_1 is not set CONFIG_LV_COLOR_DEPTH=16 # end of Color Settings # # Memory Settings # # CONFIG_LV_USE_BUILTIN_MALLOC is not set CONFIG_LV_USE_CLIB_MALLOC=y # CONFIG_LV_USE_MICROPYTHON_MALLOC is not set # CONFIG_LV_USE_RTTHREAD_MALLOC is not set # CONFIG_LV_USE_CUSTOM_MALLOC is not set # CONFIG_LV_USE_BUILTIN_STRING is not set CONFIG_LV_USE_CLIB_STRING=y # CONFIG_LV_USE_CUSTOM_STRING is not set # CONFIG_LV_USE_BUILTIN_SPRINTF is not set CONFIG_LV_USE_CLIB_SPRINTF=y # CONFIG_LV_USE_CUSTOM_SPRINTF is not set # end of Memory Settings # # HAL Settings # CONFIG_LV_DEF_REFR_PERIOD=15 CONFIG_LV_DPI_DEF=130 # end of HAL Settings # # Operating System (OS) # # CONFIG_LV_OS_NONE is not set # CONFIG_LV_OS_PTHREAD is not set CONFIG_LV_OS_FREERTOS=y # CONFIG_LV_OS_CMSIS_RTOS2 is not set # CONFIG_LV_OS_RTTHREAD is not set # CONFIG_LV_OS_WINDOWS is not set # CONFIG_LV_OS_MQX is not set # CONFIG_LV_OS_CUSTOM is not set CONFIG_LV_USE_FREERTOS_TASK_NOTIFY=y # end of Operating System (OS) # # Rendering Configuration # CONFIG_LV_DRAW_BUF_STRIDE_ALIGN=1 CONFIG_LV_DRAW_BUF_ALIGN=4 CONFIG_LV_DRAW_LAYER_SIMPLE_BUF_SIZE=24576 CONFIG_LV_DRAW_LAYER_MAX_MEMORY=0 CONFIG_LV_DRAW_THREAD_STACK_SIZE=8192 CONFIG_LV_DRAW_THREAD_PRIO=3 CONFIG_LV_USE_DRAW_SW=y CONFIG_LV_DRAW_SW_SUPPORT_RGB565=y CONFIG_LV_DRAW_SW_SUPPORT_RGB565A8=y CONFIG_LV_DRAW_SW_SUPPORT_RGB888=y CONFIG_LV_DRAW_SW_SUPPORT_XRGB8888=y CONFIG_LV_DRAW_SW_SUPPORT_ARGB8888=y CONFIG_LV_DRAW_SW_SUPPORT_L8=y CONFIG_LV_DRAW_SW_SUPPORT_AL88=y CONFIG_LV_DRAW_SW_SUPPORT_A8=y CONFIG_LV_DRAW_SW_SUPPORT_I1=y CONFIG_LV_DRAW_SW_I1_LUM_THRESHOLD=127 CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT=2 # CONFIG_LV_USE_DRAW_ARM2D_SYNC is not set # CONFIG_LV_USE_NATIVE_HELIUM_ASM is not set CONFIG_LV_DRAW_SW_COMPLEX=y # CONFIG_LV_USE_DRAW_SW_COMPLEX_GRADIENTS is not set CONFIG_LV_DRAW_SW_SHADOW_CACHE_SIZE=0 CONFIG_LV_DRAW_SW_CIRCLE_CACHE_SIZE=4 CONFIG_LV_DRAW_SW_ASM_NONE=y # CONFIG_LV_DRAW_SW_ASM_NEON is not set # CONFIG_LV_DRAW_SW_ASM_HELIUM is not set # CONFIG_LV_DRAW_SW_ASM_CUSTOM is not set CONFIG_LV_USE_DRAW_SW_ASM=0 # CONFIG_LV_USE_DRAW_VGLITE is not set # CONFIG_LV_USE_PXP is not set # CONFIG_LV_USE_DRAW_G2D is not set # CONFIG_LV_USE_DRAW_DAVE2D is not set # CONFIG_LV_USE_DRAW_SDL is not set # CONFIG_LV_USE_DRAW_VG_LITE is not set # CONFIG_LV_USE_VECTOR_GRAPHIC is not set # CONFIG_LV_USE_DRAW_DMA2D is not set # end of Rendering Configuration # # Feature Configuration # # # Logging # # CONFIG_LV_USE_LOG is not set # end of Logging # # Asserts # CONFIG_LV_USE_ASSERT_NULL=y CONFIG_LV_USE_ASSERT_MALLOC=y # CONFIG_LV_USE_ASSERT_STYLE is not set # CONFIG_LV_USE_ASSERT_MEM_INTEGRITY is not set # CONFIG_LV_USE_ASSERT_OBJ is not set CONFIG_LV_ASSERT_HANDLER_INCLUDE="assert.h" # end of Asserts # # Debug # # CONFIG_LV_USE_REFR_DEBUG is not set # CONFIG_LV_USE_LAYER_DEBUG is not set # CONFIG_LV_USE_PARALLEL_DRAW_DEBUG is not set # end of Debug # # Others # # CONFIG_LV_ENABLE_GLOBAL_CUSTOM is not set CONFIG_LV_CACHE_DEF_SIZE=0 CONFIG_LV_IMAGE_HEADER_CACHE_DEF_CNT=0 CONFIG_LV_GRADIENT_MAX_STOPS=2 CONFIG_LV_COLOR_MIX_ROUND_OFS=128 # CONFIG_LV_OBJ_STYLE_CACHE is not set # CONFIG_LV_USE_OBJ_ID is not set # CONFIG_LV_USE_OBJ_NAME is not set # CONFIG_LV_USE_OBJ_PROPERTY is not set # end of Others # end of Feature Configuration # # Compiler Settings # # CONFIG_LV_BIG_ENDIAN_SYSTEM is not set CONFIG_LV_ATTRIBUTE_MEM_ALIGN_SIZE=1 CONFIG_LV_ATTRIBUTE_FAST_MEM_USE_IRAM=y # CONFIG_LV_USE_FLOAT is not set # CONFIG_LV_USE_MATRIX is not set # CONFIG_LV_USE_PRIVATE_API is not set # end of Compiler Settings # # Font Usage # # # Enable built-in fonts # # CONFIG_LV_FONT_MONTSERRAT_8 is not set # CONFIG_LV_FONT_MONTSERRAT_10 is not set CONFIG_LV_FONT_MONTSERRAT_12=y CONFIG_LV_FONT_MONTSERRAT_14=y CONFIG_LV_FONT_MONTSERRAT_16=y CONFIG_LV_FONT_MONTSERRAT_18=y CONFIG_LV_FONT_MONTSERRAT_20=y CONFIG_LV_FONT_MONTSERRAT_22=y CONFIG_LV_FONT_MONTSERRAT_24=y CONFIG_LV_FONT_MONTSERRAT_26=y # CONFIG_LV_FONT_MONTSERRAT_28 is not set # CONFIG_LV_FONT_MONTSERRAT_30 is not set # CONFIG_LV_FONT_MONTSERRAT_32 is not set # CONFIG_LV_FONT_MONTSERRAT_34 is not set # CONFIG_LV_FONT_MONTSERRAT_36 is not set # CONFIG_LV_FONT_MONTSERRAT_38 is not set # CONFIG_LV_FONT_MONTSERRAT_40 is not set # CONFIG_LV_FONT_MONTSERRAT_42 is not set # CONFIG_LV_FONT_MONTSERRAT_44 is not set # CONFIG_LV_FONT_MONTSERRAT_46 is not set # CONFIG_LV_FONT_MONTSERRAT_48 is not set # CONFIG_LV_FONT_MONTSERRAT_28_COMPRESSED is not set # CONFIG_LV_FONT_DEJAVU_16_PERSIAN_HEBREW is not set # CONFIG_LV_FONT_SIMSUN_14_CJK is not set # CONFIG_LV_FONT_SIMSUN_16_CJK is not set # CONFIG_LV_FONT_SOURCE_HAN_SANS_SC_14_CJK is not set # CONFIG_LV_FONT_SOURCE_HAN_SANS_SC_16_CJK is not set # CONFIG_LV_FONT_UNSCII_8 is not set # CONFIG_LV_FONT_UNSCII_16 is not set # end of Enable built-in fonts # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_8 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_10 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_12 is not set CONFIG_LV_FONT_DEFAULT_MONTSERRAT_14=y # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_16 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_18 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_20 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_22 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_24 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_26 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_30 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_32 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_34 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_36 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_38 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_40 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_42 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_44 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_46 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_48 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28_COMPRESSED is not set # CONFIG_LV_FONT_DEFAULT_DEJAVU_16_PERSIAN_HEBREW is not set # CONFIG_LV_FONT_DEFAULT_SIMSUN_14_CJK is not set # CONFIG_LV_FONT_DEFAULT_SIMSUN_16_CJK is not set # CONFIG_LV_FONT_DEFAULT_SOURCE_HAN_SANS_SC_14_CJK is not set # CONFIG_LV_FONT_DEFAULT_SOURCE_HAN_SANS_SC_16_CJK is not set # CONFIG_LV_FONT_DEFAULT_UNSCII_8 is not set # CONFIG_LV_FONT_DEFAULT_UNSCII_16 is not set # CONFIG_LV_FONT_FMT_TXT_LARGE is not set CONFIG_LV_USE_FONT_COMPRESSED=y CONFIG_LV_USE_FONT_PLACEHOLDER=y # # Enable static fonts # # CONFIG_LV_DEMO_BENCHMARK_ALIGNED_FONTS is not set # end of Enable static fonts # end of Font Usage # # Text Settings # CONFIG_LV_TXT_ENC_UTF8=y # CONFIG_LV_TXT_ENC_ASCII is not set CONFIG_LV_TXT_BREAK_CHARS=" ,.;:-_" CONFIG_LV_TXT_LINE_BREAK_LONG_LEN=0 CONFIG_LV_TXT_COLOR_CMD="#" # CONFIG_LV_USE_BIDI is not set # CONFIG_LV_USE_ARABIC_PERSIAN_CHARS is not set # end of Text Settings # # Widget Usage # CONFIG_LV_WIDGETS_HAS_DEFAULT_VALUE=y CONFIG_LV_USE_ANIMIMG=y CONFIG_LV_USE_ARC=y CONFIG_LV_USE_BAR=y CONFIG_LV_USE_BUTTON=y CONFIG_LV_USE_BUTTONMATRIX=y CONFIG_LV_USE_CALENDAR=y # CONFIG_LV_CALENDAR_WEEK_STARTS_MONDAY is not set # # Days name configuration # CONFIG_LV_MONDAY_STR="Mo" CONFIG_LV_TUESDAY_STR="Tu" CONFIG_LV_WEDNESDAY_STR="We" CONFIG_LV_THURSDAY_STR="Th" CONFIG_LV_FRIDAY_STR="Fr" CONFIG_LV_SATURDAY_STR="Sa" CONFIG_LV_SUNDAY_STR="Su" # end of Days name configuration CONFIG_LV_USE_CALENDAR_HEADER_ARROW=y CONFIG_LV_USE_CALENDAR_HEADER_DROPDOWN=y # CONFIG_LV_USE_CALENDAR_CHINESE is not set CONFIG_LV_USE_CANVAS=y CONFIG_LV_USE_CHART=y CONFIG_LV_USE_CHECKBOX=y CONFIG_LV_USE_DROPDOWN=y CONFIG_LV_USE_IMAGE=y CONFIG_LV_USE_IMAGEBUTTON=y CONFIG_LV_USE_KEYBOARD=y CONFIG_LV_USE_LABEL=y CONFIG_LV_LABEL_TEXT_SELECTION=y CONFIG_LV_LABEL_LONG_TXT_HINT=y CONFIG_LV_LABEL_WAIT_CHAR_COUNT=3 CONFIG_LV_USE_LED=y CONFIG_LV_USE_LINE=y CONFIG_LV_USE_LIST=y CONFIG_LV_USE_MENU=y CONFIG_LV_USE_MSGBOX=y CONFIG_LV_USE_ROLLER=y CONFIG_LV_USE_SCALE=y CONFIG_LV_USE_SLIDER=y CONFIG_LV_USE_SPAN=y CONFIG_LV_SPAN_SNIPPET_STACK_SIZE=64 CONFIG_LV_USE_SPINBOX=y CONFIG_LV_USE_SPINNER=y CONFIG_LV_USE_SWITCH=y CONFIG_LV_USE_TEXTAREA=y CONFIG_LV_TEXTAREA_DEF_PWD_SHOW_TIME=1500 CONFIG_LV_USE_TABLE=y CONFIG_LV_USE_TABVIEW=y CONFIG_LV_USE_TILEVIEW=y CONFIG_LV_USE_WIN=y # end of Widget Usage # # Themes # CONFIG_LV_USE_THEME_DEFAULT=y # CONFIG_LV_THEME_DEFAULT_DARK is not set CONFIG_LV_THEME_DEFAULT_GROW=y CONFIG_LV_THEME_DEFAULT_TRANSITION_TIME=80 CONFIG_LV_USE_THEME_SIMPLE=y # CONFIG_LV_USE_THEME_MONO is not set # end of Themes # # Layouts # CONFIG_LV_USE_FLEX=y CONFIG_LV_USE_GRID=y # end of Layouts # # 3rd Party Libraries # CONFIG_LV_FS_DEFAULT_DRIVER_LETTER=0 # CONFIG_LV_USE_FS_STDIO is not set # CONFIG_LV_USE_FS_POSIX is not set # CONFIG_LV_USE_FS_WIN32 is not set # CONFIG_LV_USE_FS_FATFS is not set # CONFIG_LV_USE_FS_MEMFS is not set # CONFIG_LV_USE_FS_LITTLEFS is not set # CONFIG_LV_USE_FS_ARDUINO_ESP_LITTLEFS is not set # CONFIG_LV_USE_FS_ARDUINO_SD is not set # CONFIG_LV_USE_FS_UEFI is not set # CONFIG_LV_USE_LODEPNG is not set # CONFIG_LV_USE_LIBPNG is not set # CONFIG_LV_USE_BMP is not set # CONFIG_LV_USE_TJPGD is not set # CONFIG_LV_USE_LIBJPEG_TURBO is not set # CONFIG_LV_USE_GIF is not set # CONFIG_LV_BIN_DECODER_RAM_LOAD is not set # CONFIG_LV_USE_RLE is not set # CONFIG_LV_USE_QRCODE is not set # CONFIG_LV_USE_BARCODE is not set # CONFIG_LV_USE_FREETYPE is not set # CONFIG_LV_USE_TINY_TTF is not set # CONFIG_LV_USE_RLOTTIE is not set # CONFIG_LV_USE_THORVG is not set # CONFIG_LV_USE_LZ4 is not set # CONFIG_LV_USE_FFMPEG is not set # end of 3rd Party Libraries # # Others # # CONFIG_LV_USE_SNAPSHOT is not set CONFIG_LV_USE_SYSMON=y CONFIG_LV_USE_PERF_MONITOR=y # CONFIG_LV_PERF_MONITOR_ALIGN_TOP_LEFT is not set # CONFIG_LV_PERF_MONITOR_ALIGN_TOP_MID is not set # CONFIG_LV_PERF_MONITOR_ALIGN_TOP_RIGHT is not set # CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_LEFT is not set # CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_MID is not set CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_RIGHT=y # CONFIG_LV_PERF_MONITOR_ALIGN_LEFT_MID is not set # CONFIG_LV_PERF_MONITOR_ALIGN_RIGHT_MID is not set # CONFIG_LV_PERF_MONITOR_ALIGN_CENTER is not set # CONFIG_LV_USE_PERF_MONITOR_LOG_MODE is not set # CONFIG_LV_USE_PROFILER is not set # CONFIG_LV_USE_MONKEY is not set # CONFIG_LV_USE_GRIDNAV is not set # CONFIG_LV_USE_FRAGMENT is not set CONFIG_LV_USE_IMGFONT=y CONFIG_LV_USE_OBSERVER=y # CONFIG_LV_USE_IME_PINYIN is not set # CONFIG_LV_USE_FILE_EXPLORER is not set # CONFIG_LV_USE_FONT_MANAGER is not set # CONFIG_LV_USE_TEST is not set # CONFIG_LV_USE_XML is not set # CONFIG_LV_USE_COLOR_FILTER is not set CONFIG_LVGL_VERSION_MAJOR=9 CONFIG_LVGL_VERSION_MINOR=3 CONFIG_LVGL_VERSION_PATCH=0 # end of Others # # Devices # # CONFIG_LV_USE_SDL is not set # CONFIG_LV_USE_X11 is not set # CONFIG_LV_USE_WAYLAND is not set # CONFIG_LV_USE_LINUX_FBDEV is not set # CONFIG_LV_USE_NUTTX is not set # CONFIG_LV_USE_LINUX_DRM is not set # CONFIG_LV_USE_TFT_ESPI is not set # CONFIG_LV_USE_EVDEV is not set # CONFIG_LV_USE_LIBINPUT is not set # CONFIG_LV_USE_ST7735 is not set # CONFIG_LV_USE_ST7789 is not set # CONFIG_LV_USE_ST7796 is not set # CONFIG_LV_USE_ILI9341 is not set # CONFIG_LV_USE_GENERIC_MIPI is not set # CONFIG_LV_USE_RENESAS_GLCDC is not set # CONFIG_LV_USE_ST_LTDC is not set # CONFIG_LV_USE_FT81X is not set # CONFIG_LV_USE_UEFI is not set # CONFIG_LV_USE_OPENGLES is not set # CONFIG_LV_USE_QNX is not set # end of Devices # # Examples # CONFIG_LV_BUILD_EXAMPLES=y # end of Examples # # Demos # CONFIG_LV_BUILD_DEMOS=y CONFIG_LV_USE_DEMO_WIDGETS=y # CONFIG_LV_USE_DEMO_KEYPAD_AND_ENCODER is not set CONFIG_LV_USE_DEMO_BENCHMARK=y CONFIG_LV_USE_DEMO_RENDER=y CONFIG_LV_USE_DEMO_SCROLL=y CONFIG_LV_USE_DEMO_STRESS=y CONFIG_LV_USE_DEMO_TRANSFORM=y CONFIG_LV_USE_DEMO_MUSIC=y # CONFIG_LV_DEMO_MUSIC_SQUARE is not set # CONFIG_LV_DEMO_MUSIC_LANDSCAPE is not set # CONFIG_LV_DEMO_MUSIC_ROUND is not set # CONFIG_LV_DEMO_MUSIC_LARGE is not set CONFIG_LV_DEMO_MUSIC_AUTO_PLAY=y CONFIG_LV_USE_DEMO_FLEX_LAYOUT=y CONFIG_LV_USE_DEMO_MULTILANG=y # CONFIG_LV_USE_DEMO_SMARTWATCH is not set # CONFIG_LV_USE_DEMO_EBIKE is not set # CONFIG_LV_USE_DEMO_HIGH_RES is not set # end of Demos # end of LVGL configuration # end of Component config CONFIG_IDF_EXPERIMENTAL_FEATURES=y # Deprecated options for backward compatibility # CONFIG_APP_BUILD_TYPE_ELF_RAM is not set # CONFIG_NO_BLOBS is not set # CONFIG_LOG_BOOTLOADER_LEVEL_NONE is not set # CONFIG_LOG_BOOTLOADER_LEVEL_ERROR is not set # CONFIG_LOG_BOOTLOADER_LEVEL_WARN is not set CONFIG_LOG_BOOTLOADER_LEVEL_INFO=y # CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG is not set # CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE is not set CONFIG_LOG_BOOTLOADER_LEVEL=3 # CONFIG_APP_ROLLBACK_ENABLE is not set # CONFIG_FLASH_ENCRYPTION_ENABLED is not set CONFIG_FLASHMODE_QIO=y # CONFIG_FLASHMODE_QOUT is not set # CONFIG_FLASHMODE_DIO is not set # CONFIG_FLASHMODE_DOUT is not set CONFIG_MONITOR_BAUD=115200 # CONFIG_OPTIMIZATION_LEVEL_DEBUG is not set # CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG is not set # CONFIG_COMPILER_OPTIMIZATION_DEFAULT is not set # CONFIG_OPTIMIZATION_LEVEL_RELEASE is not set # CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE is not set CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED=y # CONFIG_OPTIMIZATION_ASSERTIONS_SILENT is not set # CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED is not set CONFIG_OPTIMIZATION_ASSERTION_LEVEL=2 # CONFIG_CXX_EXCEPTIONS is not set CONFIG_STACK_CHECK_NONE=y # CONFIG_STACK_CHECK_NORM is not set # CONFIG_STACK_CHECK_STRONG is not set # CONFIG_STACK_CHECK_ALL is not set # CONFIG_WARN_WRITE_STRINGS is not set # CONFIG_ESP32_APPTRACE_DEST_TRAX is not set CONFIG_ESP32_APPTRACE_DEST_NONE=y CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y # CONFIG_CAM_CTLR_MIPI_CSI_ISR_IRAM_SAFE is not set # CONFIG_CAM_CTLR_ISP_DVP_ISR_IRAM_SAFE is not set # CONFIG_CAM_CTLR_DVP_CAM_ISR_IRAM_SAFE is not set # CONFIG_MCPWM_ISR_IN_IRAM is not set # CONFIG_EVENT_LOOP_PROFILING is not set CONFIG_POST_EVENTS_FROM_ISR=y CONFIG_POST_EVENTS_FROM_IRAM_ISR=y CONFIG_GDBSTUB_SUPPORT_TASKS=y CONFIG_GDBSTUB_MAX_TASKS=32 # CONFIG_OTA_ALLOW_HTTP is not set CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304 CONFIG_MAIN_TASK_STACK_SIZE=10240 CONFIG_CONSOLE_UART_DEFAULT=y # CONFIG_CONSOLE_UART_CUSTOM is not set # CONFIG_CONSOLE_UART_NONE is not set # CONFIG_ESP_CONSOLE_UART_NONE is not set CONFIG_CONSOLE_UART=y CONFIG_CONSOLE_UART_NUM=0 CONFIG_CONSOLE_UART_BAUDRATE=115200 CONFIG_INT_WDT=y CONFIG_INT_WDT_TIMEOUT_MS=300 CONFIG_INT_WDT_CHECK_CPU1=y CONFIG_TASK_WDT=y CONFIG_ESP_TASK_WDT=y # CONFIG_TASK_WDT_PANIC is not set CONFIG_TASK_WDT_TIMEOUT_S=5 CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0=y CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1=y # CONFIG_ESP32_DEBUG_STUBS_ENABLE is not set CONFIG_BROWNOUT_DET=y CONFIG_BROWNOUT_DET_LVL_SEL_7=y # CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set # CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set CONFIG_BROWNOUT_DET_LVL=7 CONFIG_IPC_TASK_STACK_SIZE=1024 CONFIG_TIMER_TASK_STACK_SIZE=3584 # CONFIG_ESP32_ENABLE_COREDUMP_TO_FLASH is not set # CONFIG_ESP32_ENABLE_COREDUMP_TO_UART is not set CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE=y CONFIG_TIMER_TASK_PRIORITY=1 CONFIG_TIMER_TASK_STACK_DEPTH=2048 CONFIG_TIMER_QUEUE_LENGTH=10 # CONFIG_ENABLE_STATIC_TASK_CLEAN_UP_HOOK is not set CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY=y # CONFIG_HAL_ASSERTION_SILIENT is not set # CONFIG_L2_TO_L3_COPY is not set CONFIG_ESP_GRATUITOUS_ARP=y CONFIG_GARP_TMR_INTERVAL=60 CONFIG_TCPIP_RECVMBOX_SIZE=32 CONFIG_TCP_MAXRTX=12 CONFIG_TCP_SYNMAXRTX=12 CONFIG_TCP_MSS=1440 CONFIG_TCP_MSL=60000 CONFIG_TCP_SND_BUF_DEFAULT=5760 CONFIG_TCP_WND_DEFAULT=5760 CONFIG_TCP_RECVMBOX_SIZE=6 CONFIG_TCP_QUEUE_OOSEQ=y CONFIG_TCP_OVERSIZE_MSS=y # CONFIG_TCP_OVERSIZE_QUARTER_MSS is not set # CONFIG_TCP_OVERSIZE_DISABLE is not set CONFIG_UDP_RECVMBOX_SIZE=6 CONFIG_TCPIP_TASK_STACK_SIZE=3072 CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_TCPIP_TASK_AFFINITY_CPU0 is not set # CONFIG_TCPIP_TASK_AFFINITY_CPU1 is not set CONFIG_TCPIP_TASK_AFFINITY=0x7FFFFFFF # CONFIG_PPP_SUPPORT is not set CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5 CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 CONFIG_ESP32_PTHREAD_STACK_MIN=768 CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY=y # CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0 is not set # CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1 is not set CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT=-1 CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT="pthread" CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS=y # CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS is not set # CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED is not set CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT=y CONFIG_SUPPORT_TERMIOS=y CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS=1 # End of deprecated options
84,589
sdkconfig
en
unknown
unknown
{}
0
{}
0015/map_tiles_projects
espressif_esp32_p4_function_ev_board/sdkconfig.defaults
# This file was generated using idf.py save-defconfig. It can be edited manually. # Espressif IoT Development Framework (ESP-IDF) 5.4.0 Project Minimal Configuration # CONFIG_IDF_TARGET="esp32p4" CONFIG_ESPTOOLPY_FLASHMODE_QIO=y CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y CONFIG_PARTITION_TABLE_CUSTOM=y CONFIG_COMPILER_OPTIMIZATION_PERF=y CONFIG_SPIRAM=y CONFIG_SPIRAM_SPEED_200M=y CONFIG_SPIRAM_XIP_FROM_PSRAM=y CONFIG_CACHE_L2_CACHE_256KB=y CONFIG_CACHE_L2_CACHE_LINE_128B=y CONFIG_ESP_MAIN_TASK_STACK_SIZE=10240 CONFIG_FREERTOS_HZ=1000 CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID=y CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS=y CONFIG_LV_USE_CLIB_MALLOC=y CONFIG_LV_USE_CLIB_STRING=y CONFIG_LV_USE_CLIB_SPRINTF=y CONFIG_LV_DEF_REFR_PERIOD=15 CONFIG_LV_OS_FREERTOS=y CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT=2 CONFIG_LV_ATTRIBUTE_FAST_MEM_USE_IRAM=y CONFIG_LV_FONT_MONTSERRAT_12=y CONFIG_LV_FONT_MONTSERRAT_16=y CONFIG_LV_FONT_MONTSERRAT_18=y CONFIG_LV_FONT_MONTSERRAT_20=y CONFIG_LV_FONT_MONTSERRAT_22=y CONFIG_LV_FONT_MONTSERRAT_24=y CONFIG_LV_FONT_MONTSERRAT_26=y CONFIG_LV_USE_FONT_COMPRESSED=y CONFIG_LV_TXT_BREAK_CHARS=" ,.;:-_" CONFIG_LV_USE_SYSMON=y CONFIG_LV_USE_PERF_MONITOR=y CONFIG_LV_USE_IMGFONT=y CONFIG_LV_USE_DEMO_WIDGETS=y CONFIG_LV_USE_DEMO_BENCHMARK=y CONFIG_LV_USE_DEMO_RENDER=y CONFIG_LV_USE_DEMO_SCROLL=y CONFIG_LV_USE_DEMO_STRESS=y CONFIG_LV_USE_DEMO_TRANSFORM=y CONFIG_LV_USE_DEMO_MUSIC=y CONFIG_LV_DEMO_MUSIC_AUTO_PLAY=y CONFIG_LV_USE_DEMO_FLEX_LAYOUT=y CONFIG_LV_USE_DEMO_MULTILANG=y CONFIG_IDF_EXPERIMENTAL_FEATURES=y
1,523
sdkconfig
defaults
en
unknown
unknown
{}
0
{}
0015/map_tiles_projects
waveshare_esp32_p4_wifi6_touch_lcd_xc/sdkconfig
# # Automatically generated file. DO NOT EDIT. # Espressif IoT Development Framework (ESP-IDF) 5.4.2 Project Configuration # CONFIG_SOC_ADC_SUPPORTED=y CONFIG_SOC_ANA_CMPR_SUPPORTED=y CONFIG_SOC_DEDICATED_GPIO_SUPPORTED=y CONFIG_SOC_UART_SUPPORTED=y CONFIG_SOC_GDMA_SUPPORTED=y CONFIG_SOC_AHB_GDMA_SUPPORTED=y CONFIG_SOC_AXI_GDMA_SUPPORTED=y CONFIG_SOC_DW_GDMA_SUPPORTED=y CONFIG_SOC_DMA2D_SUPPORTED=y CONFIG_SOC_GPTIMER_SUPPORTED=y CONFIG_SOC_PCNT_SUPPORTED=y CONFIG_SOC_LCDCAM_SUPPORTED=y CONFIG_SOC_LCDCAM_CAM_SUPPORTED=y CONFIG_SOC_LCDCAM_I80_LCD_SUPPORTED=y CONFIG_SOC_LCDCAM_RGB_LCD_SUPPORTED=y CONFIG_SOC_MIPI_CSI_SUPPORTED=y CONFIG_SOC_MIPI_DSI_SUPPORTED=y CONFIG_SOC_MCPWM_SUPPORTED=y CONFIG_SOC_TWAI_SUPPORTED=y CONFIG_SOC_ETM_SUPPORTED=y CONFIG_SOC_PARLIO_SUPPORTED=y CONFIG_SOC_ASYNC_MEMCPY_SUPPORTED=y CONFIG_SOC_EMAC_SUPPORTED=y CONFIG_SOC_USB_OTG_SUPPORTED=y CONFIG_SOC_WIRELESS_HOST_SUPPORTED=y CONFIG_SOC_USB_SERIAL_JTAG_SUPPORTED=y CONFIG_SOC_TEMP_SENSOR_SUPPORTED=y CONFIG_SOC_SUPPORTS_SECURE_DL_MODE=y CONFIG_SOC_ULP_SUPPORTED=y CONFIG_SOC_LP_CORE_SUPPORTED=y CONFIG_SOC_EFUSE_KEY_PURPOSE_FIELD=y CONFIG_SOC_EFUSE_SUPPORTED=y CONFIG_SOC_RTC_FAST_MEM_SUPPORTED=y CONFIG_SOC_RTC_MEM_SUPPORTED=y CONFIG_SOC_RMT_SUPPORTED=y CONFIG_SOC_I2S_SUPPORTED=y CONFIG_SOC_SDM_SUPPORTED=y CONFIG_SOC_GPSPI_SUPPORTED=y CONFIG_SOC_LEDC_SUPPORTED=y CONFIG_SOC_ISP_SUPPORTED=y CONFIG_SOC_I2C_SUPPORTED=y CONFIG_SOC_SYSTIMER_SUPPORTED=y CONFIG_SOC_AES_SUPPORTED=y CONFIG_SOC_MPI_SUPPORTED=y CONFIG_SOC_SHA_SUPPORTED=y CONFIG_SOC_HMAC_SUPPORTED=y CONFIG_SOC_DIG_SIGN_SUPPORTED=y CONFIG_SOC_ECC_SUPPORTED=y CONFIG_SOC_ECC_EXTENDED_MODES_SUPPORTED=y CONFIG_SOC_FLASH_ENC_SUPPORTED=y CONFIG_SOC_SECURE_BOOT_SUPPORTED=y CONFIG_SOC_BOD_SUPPORTED=y CONFIG_SOC_APM_SUPPORTED=y CONFIG_SOC_PMU_SUPPORTED=y CONFIG_SOC_DCDC_SUPPORTED=y CONFIG_SOC_PAU_SUPPORTED=y CONFIG_SOC_LP_TIMER_SUPPORTED=y CONFIG_SOC_ULP_LP_UART_SUPPORTED=y CONFIG_SOC_LP_GPIO_MATRIX_SUPPORTED=y CONFIG_SOC_LP_PERIPHERALS_SUPPORTED=y CONFIG_SOC_LP_I2C_SUPPORTED=y CONFIG_SOC_LP_I2S_SUPPORTED=y CONFIG_SOC_LP_SPI_SUPPORTED=y CONFIG_SOC_LP_ADC_SUPPORTED=y CONFIG_SOC_LP_VAD_SUPPORTED=y CONFIG_SOC_SPIRAM_SUPPORTED=y CONFIG_SOC_PSRAM_DMA_CAPABLE=y CONFIG_SOC_SDMMC_HOST_SUPPORTED=y CONFIG_SOC_CLK_TREE_SUPPORTED=y CONFIG_SOC_ASSIST_DEBUG_SUPPORTED=y CONFIG_SOC_DEBUG_PROBE_SUPPORTED=y CONFIG_SOC_WDT_SUPPORTED=y CONFIG_SOC_SPI_FLASH_SUPPORTED=y CONFIG_SOC_TOUCH_SENSOR_SUPPORTED=y CONFIG_SOC_RNG_SUPPORTED=y CONFIG_SOC_GP_LDO_SUPPORTED=y CONFIG_SOC_PPA_SUPPORTED=y CONFIG_SOC_LIGHT_SLEEP_SUPPORTED=y CONFIG_SOC_DEEP_SLEEP_SUPPORTED=y CONFIG_SOC_PM_SUPPORTED=y CONFIG_SOC_SIMD_INSTRUCTION_SUPPORTED=y CONFIG_SOC_XTAL_SUPPORT_40M=y CONFIG_SOC_AES_SUPPORT_DMA=y CONFIG_SOC_AES_SUPPORT_GCM=y CONFIG_SOC_AES_GDMA=y CONFIG_SOC_AES_SUPPORT_AES_128=y CONFIG_SOC_AES_SUPPORT_AES_256=y CONFIG_SOC_ADC_RTC_CTRL_SUPPORTED=y CONFIG_SOC_ADC_DIG_CTRL_SUPPORTED=y CONFIG_SOC_ADC_DMA_SUPPORTED=y CONFIG_SOC_ADC_PERIPH_NUM=2 CONFIG_SOC_ADC_MAX_CHANNEL_NUM=8 CONFIG_SOC_ADC_ATTEN_NUM=4 CONFIG_SOC_ADC_DIGI_CONTROLLER_NUM=2 CONFIG_SOC_ADC_PATT_LEN_MAX=16 CONFIG_SOC_ADC_DIGI_MAX_BITWIDTH=12 CONFIG_SOC_ADC_DIGI_MIN_BITWIDTH=12 CONFIG_SOC_ADC_DIGI_IIR_FILTER_NUM=2 CONFIG_SOC_ADC_DIGI_MONITOR_NUM=2 CONFIG_SOC_ADC_DIGI_RESULT_BYTES=4 CONFIG_SOC_ADC_DIGI_DATA_BYTES_PER_CONV=4 CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH=83333 CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW=611 CONFIG_SOC_ADC_RTC_MIN_BITWIDTH=12 CONFIG_SOC_ADC_RTC_MAX_BITWIDTH=12 CONFIG_SOC_ADC_CALIBRATION_V1_SUPPORTED=y CONFIG_SOC_ADC_SELF_HW_CALI_SUPPORTED=y CONFIG_SOC_ADC_CALIB_CHAN_COMPENS_SUPPORTED=y CONFIG_SOC_ADC_SHARED_POWER=y CONFIG_SOC_BROWNOUT_RESET_SUPPORTED=y CONFIG_SOC_SHARED_IDCACHE_SUPPORTED=y CONFIG_SOC_CACHE_WRITEBACK_SUPPORTED=y CONFIG_SOC_CACHE_FREEZE_SUPPORTED=y CONFIG_SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE=y CONFIG_SOC_CPU_CORES_NUM=2 CONFIG_SOC_CPU_INTR_NUM=32 CONFIG_SOC_CPU_HAS_FLEXIBLE_INTC=y CONFIG_SOC_INT_CLIC_SUPPORTED=y CONFIG_SOC_INT_HW_NESTED_SUPPORTED=y CONFIG_SOC_BRANCH_PREDICTOR_SUPPORTED=y CONFIG_SOC_CPU_COPROC_NUM=3 CONFIG_SOC_CPU_HAS_FPU=y CONFIG_SOC_CPU_HAS_FPU_EXT_ILL_BUG=y CONFIG_SOC_CPU_HAS_HWLOOP=y CONFIG_SOC_CPU_HAS_HWLOOP_STATE_BUG=y CONFIG_SOC_CPU_HAS_PIE=y CONFIG_SOC_HP_CPU_HAS_MULTIPLE_CORES=y CONFIG_SOC_CPU_BREAKPOINTS_NUM=3 CONFIG_SOC_CPU_WATCHPOINTS_NUM=3 CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE=0x100 CONFIG_SOC_CPU_HAS_PMA=y CONFIG_SOC_CPU_IDRAM_SPLIT_USING_PMP=y CONFIG_SOC_CPU_PMP_REGION_GRANULARITY=128 CONFIG_SOC_CPU_HAS_LOCKUP_RESET=y CONFIG_SOC_SIMD_PREFERRED_DATA_ALIGNMENT=16 CONFIG_SOC_DS_SIGNATURE_MAX_BIT_LEN=4096 CONFIG_SOC_DS_KEY_PARAM_MD_IV_LENGTH=16 CONFIG_SOC_DS_KEY_CHECK_MAX_WAIT_US=1100 CONFIG_SOC_DMA_CAN_ACCESS_FLASH=y CONFIG_SOC_AHB_GDMA_VERSION=2 CONFIG_SOC_GDMA_SUPPORT_CRC=y CONFIG_SOC_GDMA_NUM_GROUPS_MAX=2 CONFIG_SOC_GDMA_PAIRS_PER_GROUP_MAX=3 CONFIG_SOC_AXI_GDMA_SUPPORT_PSRAM=y CONFIG_SOC_GDMA_SUPPORT_ETM=y CONFIG_SOC_GDMA_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_AXI_DMA_EXT_MEM_ENC_ALIGNMENT=16 CONFIG_SOC_DMA2D_GROUPS=1 CONFIG_SOC_DMA2D_TX_CHANNELS_PER_GROUP=3 CONFIG_SOC_DMA2D_RX_CHANNELS_PER_GROUP=2 CONFIG_SOC_ETM_GROUPS=1 CONFIG_SOC_ETM_CHANNELS_PER_GROUP=50 CONFIG_SOC_ETM_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_GPIO_PORT=1 CONFIG_SOC_GPIO_PIN_COUNT=55 CONFIG_SOC_GPIO_SUPPORT_PIN_GLITCH_FILTER=y CONFIG_SOC_GPIO_FLEX_GLITCH_FILTER_NUM=8 CONFIG_SOC_GPIO_SUPPORT_PIN_HYS_FILTER=y CONFIG_SOC_GPIO_SUPPORT_ETM=y CONFIG_SOC_GPIO_SUPPORT_RTC_INDEPENDENT=y CONFIG_SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP=y CONFIG_SOC_LP_IO_HAS_INDEPENDENT_WAKEUP_SOURCE=y CONFIG_SOC_LP_IO_CLOCK_IS_INDEPENDENT=y CONFIG_SOC_GPIO_VALID_GPIO_MASK=0x007FFFFFFFFFFFFF CONFIG_SOC_GPIO_IN_RANGE_MAX=54 CONFIG_SOC_GPIO_OUT_RANGE_MAX=54 CONFIG_SOC_GPIO_DEEP_SLEEP_WAKE_VALID_GPIO_MASK=0 CONFIG_SOC_GPIO_DEEP_SLEEP_WAKE_SUPPORTED_PIN_CNT=16 CONFIG_SOC_GPIO_VALID_DIGITAL_IO_PAD_MASK=0x007FFFFFFFFF0000 CONFIG_SOC_GPIO_CLOCKOUT_BY_GPIO_MATRIX=y CONFIG_SOC_GPIO_CLOCKOUT_CHANNEL_NUM=2 CONFIG_SOC_CLOCKOUT_SUPPORT_CHANNEL_DIVIDER=y CONFIG_SOC_DEBUG_PROBE_NUM_UNIT=1 CONFIG_SOC_DEBUG_PROBE_MAX_OUTPUT_WIDTH=16 CONFIG_SOC_GPIO_SUPPORT_FORCE_HOLD=y CONFIG_SOC_RTCIO_PIN_COUNT=16 CONFIG_SOC_RTCIO_INPUT_OUTPUT_SUPPORTED=y CONFIG_SOC_RTCIO_HOLD_SUPPORTED=y CONFIG_SOC_RTCIO_WAKE_SUPPORTED=y CONFIG_SOC_RTCIO_EDGE_WAKE_SUPPORTED=y CONFIG_SOC_DEDIC_GPIO_OUT_CHANNELS_NUM=8 CONFIG_SOC_DEDIC_GPIO_IN_CHANNELS_NUM=8 CONFIG_SOC_DEDIC_PERIPH_ALWAYS_ENABLE=y CONFIG_SOC_ANA_CMPR_NUM=2 CONFIG_SOC_ANA_CMPR_CAN_DISTINGUISH_EDGE=y CONFIG_SOC_ANA_CMPR_SUPPORT_ETM=y CONFIG_SOC_I2C_NUM=3 CONFIG_SOC_HP_I2C_NUM=2 CONFIG_SOC_I2C_FIFO_LEN=32 CONFIG_SOC_I2C_CMD_REG_NUM=8 CONFIG_SOC_I2C_SUPPORT_SLAVE=y CONFIG_SOC_I2C_SUPPORT_HW_FSM_RST=y CONFIG_SOC_I2C_SUPPORT_HW_CLR_BUS=y CONFIG_SOC_I2C_SUPPORT_XTAL=y CONFIG_SOC_I2C_SUPPORT_RTC=y CONFIG_SOC_I2C_SUPPORT_10BIT_ADDR=y CONFIG_SOC_I2C_SLAVE_SUPPORT_BROADCAST=y CONFIG_SOC_I2C_SLAVE_CAN_GET_STRETCH_CAUSE=y CONFIG_SOC_I2C_SLAVE_SUPPORT_I2CRAM_ACCESS=y CONFIG_SOC_I2C_SLAVE_SUPPORT_SLAVE_UNMATCH=y CONFIG_SOC_I2C_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_LP_I2C_NUM=1 CONFIG_SOC_LP_I2C_FIFO_LEN=16 CONFIG_SOC_I2S_NUM=3 CONFIG_SOC_I2S_HW_VERSION_2=y CONFIG_SOC_I2S_SUPPORTS_ETM=y CONFIG_SOC_I2S_SUPPORTS_XTAL=y CONFIG_SOC_I2S_SUPPORTS_APLL=y CONFIG_SOC_I2S_SUPPORTS_PCM=y CONFIG_SOC_I2S_SUPPORTS_PDM=y CONFIG_SOC_I2S_SUPPORTS_PDM_TX=y CONFIG_SOC_I2S_SUPPORTS_PDM_RX=y CONFIG_SOC_I2S_SUPPORTS_PDM_RX_HP_FILTER=y CONFIG_SOC_I2S_SUPPORTS_TX_SYNC_CNT=y CONFIG_SOC_I2S_SUPPORTS_TDM=y CONFIG_SOC_I2S_PDM_MAX_TX_LINES=2 CONFIG_SOC_I2S_PDM_MAX_RX_LINES=4 CONFIG_SOC_I2S_TDM_FULL_DATA_WIDTH=y CONFIG_SOC_I2S_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_LP_I2S_NUM=1 CONFIG_SOC_ISP_BF_SUPPORTED=y CONFIG_SOC_ISP_CCM_SUPPORTED=y CONFIG_SOC_ISP_DEMOSAIC_SUPPORTED=y CONFIG_SOC_ISP_DVP_SUPPORTED=y CONFIG_SOC_ISP_SHARPEN_SUPPORTED=y CONFIG_SOC_ISP_COLOR_SUPPORTED=y CONFIG_SOC_ISP_LSC_SUPPORTED=y CONFIG_SOC_ISP_SHARE_CSI_BRG=y CONFIG_SOC_ISP_NUMS=1 CONFIG_SOC_ISP_DVP_CTLR_NUMS=1 CONFIG_SOC_ISP_AE_CTLR_NUMS=1 CONFIG_SOC_ISP_AE_BLOCK_X_NUMS=5 CONFIG_SOC_ISP_AE_BLOCK_Y_NUMS=5 CONFIG_SOC_ISP_AF_CTLR_NUMS=1 CONFIG_SOC_ISP_AF_WINDOW_NUMS=3 CONFIG_SOC_ISP_BF_TEMPLATE_X_NUMS=3 CONFIG_SOC_ISP_BF_TEMPLATE_Y_NUMS=3 CONFIG_SOC_ISP_CCM_DIMENSION=3 CONFIG_SOC_ISP_DEMOSAIC_GRAD_RATIO_INT_BITS=2 CONFIG_SOC_ISP_DEMOSAIC_GRAD_RATIO_DEC_BITS=4 CONFIG_SOC_ISP_DEMOSAIC_GRAD_RATIO_RES_BITS=26 CONFIG_SOC_ISP_DVP_DATA_WIDTH_MAX=16 CONFIG_SOC_ISP_SHARPEN_TEMPLATE_X_NUMS=3 CONFIG_SOC_ISP_SHARPEN_TEMPLATE_Y_NUMS=3 CONFIG_SOC_ISP_SHARPEN_H_FREQ_COEF_INT_BITS=3 CONFIG_SOC_ISP_SHARPEN_H_FREQ_COEF_DEC_BITS=5 CONFIG_SOC_ISP_SHARPEN_H_FREQ_COEF_RES_BITS=24 CONFIG_SOC_ISP_SHARPEN_M_FREQ_COEF_INT_BITS=3 CONFIG_SOC_ISP_SHARPEN_M_FREQ_COEF_DEC_BITS=5 CONFIG_SOC_ISP_SHARPEN_M_FREQ_COEF_RES_BITS=24 CONFIG_SOC_ISP_HIST_CTLR_NUMS=1 CONFIG_SOC_ISP_HIST_BLOCK_X_NUMS=5 CONFIG_SOC_ISP_HIST_BLOCK_Y_NUMS=5 CONFIG_SOC_ISP_HIST_SEGMENT_NUMS=16 CONFIG_SOC_ISP_HIST_INTERVAL_NUMS=15 CONFIG_SOC_ISP_LSC_GRAD_RATIO_INT_BITS=2 CONFIG_SOC_ISP_LSC_GRAD_RATIO_DEC_BITS=8 CONFIG_SOC_ISP_LSC_GRAD_RATIO_RES_BITS=22 CONFIG_SOC_LEDC_SUPPORT_PLL_DIV_CLOCK=y CONFIG_SOC_LEDC_SUPPORT_XTAL_CLOCK=y CONFIG_SOC_LEDC_TIMER_NUM=4 CONFIG_SOC_LEDC_CHANNEL_NUM=8 CONFIG_SOC_LEDC_TIMER_BIT_WIDTH=20 CONFIG_SOC_LEDC_GAMMA_CURVE_FADE_SUPPORTED=y CONFIG_SOC_LEDC_GAMMA_CURVE_FADE_RANGE_MAX=16 CONFIG_SOC_LEDC_SUPPORT_FADE_STOP=y CONFIG_SOC_LEDC_FADE_PARAMS_BIT_WIDTH=10 CONFIG_SOC_LEDC_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_MMU_PERIPH_NUM=2 CONFIG_SOC_MMU_LINEAR_ADDRESS_REGION_NUM=2 CONFIG_SOC_MMU_DI_VADDR_SHARED=y CONFIG_SOC_MMU_PER_EXT_MEM_TARGET=y CONFIG_SOC_MPU_MIN_REGION_SIZE=0x20000000 CONFIG_SOC_MPU_REGIONS_MAX_NUM=8 CONFIG_SOC_PCNT_GROUPS=1 CONFIG_SOC_PCNT_UNITS_PER_GROUP=4 CONFIG_SOC_PCNT_CHANNELS_PER_UNIT=2 CONFIG_SOC_PCNT_THRES_POINT_PER_UNIT=2 CONFIG_SOC_PCNT_SUPPORT_RUNTIME_THRES_UPDATE=y CONFIG_SOC_PCNT_SUPPORT_CLEAR_SIGNAL=y CONFIG_SOC_PCNT_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_RMT_GROUPS=1 CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP=4 CONFIG_SOC_RMT_RX_CANDIDATES_PER_GROUP=4 CONFIG_SOC_RMT_CHANNELS_PER_GROUP=8 CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL=48 CONFIG_SOC_RMT_SUPPORT_RX_PINGPONG=y CONFIG_SOC_RMT_SUPPORT_RX_DEMODULATION=y CONFIG_SOC_RMT_SUPPORT_TX_ASYNC_STOP=y CONFIG_SOC_RMT_SUPPORT_TX_LOOP_COUNT=y CONFIG_SOC_RMT_SUPPORT_TX_LOOP_AUTO_STOP=y CONFIG_SOC_RMT_SUPPORT_TX_SYNCHRO=y CONFIG_SOC_RMT_SUPPORT_TX_CARRIER_DATA_ONLY=y CONFIG_SOC_RMT_SUPPORT_XTAL=y CONFIG_SOC_RMT_SUPPORT_RC_FAST=y CONFIG_SOC_RMT_SUPPORT_DMA=y CONFIG_SOC_RMT_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_LCD_I80_SUPPORTED=y CONFIG_SOC_LCD_RGB_SUPPORTED=y CONFIG_SOC_LCDCAM_I80_NUM_BUSES=1 CONFIG_SOC_LCDCAM_I80_BUS_WIDTH=24 CONFIG_SOC_LCDCAM_RGB_NUM_PANELS=1 CONFIG_SOC_LCDCAM_RGB_DATA_WIDTH=24 CONFIG_SOC_LCD_SUPPORT_RGB_YUV_CONV=y CONFIG_SOC_MCPWM_GROUPS=2 CONFIG_SOC_MCPWM_TIMERS_PER_GROUP=3 CONFIG_SOC_MCPWM_OPERATORS_PER_GROUP=3 CONFIG_SOC_MCPWM_COMPARATORS_PER_OPERATOR=2 CONFIG_SOC_MCPWM_EVENT_COMPARATORS_PER_OPERATOR=2 CONFIG_SOC_MCPWM_GENERATORS_PER_OPERATOR=2 CONFIG_SOC_MCPWM_TRIGGERS_PER_OPERATOR=2 CONFIG_SOC_MCPWM_GPIO_FAULTS_PER_GROUP=3 CONFIG_SOC_MCPWM_CAPTURE_TIMERS_PER_GROUP=y CONFIG_SOC_MCPWM_CAPTURE_CHANNELS_PER_TIMER=3 CONFIG_SOC_MCPWM_GPIO_SYNCHROS_PER_GROUP=3 CONFIG_SOC_MCPWM_SWSYNC_CAN_PROPAGATE=y CONFIG_SOC_MCPWM_SUPPORT_ETM=y CONFIG_SOC_MCPWM_SUPPORT_EVENT_COMPARATOR=y CONFIG_SOC_MCPWM_CAPTURE_CLK_FROM_GROUP=y CONFIG_SOC_MCPWM_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_USB_OTG_PERIPH_NUM=2 CONFIG_SOC_USB_UTMI_PHY_NUM=1 CONFIG_SOC_USB_UTMI_PHY_NO_POWER_OFF_ISO=y CONFIG_SOC_PARLIO_GROUPS=1 CONFIG_SOC_PARLIO_TX_UNITS_PER_GROUP=1 CONFIG_SOC_PARLIO_RX_UNITS_PER_GROUP=1 CONFIG_SOC_PARLIO_TX_UNIT_MAX_DATA_WIDTH=16 CONFIG_SOC_PARLIO_RX_UNIT_MAX_DATA_WIDTH=16 CONFIG_SOC_PARLIO_TX_CLK_SUPPORT_GATING=y CONFIG_SOC_PARLIO_RX_CLK_SUPPORT_GATING=y CONFIG_SOC_PARLIO_RX_CLK_SUPPORT_OUTPUT=y CONFIG_SOC_PARLIO_TRANS_BIT_ALIGN=y CONFIG_SOC_PARLIO_TX_SIZE_BY_DMA=y CONFIG_SOC_PARLIO_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_MPI_MEM_BLOCKS_NUM=4 CONFIG_SOC_MPI_OPERATIONS_NUM=3 CONFIG_SOC_RSA_MAX_BIT_LEN=4096 CONFIG_SOC_SDMMC_USE_IOMUX=y CONFIG_SOC_SDMMC_USE_GPIO_MATRIX=y CONFIG_SOC_SDMMC_NUM_SLOTS=2 CONFIG_SOC_SDMMC_DELAY_PHASE_NUM=4 CONFIG_SOC_SDMMC_IO_POWER_EXTERNAL=y CONFIG_SOC_SDMMC_PSRAM_DMA_CAPABLE=y CONFIG_SOC_SDMMC_UHS_I_SUPPORTED=y CONFIG_SOC_SHA_DMA_MAX_BUFFER_SIZE=3968 CONFIG_SOC_SHA_SUPPORT_DMA=y CONFIG_SOC_SHA_SUPPORT_RESUME=y CONFIG_SOC_SHA_GDMA=y CONFIG_SOC_SHA_SUPPORT_SHA1=y CONFIG_SOC_SHA_SUPPORT_SHA224=y CONFIG_SOC_SHA_SUPPORT_SHA256=y CONFIG_SOC_SHA_SUPPORT_SHA384=y CONFIG_SOC_SHA_SUPPORT_SHA512=y CONFIG_SOC_SHA_SUPPORT_SHA512_224=y CONFIG_SOC_SHA_SUPPORT_SHA512_256=y CONFIG_SOC_SHA_SUPPORT_SHA512_T=y CONFIG_SOC_ECDSA_SUPPORT_EXPORT_PUBKEY=y CONFIG_SOC_ECDSA_SUPPORT_DETERMINISTIC_MODE=y CONFIG_SOC_ECDSA_USES_MPI=y CONFIG_SOC_SDM_GROUPS=1 CONFIG_SOC_SDM_CHANNELS_PER_GROUP=8 CONFIG_SOC_SDM_CLK_SUPPORT_PLL_F80M=y CONFIG_SOC_SDM_CLK_SUPPORT_XTAL=y CONFIG_SOC_SPI_PERIPH_NUM=3 CONFIG_SOC_SPI_MAX_CS_NUM=6 CONFIG_SOC_SPI_MAXIMUM_BUFFER_SIZE=64 CONFIG_SOC_SPI_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_SPI_SUPPORT_SLAVE_HD_VER2=y CONFIG_SOC_SPI_SLAVE_SUPPORT_SEG_TRANS=y CONFIG_SOC_SPI_SUPPORT_DDRCLK=y CONFIG_SOC_SPI_SUPPORT_CD_SIG=y CONFIG_SOC_SPI_SUPPORT_OCT=y CONFIG_SOC_SPI_SUPPORT_CLK_XTAL=y CONFIG_SOC_SPI_SUPPORT_CLK_RC_FAST=y CONFIG_SOC_SPI_SUPPORT_CLK_SPLL=y CONFIG_SOC_MSPI_HAS_INDEPENT_IOMUX=y CONFIG_SOC_MEMSPI_IS_INDEPENDENT=y CONFIG_SOC_SPI_MAX_PRE_DIVIDER=16 CONFIG_SOC_LP_SPI_PERIPH_NUM=y CONFIG_SOC_LP_SPI_MAXIMUM_BUFFER_SIZE=64 CONFIG_SOC_SPIRAM_XIP_SUPPORTED=y CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_WAIT_IDLE=y CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_SUSPEND=y CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_RESUME=y CONFIG_SOC_SPI_MEM_SUPPORT_IDLE_INTR=y CONFIG_SOC_SPI_MEM_SUPPORT_SW_SUSPEND=y CONFIG_SOC_SPI_MEM_SUPPORT_CHECK_SUS=y CONFIG_SOC_SPI_MEM_SUPPORT_TIMING_TUNING=y CONFIG_SOC_MEMSPI_TIMING_TUNING_BY_DQS=y CONFIG_SOC_SPI_MEM_SUPPORT_CACHE_32BIT_ADDR_MAP=y CONFIG_SOC_SPI_PERIPH_SUPPORT_CONTROL_DUMMY_OUT=y CONFIG_SOC_MEMSPI_SRC_FREQ_80M_SUPPORTED=y CONFIG_SOC_MEMSPI_SRC_FREQ_40M_SUPPORTED=y CONFIG_SOC_MEMSPI_SRC_FREQ_20M_SUPPORTED=y CONFIG_SOC_MEMSPI_FLASH_PSRAM_INDEPENDENT=y CONFIG_SOC_SYSTIMER_COUNTER_NUM=2 CONFIG_SOC_SYSTIMER_ALARM_NUM=3 CONFIG_SOC_SYSTIMER_BIT_WIDTH_LO=32 CONFIG_SOC_SYSTIMER_BIT_WIDTH_HI=20 CONFIG_SOC_SYSTIMER_FIXED_DIVIDER=y CONFIG_SOC_SYSTIMER_SUPPORT_RC_FAST=y CONFIG_SOC_SYSTIMER_INT_LEVEL=y CONFIG_SOC_SYSTIMER_ALARM_MISS_COMPENSATE=y CONFIG_SOC_SYSTIMER_SUPPORT_ETM=y CONFIG_SOC_LP_TIMER_BIT_WIDTH_LO=32 CONFIG_SOC_LP_TIMER_BIT_WIDTH_HI=16 CONFIG_SOC_TIMER_GROUPS=2 CONFIG_SOC_TIMER_GROUP_TIMERS_PER_GROUP=2 CONFIG_SOC_TIMER_GROUP_COUNTER_BIT_WIDTH=54 CONFIG_SOC_TIMER_GROUP_SUPPORT_XTAL=y CONFIG_SOC_TIMER_GROUP_SUPPORT_RC_FAST=y CONFIG_SOC_TIMER_GROUP_TOTAL_TIMERS=4 CONFIG_SOC_TIMER_SUPPORT_ETM=y CONFIG_SOC_TIMER_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_MWDT_SUPPORT_XTAL=y CONFIG_SOC_MWDT_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_TOUCH_SENSOR_VERSION=3 CONFIG_SOC_TOUCH_SENSOR_NUM=14 CONFIG_SOC_TOUCH_SUPPORT_SLEEP_WAKEUP=y CONFIG_SOC_TOUCH_SUPPORT_WATERPROOF=y CONFIG_SOC_TOUCH_SUPPORT_PROX_SENSING=y CONFIG_SOC_TOUCH_PROXIMITY_CHANNEL_NUM=3 CONFIG_SOC_TOUCH_PROXIMITY_MEAS_DONE_SUPPORTED=y CONFIG_SOC_TOUCH_SUPPORT_FREQ_HOP=y CONFIG_SOC_TOUCH_SAMPLE_CFG_NUM=3 CONFIG_SOC_TWAI_CONTROLLER_NUM=3 CONFIG_SOC_TWAI_CLK_SUPPORT_XTAL=y CONFIG_SOC_TWAI_BRP_MIN=2 CONFIG_SOC_TWAI_BRP_MAX=32768 CONFIG_SOC_TWAI_SUPPORTS_RX_STATUS=y CONFIG_SOC_TWAI_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_EFUSE_DIS_PAD_JTAG=y CONFIG_SOC_EFUSE_DIS_USB_JTAG=y CONFIG_SOC_EFUSE_DIS_DIRECT_BOOT=y CONFIG_SOC_EFUSE_SOFT_DIS_JTAG=y CONFIG_SOC_EFUSE_DIS_DOWNLOAD_MSPI=y CONFIG_SOC_EFUSE_ECDSA_KEY=y CONFIG_SOC_KEY_MANAGER_ECDSA_KEY_DEPLOY=y CONFIG_SOC_KEY_MANAGER_FE_KEY_DEPLOY=y CONFIG_SOC_SECURE_BOOT_V2_RSA=y CONFIG_SOC_SECURE_BOOT_V2_ECC=y CONFIG_SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS=3 CONFIG_SOC_EFUSE_REVOKE_BOOT_KEY_DIGESTS=y CONFIG_SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY=y CONFIG_SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX=64 CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES=y CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_OPTIONS=y CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_128=y CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_256=y CONFIG_SOC_UART_NUM=6 CONFIG_SOC_UART_HP_NUM=5 CONFIG_SOC_UART_LP_NUM=1 CONFIG_SOC_UART_FIFO_LEN=128 CONFIG_SOC_LP_UART_FIFO_LEN=16 CONFIG_SOC_UART_BITRATE_MAX=5000000 CONFIG_SOC_UART_SUPPORT_PLL_F80M_CLK=y CONFIG_SOC_UART_SUPPORT_RTC_CLK=y CONFIG_SOC_UART_SUPPORT_XTAL_CLK=y CONFIG_SOC_UART_SUPPORT_WAKEUP_INT=y CONFIG_SOC_UART_HAS_LP_UART=y CONFIG_SOC_UART_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_UART_SUPPORT_FSM_TX_WAIT_SEND=y CONFIG_SOC_LP_I2S_SUPPORT_VAD=y CONFIG_SOC_COEX_HW_PTI=y CONFIG_SOC_PHY_DIG_REGS_MEM_SIZE=21 CONFIG_SOC_WIFI_LIGHT_SLEEP_CLK_WIDTH=12 CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP=y CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP_MODE_PER_PIN=y CONFIG_SOC_PM_EXT1_WAKEUP_BY_PMU=y CONFIG_SOC_PM_SUPPORT_WIFI_WAKEUP=y CONFIG_SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP=y CONFIG_SOC_PM_SUPPORT_XTAL32K_PD=y CONFIG_SOC_PM_SUPPORT_RC32K_PD=y CONFIG_SOC_PM_SUPPORT_RC_FAST_PD=y CONFIG_SOC_PM_SUPPORT_VDDSDIO_PD=y CONFIG_SOC_PM_SUPPORT_TOP_PD=y CONFIG_SOC_PM_SUPPORT_CNNT_PD=y CONFIG_SOC_PM_SUPPORT_RTC_PERIPH_PD=y CONFIG_SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY=y CONFIG_SOC_PM_CPU_RETENTION_BY_SW=y CONFIG_SOC_PM_CACHE_RETENTION_BY_PAU=y CONFIG_SOC_PM_PAU_LINK_NUM=4 CONFIG_SOC_PM_PAU_REGDMA_LINK_MULTI_ADDR=y CONFIG_SOC_PAU_IN_TOP_DOMAIN=y CONFIG_SOC_CPU_IN_TOP_DOMAIN=y CONFIG_SOC_PM_PAU_REGDMA_UPDATE_CACHE_BEFORE_WAIT_COMPARE=y CONFIG_SOC_SLEEP_SYSTIMER_STALL_WORKAROUND=y CONFIG_SOC_SLEEP_TGWDT_STOP_WORKAROUND=y CONFIG_SOC_PM_RETENTION_MODULE_NUM=64 CONFIG_SOC_PSRAM_VDD_POWER_MPLL=y CONFIG_SOC_CLK_RC_FAST_SUPPORT_CALIBRATION=y CONFIG_SOC_CLK_APLL_SUPPORTED=y CONFIG_SOC_CLK_MPLL_SUPPORTED=y CONFIG_SOC_CLK_SDIO_PLL_SUPPORTED=y CONFIG_SOC_CLK_XTAL32K_SUPPORTED=y CONFIG_SOC_CLK_RC32K_SUPPORTED=y CONFIG_SOC_CLK_LP_FAST_SUPPORT_LP_PLL=y CONFIG_SOC_CLK_LP_FAST_SUPPORT_XTAL=y CONFIG_SOC_PERIPH_CLK_CTRL_SHARED=y CONFIG_SOC_TEMPERATURE_SENSOR_LP_PLL_SUPPORT=y CONFIG_SOC_TEMPERATURE_SENSOR_INTR_SUPPORT=y CONFIG_SOC_TSENS_IS_INDEPENDENT_FROM_ADC=y CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_ETM=y CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_SLEEP_RETENTION=y CONFIG_SOC_MEM_TCM_SUPPORTED=y CONFIG_SOC_MEM_NON_CONTIGUOUS_SRAM=y CONFIG_SOC_ASYNCHRONOUS_BUS_ERROR_MODE=y CONFIG_SOC_EMAC_IEEE_1588_SUPPORT=y CONFIG_SOC_EMAC_USE_MULTI_IO_MUX=y CONFIG_SOC_EMAC_MII_USE_GPIO_MATRIX=y CONFIG_SOC_JPEG_CODEC_SUPPORTED=y CONFIG_SOC_JPEG_DECODE_SUPPORTED=y CONFIG_SOC_JPEG_ENCODE_SUPPORTED=y CONFIG_SOC_LCDCAM_CAM_SUPPORT_RGB_YUV_CONV=y CONFIG_SOC_LCDCAM_CAM_PERIPH_NUM=1 CONFIG_SOC_LCDCAM_CAM_DATA_WIDTH_MAX=16 CONFIG_SOC_LP_CORE_SUPPORT_ETM=y CONFIG_SOC_LP_CORE_SUPPORT_LP_ADC=y CONFIG_SOC_LP_CORE_SUPPORT_LP_VAD=y CONFIG_IDF_CMAKE=y CONFIG_IDF_TOOLCHAIN="gcc" CONFIG_IDF_TOOLCHAIN_GCC=y CONFIG_IDF_TARGET_ARCH_RISCV=y CONFIG_IDF_TARGET_ARCH="riscv" CONFIG_IDF_TARGET="esp32p4" CONFIG_IDF_INIT_VERSION="5.4.2" CONFIG_IDF_TARGET_ESP32P4=y CONFIG_IDF_FIRMWARE_CHIP_ID=0x0012 # # Build type # CONFIG_APP_BUILD_TYPE_APP_2NDBOOT=y # CONFIG_APP_BUILD_TYPE_RAM is not set CONFIG_APP_BUILD_GENERATE_BINARIES=y CONFIG_APP_BUILD_BOOTLOADER=y CONFIG_APP_BUILD_USE_FLASH_SECTIONS=y # CONFIG_APP_REPRODUCIBLE_BUILD is not set # CONFIG_APP_NO_BLOBS is not set # end of Build type # # Bootloader config # # # Bootloader manager # CONFIG_BOOTLOADER_COMPILE_TIME_DATE=y CONFIG_BOOTLOADER_PROJECT_VER=1 # end of Bootloader manager CONFIG_BOOTLOADER_OFFSET_IN_FLASH=0x2000 CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG is not set # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF is not set # # Log # # CONFIG_BOOTLOADER_LOG_LEVEL_NONE is not set # CONFIG_BOOTLOADER_LOG_LEVEL_ERROR is not set # CONFIG_BOOTLOADER_LOG_LEVEL_WARN is not set CONFIG_BOOTLOADER_LOG_LEVEL_INFO=y # CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG is not set # CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE is not set CONFIG_BOOTLOADER_LOG_LEVEL=3 # # Format # # CONFIG_BOOTLOADER_LOG_COLORS is not set CONFIG_BOOTLOADER_LOG_TIMESTAMP_SOURCE_CPU_TICKS=y # end of Format # end of Log # # Serial Flash Configurations # # CONFIG_BOOTLOADER_FLASH_DC_AWARE is not set CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT=y CONFIG_BOOTLOADER_FLASH_32BIT_ADDR=y CONFIG_BOOTLOADER_FLASH_NEEDS_32BIT_FEAT=y CONFIG_BOOTLOADER_FLASH_NEEDS_32BIT_ADDR_QUAD_FLASH=y # CONFIG_BOOTLOADER_CACHE_32BIT_ADDR_QUAD_FLASH is not set # end of Serial Flash Configurations # CONFIG_BOOTLOADER_FACTORY_RESET is not set # CONFIG_BOOTLOADER_APP_TEST is not set CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE=y CONFIG_BOOTLOADER_WDT_ENABLE=y # CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE is not set CONFIG_BOOTLOADER_WDT_TIME_MS=9000 # CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS is not set CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0 # CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC is not set # end of Bootloader config # # Security features # CONFIG_SECURE_BOOT_V2_RSA_SUPPORTED=y CONFIG_SECURE_BOOT_V2_ECC_SUPPORTED=y CONFIG_SECURE_BOOT_V2_PREFERRED=y # CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT is not set # CONFIG_SECURE_BOOT is not set # CONFIG_SECURE_FLASH_ENC_ENABLED is not set CONFIG_SECURE_ROM_DL_MODE_ENABLED=y # end of Security features # # Application manager # CONFIG_APP_COMPILE_TIME_DATE=y # CONFIG_APP_EXCLUDE_PROJECT_VER_VAR is not set # CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR is not set # CONFIG_APP_PROJECT_VER_FROM_CONFIG is not set CONFIG_APP_RETRIEVE_LEN_ELF_SHA=9 # end of Application manager CONFIG_ESP_ROM_HAS_CRC_LE=y CONFIG_ESP_ROM_HAS_CRC_BE=y CONFIG_ESP_ROM_UART_CLK_IS_XTAL=y CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM=6 CONFIG_ESP_ROM_USB_OTG_NUM=5 CONFIG_ESP_ROM_HAS_RETARGETABLE_LOCKING=y CONFIG_ESP_ROM_GET_CLK_FREQ=y CONFIG_ESP_ROM_HAS_RVFPLIB=y CONFIG_ESP_ROM_HAS_HAL_WDT=y CONFIG_ESP_ROM_HAS_HAL_SYSTIMER=y CONFIG_ESP_ROM_HAS_LAYOUT_TABLE=y CONFIG_ESP_ROM_WDT_INIT_PATCH=y CONFIG_ESP_ROM_HAS_LP_ROM=y CONFIG_ESP_ROM_WITHOUT_REGI2C=y CONFIG_ESP_ROM_HAS_NEWLIB=y CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT=y CONFIG_ESP_ROM_HAS_NEWLIB_NANO_PRINTF_FLOAT_BUG=y CONFIG_ESP_ROM_HAS_VERSION=y CONFIG_ESP_ROM_CLIC_INT_TYPE_PATCH=y CONFIG_ESP_ROM_HAS_OUTPUT_PUTC_FUNC=y # # Boot ROM Behavior # CONFIG_BOOT_ROM_LOG_ALWAYS_ON=y # CONFIG_BOOT_ROM_LOG_ALWAYS_OFF is not set # CONFIG_BOOT_ROM_LOG_ON_GPIO_HIGH is not set # CONFIG_BOOT_ROM_LOG_ON_GPIO_LOW is not set # end of Boot ROM Behavior # # Serial flasher config # # CONFIG_ESPTOOLPY_NO_STUB is not set CONFIG_ESPTOOLPY_FLASHMODE_QIO=y # CONFIG_ESPTOOLPY_FLASHMODE_QOUT is not set # CONFIG_ESPTOOLPY_FLASHMODE_DIO is not set # CONFIG_ESPTOOLPY_FLASHMODE_DOUT is not set CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR=y CONFIG_ESPTOOLPY_FLASHMODE="dio" CONFIG_ESPTOOLPY_FLASHFREQ_80M=y # CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set # CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set CONFIG_ESPTOOLPY_FLASHFREQ_VAL=80 CONFIG_ESPTOOLPY_FLASHFREQ="80m" # CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set CONFIG_ESPTOOLPY_FLASHSIZE_32MB=y # CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set CONFIG_ESPTOOLPY_FLASHSIZE="32MB" # CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set CONFIG_ESPTOOLPY_BEFORE_RESET=y # CONFIG_ESPTOOLPY_BEFORE_NORESET is not set CONFIG_ESPTOOLPY_BEFORE="default_reset" CONFIG_ESPTOOLPY_AFTER_RESET=y # CONFIG_ESPTOOLPY_AFTER_NORESET is not set CONFIG_ESPTOOLPY_AFTER="hard_reset" CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 # end of Serial flasher config # # Partition Table # # CONFIG_PARTITION_TABLE_SINGLE_APP is not set # CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set # CONFIG_PARTITION_TABLE_TWO_OTA is not set # CONFIG_PARTITION_TABLE_TWO_OTA_LARGE is not set CONFIG_PARTITION_TABLE_CUSTOM=y CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" CONFIG_PARTITION_TABLE_OFFSET=0x8000 CONFIG_PARTITION_TABLE_MD5=y # end of Partition Table # # Compiler options # # CONFIG_COMPILER_OPTIMIZATION_DEBUG is not set # CONFIG_COMPILER_OPTIMIZATION_SIZE is not set CONFIG_COMPILER_OPTIMIZATION_PERF=y # CONFIG_COMPILER_OPTIMIZATION_NONE is not set CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE=y # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT is not set # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set CONFIG_COMPILER_ASSERT_NDEBUG_EVALUATE=y # CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB is not set CONFIG_COMPILER_FLOAT_LIB_FROM_RVFPLIB=y CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL=2 # CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT is not set CONFIG_COMPILER_HIDE_PATHS_MACROS=y # CONFIG_COMPILER_CXX_EXCEPTIONS is not set # CONFIG_COMPILER_CXX_RTTI is not set CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y # CONFIG_COMPILER_STACK_CHECK_MODE_NORM is not set # CONFIG_COMPILER_STACK_CHECK_MODE_STRONG is not set # CONFIG_COMPILER_STACK_CHECK_MODE_ALL is not set # CONFIG_COMPILER_NO_MERGE_CONSTANTS is not set # CONFIG_COMPILER_WARN_WRITE_STRINGS is not set # CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS is not set CONFIG_COMPILER_DISABLE_DEFAULT_ERRORS=y # CONFIG_COMPILER_DISABLE_GCC12_WARNINGS is not set # CONFIG_COMPILER_DISABLE_GCC13_WARNINGS is not set # CONFIG_COMPILER_DISABLE_GCC14_WARNINGS is not set # CONFIG_COMPILER_DUMP_RTL_FILES is not set CONFIG_COMPILER_RT_LIB_GCCLIB=y CONFIG_COMPILER_RT_LIB_NAME="gcc" # CONFIG_COMPILER_ORPHAN_SECTIONS_WARNING is not set CONFIG_COMPILER_ORPHAN_SECTIONS_PLACE=y # CONFIG_COMPILER_STATIC_ANALYZER is not set # end of Compiler options # # Component config # # # Application Level Tracing # # CONFIG_APPTRACE_DEST_JTAG is not set CONFIG_APPTRACE_DEST_NONE=y # CONFIG_APPTRACE_DEST_UART1 is not set # CONFIG_APPTRACE_DEST_UART2 is not set CONFIG_APPTRACE_DEST_UART_NONE=y CONFIG_APPTRACE_UART_TASK_PRIO=1 CONFIG_APPTRACE_LOCK_ENABLE=y # end of Application Level Tracing # # Bluetooth # # CONFIG_BT_ENABLED is not set # # Common Options # # CONFIG_BT_BLE_LOG_SPI_OUT_ENABLED is not set # end of Common Options # end of Bluetooth # # Console Library # # CONFIG_CONSOLE_SORTED_HELP is not set # end of Console Library # # Driver Configurations # # # TWAI Configuration # # CONFIG_TWAI_ISR_IN_IRAM is not set # end of TWAI Configuration # # Legacy ADC Driver Configuration # # CONFIG_ADC_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_ADC_SKIP_LEGACY_CONFLICT_CHECK is not set # # Legacy ADC Calibration Configuration # # CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN is not set # end of Legacy ADC Calibration Configuration # end of Legacy ADC Driver Configuration # # Legacy MCPWM Driver Configurations # # CONFIG_MCPWM_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_MCPWM_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy MCPWM Driver Configurations # # Legacy Timer Group Driver Configurations # # CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_GPTIMER_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy Timer Group Driver Configurations # # Legacy RMT Driver Configurations # # CONFIG_RMT_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_RMT_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy RMT Driver Configurations # # Legacy I2S Driver Configurations # # CONFIG_I2S_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_I2S_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy I2S Driver Configurations # # Legacy I2C Driver Configurations # # CONFIG_I2C_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy I2C Driver Configurations # # Legacy PCNT Driver Configurations # # CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_PCNT_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy PCNT Driver Configurations # # Legacy SDM Driver Configurations # # CONFIG_SDM_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_SDM_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy SDM Driver Configurations # # Legacy Temperature Sensor Driver Configurations # # CONFIG_TEMP_SENSOR_SUPPRESS_DEPRECATE_WARN is not set # CONFIG_TEMP_SENSOR_SKIP_LEGACY_CONFLICT_CHECK is not set # end of Legacy Temperature Sensor Driver Configurations # end of Driver Configurations # # eFuse Bit Manager # # CONFIG_EFUSE_CUSTOM_TABLE is not set # CONFIG_EFUSE_VIRTUAL is not set CONFIG_EFUSE_MAX_BLK_LEN=256 # end of eFuse Bit Manager # # ESP-TLS # CONFIG_ESP_TLS_USING_MBEDTLS=y CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y # CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is not set # CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is not set # CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK is not set # CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL is not set # CONFIG_ESP_TLS_PSK_VERIFICATION is not set # CONFIG_ESP_TLS_INSECURE is not set # end of ESP-TLS # # ADC and ADC Calibration # # CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM is not set # CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is not set # CONFIG_ADC_ENABLE_DEBUG_LOG is not set # end of ADC and ADC Calibration # # Wireless Coexistence # # CONFIG_ESP_COEX_GPIO_DEBUG is not set # end of Wireless Coexistence # # Common ESP-related # CONFIG_ESP_ERR_TO_NAME_LOOKUP=y # end of Common ESP-related # # ESP-Driver:Analog Comparator Configurations # # CONFIG_ANA_CMPR_ISR_IRAM_SAFE is not set # CONFIG_ANA_CMPR_CTRL_FUNC_IN_IRAM is not set # CONFIG_ANA_CMPR_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:Analog Comparator Configurations # # ESP-Driver:Camera Controller Configurations # # CONFIG_CAM_CTLR_MIPI_CSI_ISR_CACHE_SAFE is not set # CONFIG_CAM_CTLR_ISP_DVP_ISR_CACHE_SAFE is not set # CONFIG_CAM_CTLR_DVP_CAM_ISR_CACHE_SAFE is not set # end of ESP-Driver:Camera Controller Configurations # # ESP-Driver:GPIO Configurations # # CONFIG_GPIO_CTRL_FUNC_IN_IRAM is not set # end of ESP-Driver:GPIO Configurations # # ESP-Driver:GPTimer Configurations # CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set # CONFIG_GPTIMER_ISR_IRAM_SAFE is not set CONFIG_GPTIMER_OBJ_CACHE_SAFE=y # CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:GPTimer Configurations # # ESP-Driver:I2C Configurations # # CONFIG_I2C_ISR_IRAM_SAFE is not set # CONFIG_I2C_ENABLE_DEBUG_LOG is not set # CONFIG_I2C_ENABLE_SLAVE_DRIVER_VERSION_2 is not set # end of ESP-Driver:I2C Configurations # # ESP-Driver:I2S Configurations # # CONFIG_I2S_ISR_IRAM_SAFE is not set # CONFIG_I2S_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:I2S Configurations # # ESP-Driver:ISP Configurations # # CONFIG_ISP_ISR_IRAM_SAFE is not set # CONFIG_ISP_CTRL_FUNC_IN_IRAM is not set # end of ESP-Driver:ISP Configurations # # ESP-Driver:JPEG-Codec Configurations # # CONFIG_JPEG_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:JPEG-Codec Configurations # # ESP-Driver:LEDC Configurations # # CONFIG_LEDC_CTRL_FUNC_IN_IRAM is not set # end of ESP-Driver:LEDC Configurations # # ESP-Driver:MCPWM Configurations # # CONFIG_MCPWM_ISR_IRAM_SAFE is not set # CONFIG_MCPWM_CTRL_FUNC_IN_IRAM is not set # CONFIG_MCPWM_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:MCPWM Configurations # # ESP-Driver:Parallel IO Configurations # # CONFIG_PARLIO_ENABLE_DEBUG_LOG is not set # CONFIG_PARLIO_ISR_IRAM_SAFE is not set # end of ESP-Driver:Parallel IO Configurations # # ESP-Driver:PCNT Configurations # # CONFIG_PCNT_CTRL_FUNC_IN_IRAM is not set # CONFIG_PCNT_ISR_IRAM_SAFE is not set # CONFIG_PCNT_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:PCNT Configurations # # ESP-Driver:RMT Configurations # # CONFIG_RMT_ISR_IRAM_SAFE is not set # CONFIG_RMT_RECV_FUNC_IN_IRAM is not set # CONFIG_RMT_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:RMT Configurations # # ESP-Driver:Sigma Delta Modulator Configurations # # CONFIG_SDM_CTRL_FUNC_IN_IRAM is not set # CONFIG_SDM_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:Sigma Delta Modulator Configurations # # ESP-Driver:SPI Configurations # # CONFIG_SPI_MASTER_IN_IRAM is not set CONFIG_SPI_MASTER_ISR_IN_IRAM=y # CONFIG_SPI_SLAVE_IN_IRAM is not set CONFIG_SPI_SLAVE_ISR_IN_IRAM=y # end of ESP-Driver:SPI Configurations # # ESP-Driver:Touch Sensor Configurations # # CONFIG_TOUCH_CTRL_FUNC_IN_IRAM is not set # CONFIG_TOUCH_ISR_IRAM_SAFE is not set # CONFIG_TOUCH_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:Touch Sensor Configurations # # ESP-Driver:Temperature Sensor Configurations # # CONFIG_TEMP_SENSOR_ENABLE_DEBUG_LOG is not set # CONFIG_TEMP_SENSOR_ISR_IRAM_SAFE is not set # end of ESP-Driver:Temperature Sensor Configurations # # ESP-Driver:UART Configurations # # CONFIG_UART_ISR_IN_IRAM is not set # end of ESP-Driver:UART Configurations # # ESP-Driver:USB Serial/JTAG Configuration # CONFIG_USJ_ENABLE_USB_SERIAL_JTAG=y # end of ESP-Driver:USB Serial/JTAG Configuration # # Ethernet # CONFIG_ETH_ENABLED=y CONFIG_ETH_USE_ESP32_EMAC=y CONFIG_ETH_PHY_INTERFACE_RMII=y CONFIG_ETH_DMA_BUFFER_SIZE=512 CONFIG_ETH_DMA_RX_BUFFER_NUM=20 CONFIG_ETH_DMA_TX_BUFFER_NUM=10 # CONFIG_ETH_SOFT_FLOW_CONTROL is not set # CONFIG_ETH_IRAM_OPTIMIZATION is not set CONFIG_ETH_USE_SPI_ETHERNET=y # CONFIG_ETH_SPI_ETHERNET_DM9051 is not set # CONFIG_ETH_SPI_ETHERNET_W5500 is not set # CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL is not set # CONFIG_ETH_USE_OPENETH is not set # CONFIG_ETH_TRANSMIT_MUTEX is not set # end of Ethernet # # Event Loop Library # # CONFIG_ESP_EVENT_LOOP_PROFILING is not set CONFIG_ESP_EVENT_POST_FROM_ISR=y CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR=y # end of Event Loop Library # # GDB Stub # CONFIG_ESP_GDBSTUB_ENABLED=y # CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME is not set CONFIG_ESP_GDBSTUB_SUPPORT_TASKS=y CONFIG_ESP_GDBSTUB_MAX_TASKS=32 # end of GDB Stub # # ESP HID # CONFIG_ESPHID_TASK_SIZE_BT=2048 CONFIG_ESPHID_TASK_SIZE_BLE=4096 # end of ESP HID # # ESP HTTP client # CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y # CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH is not set # CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH is not set # CONFIG_ESP_HTTP_CLIENT_ENABLE_CUSTOM_TRANSPORT is not set CONFIG_ESP_HTTP_CLIENT_EVENT_POST_TIMEOUT=2000 # end of ESP HTTP client # # HTTP Server # CONFIG_HTTPD_MAX_REQ_HDR_LEN=512 CONFIG_HTTPD_MAX_URI_LEN=512 CONFIG_HTTPD_ERR_RESP_NO_DELAY=y CONFIG_HTTPD_PURGE_BUF_LEN=32 # CONFIG_HTTPD_LOG_PURGE_DATA is not set # CONFIG_HTTPD_WS_SUPPORT is not set # CONFIG_HTTPD_QUEUE_WORK_BLOCKING is not set CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT=2000 # end of HTTP Server # # ESP HTTPS OTA # # CONFIG_ESP_HTTPS_OTA_DECRYPT_CB is not set # CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP is not set CONFIG_ESP_HTTPS_OTA_EVENT_POST_TIMEOUT=2000 # end of ESP HTTPS OTA # # ESP HTTPS server # # CONFIG_ESP_HTTPS_SERVER_ENABLE is not set CONFIG_ESP_HTTPS_SERVER_EVENT_POST_TIMEOUT=2000 # end of ESP HTTPS server # # Hardware Settings # # # Chip revision # # CONFIG_ESP32P4_REV_MIN_0 is not set CONFIG_ESP32P4_REV_MIN_1=y # CONFIG_ESP32P4_REV_MIN_100 is not set CONFIG_ESP32P4_REV_MIN_FULL=1 CONFIG_ESP_REV_MIN_FULL=1 # # Maximum Supported ESP32-P4 Revision (Rev v1.99) # CONFIG_ESP32P4_REV_MAX_FULL=199 CONFIG_ESP_REV_MAX_FULL=199 CONFIG_ESP_EFUSE_BLOCK_REV_MIN_FULL=0 CONFIG_ESP_EFUSE_BLOCK_REV_MAX_FULL=99 # # Maximum Supported ESP32-P4 eFuse Block Revision (eFuse Block Rev v0.99) # # end of Chip revision # # MAC Config # CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH=y CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES_ONE=y CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES=1 CONFIG_ESP32P4_UNIVERSAL_MAC_ADDRESSES_ONE=y CONFIG_ESP32P4_UNIVERSAL_MAC_ADDRESSES=1 # CONFIG_ESP_MAC_USE_CUSTOM_MAC_AS_BASE_MAC is not set # end of MAC Config # # Sleep Config # CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND=y CONFIG_ESP_SLEEP_PSRAM_LEAKAGE_WORKAROUND=y # CONFIG_ESP_SLEEP_MSPI_NEED_ALL_IO_PU is not set # CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND is not set CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY=0 # CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION is not set # CONFIG_ESP_SLEEP_DEBUG is not set CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS=y # end of Sleep Config # # RTC Clock Config # CONFIG_RTC_CLK_SRC_INT_RC=y # CONFIG_RTC_CLK_SRC_EXT_CRYS is not set CONFIG_RTC_CLK_CAL_CYCLES=1024 CONFIG_RTC_FAST_CLK_SRC_RC_FAST=y # CONFIG_RTC_FAST_CLK_SRC_XTAL is not set # end of RTC Clock Config # # Peripheral Control # CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y # end of Peripheral Control # # ETM Configuration # # CONFIG_ETM_ENABLE_DEBUG_LOG is not set # end of ETM Configuration # # GDMA Configurations # CONFIG_GDMA_CTRL_FUNC_IN_IRAM=y CONFIG_GDMA_ISR_HANDLER_IN_IRAM=y CONFIG_GDMA_OBJ_DRAM_SAFE=y # CONFIG_GDMA_ENABLE_DEBUG_LOG is not set # CONFIG_GDMA_ISR_IRAM_SAFE is not set # end of GDMA Configurations # # DW_GDMA Configurations # # CONFIG_DW_GDMA_ENABLE_DEBUG_LOG is not set # end of DW_GDMA Configurations # # 2D-DMA Configurations # # CONFIG_DMA2D_OPERATION_FUNC_IN_IRAM is not set # CONFIG_DMA2D_ISR_IRAM_SAFE is not set # end of 2D-DMA Configurations # # Main XTAL Config # CONFIG_XTAL_FREQ_40=y CONFIG_XTAL_FREQ=40 # end of Main XTAL Config # # DCDC Regulator Configurations # CONFIG_ESP_SLEEP_KEEP_DCDC_ALWAYS_ON=y CONFIG_ESP_SLEEP_DCM_VSET_VAL_IN_SLEEP=14 # end of DCDC Regulator Configurations # # LDO Regulator Configurations # CONFIG_ESP_LDO_RESERVE_SPI_NOR_FLASH=y CONFIG_ESP_LDO_CHAN_SPI_NOR_FLASH_DOMAIN=1 CONFIG_ESP_LDO_VOLTAGE_SPI_NOR_FLASH_3300_MV=y CONFIG_ESP_LDO_VOLTAGE_SPI_NOR_FLASH_DOMAIN=3300 CONFIG_ESP_LDO_RESERVE_PSRAM=y CONFIG_ESP_LDO_CHAN_PSRAM_DOMAIN=2 CONFIG_ESP_LDO_VOLTAGE_PSRAM_1900_MV=y CONFIG_ESP_LDO_VOLTAGE_PSRAM_DOMAIN=1900 # end of LDO Regulator Configurations CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y # end of Hardware Settings # # ESP-Driver:LCD Controller Configurations # # CONFIG_LCD_ENABLE_DEBUG_LOG is not set # CONFIG_LCD_RGB_ISR_IRAM_SAFE is not set # CONFIG_LCD_RGB_RESTART_IN_VSYNC is not set # CONFIG_LCD_DSI_ISR_IRAM_SAFE is not set # end of ESP-Driver:LCD Controller Configurations # # ESP-MM: Memory Management Configurations # # CONFIG_ESP_MM_CACHE_MSYNC_C2M_CHUNKED_OPS is not set # end of ESP-MM: Memory Management Configurations # # ESP NETIF Adapter # CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL=120 # CONFIG_ESP_NETIF_PROVIDE_CUSTOM_IMPLEMENTATION is not set CONFIG_ESP_NETIF_TCPIP_LWIP=y # CONFIG_ESP_NETIF_LOOPBACK is not set CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y CONFIG_ESP_NETIF_REPORT_DATA_TRAFFIC=y # CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS is not set # CONFIG_ESP_NETIF_L2_TAP is not set # CONFIG_ESP_NETIF_BRIDGE_EN is not set # CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF is not set # end of ESP NETIF Adapter # # Partition API Configuration # # end of Partition API Configuration # # PHY # # end of PHY # # Power Management # # CONFIG_PM_ENABLE is not set # CONFIG_PM_SLP_IRAM_OPT is not set # CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP is not set # end of Power Management # # ESP PSRAM # CONFIG_SPIRAM=y # # PSRAM config # CONFIG_SPIRAM_MODE_HEX=y CONFIG_SPIRAM_SPEED_200M=y # CONFIG_SPIRAM_SPEED_20M is not set CONFIG_SPIRAM_SPEED=200 CONFIG_SPIRAM_FETCH_INSTRUCTIONS=y CONFIG_SPIRAM_RODATA=y CONFIG_SPIRAM_XIP_FROM_PSRAM=y CONFIG_SPIRAM_FLASH_LOAD_TO_PSRAM=y # CONFIG_SPIRAM_ECC_ENABLE is not set CONFIG_SPIRAM_BOOT_INIT=y CONFIG_SPIRAM_PRE_CONFIGURE_MEMORY_PROTECTION=y # CONFIG_SPIRAM_IGNORE_NOTFOUND is not set # CONFIG_SPIRAM_USE_MEMMAP is not set # CONFIG_SPIRAM_USE_CAPS_ALLOC is not set CONFIG_SPIRAM_USE_MALLOC=y CONFIG_SPIRAM_MEMTEST=y CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=16384 # CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP is not set CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL=32768 # CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY is not set # CONFIG_SPIRAM_ALLOW_NOINIT_SEG_EXTERNAL_MEMORY is not set # end of PSRAM config # end of ESP PSRAM # # ESP Ringbuf # # CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH is not set # end of ESP Ringbuf # # ESP Security Specific # # end of ESP Security Specific # # ESP System Settings # CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_360=y CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=360 # # Cache config # # CONFIG_CACHE_L2_CACHE_128KB is not set CONFIG_CACHE_L2_CACHE_256KB=y # CONFIG_CACHE_L2_CACHE_512KB is not set CONFIG_CACHE_L2_CACHE_SIZE=0x40000 # CONFIG_CACHE_L2_CACHE_LINE_64B is not set CONFIG_CACHE_L2_CACHE_LINE_128B=y CONFIG_CACHE_L2_CACHE_LINE_SIZE=128 CONFIG_CACHE_L1_CACHE_LINE_SIZE=64 # end of Cache config # CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT is not set CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y # CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set # CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=0 CONFIG_ESP_SYSTEM_RTC_FAST_MEM_AS_HEAP_DEPCHECK=y CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP=y # CONFIG_ESP_SYSTEM_USE_EH_FRAME is not set # # Memory protection # CONFIG_ESP_SYSTEM_PMP_IDRAM_SPLIT=y # CONFIG_ESP_SYSTEM_PMP_LP_CORE_RESERVE_MEM_EXECUTABLE is not set # end of Memory protection CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=2304 CONFIG_ESP_MAIN_TASK_STACK_SIZE=10240 CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0=y # CONFIG_ESP_MAIN_TASK_AFFINITY_CPU1 is not set # CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY is not set CONFIG_ESP_MAIN_TASK_AFFINITY=0x0 CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE=2048 CONFIG_ESP_CONSOLE_UART_DEFAULT=y # CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG is not set # CONFIG_ESP_CONSOLE_UART_CUSTOM is not set # CONFIG_ESP_CONSOLE_NONE is not set # CONFIG_ESP_CONSOLE_SECONDARY_NONE is not set CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y CONFIG_ESP_CONSOLE_UART=y CONFIG_ESP_CONSOLE_UART_NUM=0 CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0 CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200 CONFIG_ESP_INT_WDT=y CONFIG_ESP_INT_WDT_TIMEOUT_MS=300 CONFIG_ESP_INT_WDT_CHECK_CPU1=y CONFIG_ESP_TASK_WDT_EN=y CONFIG_ESP_TASK_WDT_INIT=y # CONFIG_ESP_TASK_WDT_PANIC is not set CONFIG_ESP_TASK_WDT_TIMEOUT_S=5 CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=y CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1=y # CONFIG_ESP_PANIC_HANDLER_IRAM is not set # CONFIG_ESP_DEBUG_STUBS_ENABLE is not set CONFIG_ESP_DEBUG_OCDAWARE=y CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4=y # # Brownout Detector # CONFIG_ESP_BROWNOUT_DET=y CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7=y # CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set # CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set CONFIG_ESP_BROWNOUT_DET_LVL=7 # end of Brownout Detector CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y CONFIG_ESP_SYSTEM_HW_STACK_GUARD=y CONFIG_ESP_SYSTEM_HW_PC_RECORD=y # end of ESP System Settings # # IPC (Inter-Processor Call) # CONFIG_ESP_IPC_TASK_STACK_SIZE=1024 CONFIG_ESP_IPC_USES_CALLERS_PRIORITY=y CONFIG_ESP_IPC_ISR_ENABLE=y # end of IPC (Inter-Processor Call) # # ESP Timer (High Resolution Timer) # # CONFIG_ESP_TIMER_PROFILING is not set CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER=y CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER=y CONFIG_ESP_TIMER_TASK_STACK_SIZE=3584 CONFIG_ESP_TIMER_INTERRUPT_LEVEL=1 # CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL is not set CONFIG_ESP_TIMER_TASK_AFFINITY=0x0 CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0=y CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0=y # CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is not set CONFIG_ESP_TIMER_IMPL_SYSTIMER=y # end of ESP Timer (High Resolution Timer) # # Wi-Fi # # CONFIG_ESP_HOST_WIFI_ENABLED is not set # end of Wi-Fi # # Core dump # # CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH is not set # CONFIG_ESP_COREDUMP_ENABLE_TO_UART is not set CONFIG_ESP_COREDUMP_ENABLE_TO_NONE=y # end of Core dump # # FAT Filesystem support # CONFIG_FATFS_VOLUME_COUNT=2 # CONFIG_FATFS_LFN_NONE is not set CONFIG_FATFS_LFN_HEAP=y # CONFIG_FATFS_LFN_STACK is not set # CONFIG_FATFS_SECTOR_512 is not set CONFIG_FATFS_SECTOR_4096=y # CONFIG_FATFS_CODEPAGE_DYNAMIC is not set CONFIG_FATFS_CODEPAGE_437=y # CONFIG_FATFS_CODEPAGE_720 is not set # CONFIG_FATFS_CODEPAGE_737 is not set # CONFIG_FATFS_CODEPAGE_771 is not set # CONFIG_FATFS_CODEPAGE_775 is not set # CONFIG_FATFS_CODEPAGE_850 is not set # CONFIG_FATFS_CODEPAGE_852 is not set # CONFIG_FATFS_CODEPAGE_855 is not set # CONFIG_FATFS_CODEPAGE_857 is not set # CONFIG_FATFS_CODEPAGE_860 is not set # CONFIG_FATFS_CODEPAGE_861 is not set # CONFIG_FATFS_CODEPAGE_862 is not set # CONFIG_FATFS_CODEPAGE_863 is not set # CONFIG_FATFS_CODEPAGE_864 is not set # CONFIG_FATFS_CODEPAGE_865 is not set # CONFIG_FATFS_CODEPAGE_866 is not set # CONFIG_FATFS_CODEPAGE_869 is not set # CONFIG_FATFS_CODEPAGE_932 is not set # CONFIG_FATFS_CODEPAGE_936 is not set # CONFIG_FATFS_CODEPAGE_949 is not set # CONFIG_FATFS_CODEPAGE_950 is not set CONFIG_FATFS_CODEPAGE=437 CONFIG_FATFS_MAX_LFN=255 CONFIG_FATFS_API_ENCODING_ANSI_OEM=y # CONFIG_FATFS_API_ENCODING_UTF_8 is not set CONFIG_FATFS_FS_LOCK=0 CONFIG_FATFS_TIMEOUT_MS=10000 CONFIG_FATFS_PER_FILE_CACHE=y CONFIG_FATFS_ALLOC_PREFER_EXTRAM=y # CONFIG_FATFS_USE_FASTSEEK is not set CONFIG_FATFS_USE_STRFUNC_NONE=y # CONFIG_FATFS_USE_STRFUNC_WITHOUT_CRLF_CONV is not set # CONFIG_FATFS_USE_STRFUNC_WITH_CRLF_CONV is not set CONFIG_FATFS_VFS_FSTAT_BLKSIZE=0 # CONFIG_FATFS_IMMEDIATE_FSYNC is not set # CONFIG_FATFS_USE_LABEL is not set CONFIG_FATFS_LINK_LOCK=y # CONFIG_FATFS_USE_DYN_BUFFERS is not set # # File system free space calculation behavior # CONFIG_FATFS_DONT_TRUST_FREE_CLUSTER_CNT=0 CONFIG_FATFS_DONT_TRUST_LAST_ALLOC=0 # end of File system free space calculation behavior # end of FAT Filesystem support # # FreeRTOS # # # Kernel # # CONFIG_FREERTOS_UNICORE is not set CONFIG_FREERTOS_HZ=1000 # CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE is not set # CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL is not set CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY=y CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=1 CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536 # CONFIG_FREERTOS_USE_IDLE_HOOK is not set # CONFIG_FREERTOS_USE_TICK_HOOK is not set CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16 # CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY is not set CONFIG_FREERTOS_USE_TIMERS=y CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME="Tmr Svc" # CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU0 is not set # CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU1 is not set CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY=y CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY=0x7FFFFFFF CONFIG_FREERTOS_TIMER_TASK_PRIORITY=1 CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048 CONFIG_FREERTOS_TIMER_QUEUE_LENGTH=10 CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE=0 CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=1 CONFIG_FREERTOS_USE_TRACE_FACILITY=y CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS=y # CONFIG_FREERTOS_USE_LIST_DATA_INTEGRITY_CHECK_BYTES is not set CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID=y CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS=y CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE_U32=y # CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE_U64 is not set # CONFIG_FREERTOS_USE_APPLICATION_TASK_TAG is not set # end of Kernel # # Port # # CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK is not set CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS=y # CONFIG_FREERTOS_TASK_PRE_DELETION_HOOK is not set # CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP is not set CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER=y CONFIG_FREERTOS_ISR_STACKSIZE=1536 CONFIG_FREERTOS_INTERRUPT_BACKTRACE=y CONFIG_FREERTOS_TICK_SUPPORT_SYSTIMER=y CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1=y # CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL3 is not set CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER=y CONFIG_FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER=y # CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH is not set # CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE is not set # end of Port # # Extra # CONFIG_FREERTOS_TASK_CREATE_ALLOW_EXT_MEM=y # end of Extra CONFIG_FREERTOS_PORT=y CONFIG_FREERTOS_NO_AFFINITY=0x7FFFFFFF CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y CONFIG_FREERTOS_DEBUG_OCDAWARE=y CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT=y CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y CONFIG_FREERTOS_NUMBER_OF_CORES=2 # end of FreeRTOS # # Hardware Abstraction Layer (HAL) and Low Level (LL) # CONFIG_HAL_ASSERTION_EQUALS_SYSTEM=y # CONFIG_HAL_ASSERTION_DISABLE is not set # CONFIG_HAL_ASSERTION_SILENT is not set # CONFIG_HAL_ASSERTION_ENABLE is not set CONFIG_HAL_DEFAULT_ASSERTION_LEVEL=2 CONFIG_HAL_SYSTIMER_USE_ROM_IMPL=y CONFIG_HAL_WDT_USE_ROM_IMPL=y CONFIG_HAL_SPI_MASTER_FUNC_IN_IRAM=y CONFIG_HAL_SPI_SLAVE_FUNC_IN_IRAM=y # end of Hardware Abstraction Layer (HAL) and Low Level (LL) # # Heap memory debugging # CONFIG_HEAP_POISONING_DISABLED=y # CONFIG_HEAP_POISONING_LIGHT is not set # CONFIG_HEAP_POISONING_COMPREHENSIVE is not set CONFIG_HEAP_TRACING_OFF=y # CONFIG_HEAP_TRACING_STANDALONE is not set # CONFIG_HEAP_TRACING_TOHOST is not set # CONFIG_HEAP_USE_HOOKS is not set # CONFIG_HEAP_TASK_TRACKING is not set # CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS is not set # CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH is not set # end of Heap memory debugging # # Log # # # Log Level # # CONFIG_LOG_DEFAULT_LEVEL_NONE is not set # CONFIG_LOG_DEFAULT_LEVEL_ERROR is not set # CONFIG_LOG_DEFAULT_LEVEL_WARN is not set CONFIG_LOG_DEFAULT_LEVEL_INFO=y # CONFIG_LOG_DEFAULT_LEVEL_DEBUG is not set # CONFIG_LOG_DEFAULT_LEVEL_VERBOSE is not set CONFIG_LOG_DEFAULT_LEVEL=3 CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT=y # CONFIG_LOG_MAXIMUM_LEVEL_DEBUG is not set # CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE is not set CONFIG_LOG_MAXIMUM_LEVEL=3 # # Level Settings # # CONFIG_LOG_MASTER_LEVEL is not set CONFIG_LOG_DYNAMIC_LEVEL_CONTROL=y # CONFIG_LOG_TAG_LEVEL_IMPL_NONE is not set # CONFIG_LOG_TAG_LEVEL_IMPL_LINKED_LIST is not set CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_AND_LINKED_LIST=y # CONFIG_LOG_TAG_LEVEL_CACHE_ARRAY is not set CONFIG_LOG_TAG_LEVEL_CACHE_BINARY_MIN_HEAP=y CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_SIZE=31 # end of Level Settings # end of Log Level # # Format # CONFIG_LOG_COLORS=y CONFIG_LOG_TIMESTAMP_SOURCE_RTOS=y # CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM is not set # end of Format # end of Log # # LWIP # CONFIG_LWIP_ENABLE=y CONFIG_LWIP_LOCAL_HOSTNAME="espressif" # CONFIG_LWIP_NETIF_API is not set CONFIG_LWIP_TCPIP_TASK_PRIO=18 # CONFIG_LWIP_TCPIP_CORE_LOCKING is not set # CONFIG_LWIP_CHECK_THREAD_SAFETY is not set CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y # CONFIG_LWIP_L2_TO_L3_COPY is not set # CONFIG_LWIP_IRAM_OPTIMIZATION is not set # CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION is not set CONFIG_LWIP_TIMERS_ONDEMAND=y CONFIG_LWIP_ND6=y # CONFIG_LWIP_FORCE_ROUTER_FORWARDING is not set CONFIG_LWIP_MAX_SOCKETS=10 # CONFIG_LWIP_USE_ONLY_LWIP_SELECT is not set # CONFIG_LWIP_SO_LINGER is not set CONFIG_LWIP_SO_REUSE=y CONFIG_LWIP_SO_REUSE_RXTOALL=y # CONFIG_LWIP_SO_RCVBUF is not set # CONFIG_LWIP_NETBUF_RECVINFO is not set CONFIG_LWIP_IP_DEFAULT_TTL=64 CONFIG_LWIP_IP4_FRAG=y CONFIG_LWIP_IP6_FRAG=y # CONFIG_LWIP_IP4_REASSEMBLY is not set # CONFIG_LWIP_IP6_REASSEMBLY is not set CONFIG_LWIP_IP_REASS_MAX_PBUFS=10 # CONFIG_LWIP_IP_FORWARD is not set # CONFIG_LWIP_STATS is not set CONFIG_LWIP_ESP_GRATUITOUS_ARP=y CONFIG_LWIP_GARP_TMR_INTERVAL=60 CONFIG_LWIP_ESP_MLDV6_REPORT=y CONFIG_LWIP_MLDV6_TMR_INTERVAL=40 CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32 CONFIG_LWIP_DHCP_DOES_ARP_CHECK=y # CONFIG_LWIP_DHCP_DOES_ACD_CHECK is not set # CONFIG_LWIP_DHCP_DOES_NOT_CHECK_OFFERED_IP is not set # CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID is not set CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID=y # CONFIG_LWIP_DHCP_RESTORE_LAST_IP is not set CONFIG_LWIP_DHCP_OPTIONS_LEN=68 CONFIG_LWIP_NUM_NETIF_CLIENT_DATA=0 CONFIG_LWIP_DHCP_COARSE_TIMER_SECS=1 # # DHCP server # CONFIG_LWIP_DHCPS=y CONFIG_LWIP_DHCPS_LEASE_UNIT=60 CONFIG_LWIP_DHCPS_MAX_STATION_NUM=8 CONFIG_LWIP_DHCPS_STATIC_ENTRIES=y CONFIG_LWIP_DHCPS_ADD_DNS=y # end of DHCP server # CONFIG_LWIP_AUTOIP is not set CONFIG_LWIP_IPV4=y CONFIG_LWIP_IPV6=y # CONFIG_LWIP_IPV6_AUTOCONFIG is not set CONFIG_LWIP_IPV6_NUM_ADDRESSES=3 # CONFIG_LWIP_IPV6_FORWARD is not set # CONFIG_LWIP_NETIF_STATUS_CALLBACK is not set CONFIG_LWIP_NETIF_LOOPBACK=y CONFIG_LWIP_LOOPBACK_MAX_PBUFS=8 # # TCP # CONFIG_LWIP_MAX_ACTIVE_TCP=16 CONFIG_LWIP_MAX_LISTENING_TCP=16 CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION=y CONFIG_LWIP_TCP_MAXRTX=12 CONFIG_LWIP_TCP_SYNMAXRTX=12 CONFIG_LWIP_TCP_MSS=1440 CONFIG_LWIP_TCP_TMR_INTERVAL=250 CONFIG_LWIP_TCP_MSL=60000 CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT=20000 CONFIG_LWIP_TCP_SND_BUF_DEFAULT=5760 CONFIG_LWIP_TCP_WND_DEFAULT=5760 CONFIG_LWIP_TCP_RECVMBOX_SIZE=6 CONFIG_LWIP_TCP_ACCEPTMBOX_SIZE=6 CONFIG_LWIP_TCP_QUEUE_OOSEQ=y CONFIG_LWIP_TCP_OOSEQ_TIMEOUT=6 CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS=4 # CONFIG_LWIP_TCP_SACK_OUT is not set CONFIG_LWIP_TCP_OVERSIZE_MSS=y # CONFIG_LWIP_TCP_OVERSIZE_QUARTER_MSS is not set # CONFIG_LWIP_TCP_OVERSIZE_DISABLE is not set CONFIG_LWIP_TCP_RTO_TIME=1500 # end of TCP # # UDP # CONFIG_LWIP_MAX_UDP_PCBS=16 CONFIG_LWIP_UDP_RECVMBOX_SIZE=6 # end of UDP # # Checksums # # CONFIG_LWIP_CHECKSUM_CHECK_IP is not set # CONFIG_LWIP_CHECKSUM_CHECK_UDP is not set CONFIG_LWIP_CHECKSUM_CHECK_ICMP=y # end of Checksums CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=3072 CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0 is not set # CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU1 is not set CONFIG_LWIP_TCPIP_TASK_AFFINITY=0x7FFFFFFF CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE=3 CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS=5 CONFIG_LWIP_IPV6_ND6_NUM_PREFIXES=5 CONFIG_LWIP_IPV6_ND6_NUM_ROUTERS=3 CONFIG_LWIP_IPV6_ND6_NUM_DESTINATIONS=10 # CONFIG_LWIP_PPP_SUPPORT is not set # CONFIG_LWIP_SLIP_SUPPORT is not set # # ICMP # CONFIG_LWIP_ICMP=y # CONFIG_LWIP_MULTICAST_PING is not set # CONFIG_LWIP_BROADCAST_PING is not set # end of ICMP # # LWIP RAW API # CONFIG_LWIP_MAX_RAW_PCBS=16 # end of LWIP RAW API # # SNTP # CONFIG_LWIP_SNTP_MAX_SERVERS=1 # CONFIG_LWIP_DHCP_GET_NTP_SRV is not set CONFIG_LWIP_SNTP_UPDATE_DELAY=3600000 CONFIG_LWIP_SNTP_STARTUP_DELAY=y CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY=5000 # end of SNTP # # DNS # CONFIG_LWIP_DNS_MAX_HOST_IP=1 CONFIG_LWIP_DNS_MAX_SERVERS=3 # CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT is not set # CONFIG_LWIP_DNS_SETSERVER_WITH_NETIF is not set # end of DNS CONFIG_LWIP_BRIDGEIF_MAX_PORTS=7 CONFIG_LWIP_ESP_LWIP_ASSERT=y # # Hooks # # CONFIG_LWIP_HOOK_TCP_ISN_NONE is not set CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT=y # CONFIG_LWIP_HOOK_TCP_ISN_CUSTOM is not set CONFIG_LWIP_HOOK_IP6_ROUTE_NONE=y # CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT is not set # CONFIG_LWIP_HOOK_IP6_ROUTE_CUSTOM is not set CONFIG_LWIP_HOOK_ND6_GET_GW_NONE=y # CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT is not set # CONFIG_LWIP_HOOK_ND6_GET_GW_CUSTOM is not set CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE=y # CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT is not set # CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM is not set CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE=y # CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT is not set # CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not set CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_NONE=y # CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_CUSTOM is not set # CONFIG_LWIP_HOOK_IP6_INPUT_NONE is not set CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT=y # CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM is not set # end of Hooks # CONFIG_LWIP_DEBUG is not set # end of LWIP # # mbedTLS # CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y # CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC is not set # CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC is not set # CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC is not set CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384 CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096 # CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set # CONFIG_MBEDTLS_DEBUG is not set # # mbedTLS v3.x related # # CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 is not set # CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set # CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK is not set # CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y CONFIG_MBEDTLS_PKCS7_C=y # end of mbedTLS v3.x related # # Certificate Bundle # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=y # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN is not set # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE is not set # CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE is not set # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEPRECATED_LIST is not set CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS=200 # end of Certificate Bundle # CONFIG_MBEDTLS_ECP_RESTARTABLE is not set # CONFIG_MBEDTLS_CMAC_C is not set CONFIG_MBEDTLS_HARDWARE_AES=y CONFIG_MBEDTLS_AES_USE_INTERRUPT=y CONFIG_MBEDTLS_AES_INTERRUPT_LEVEL=0 CONFIG_MBEDTLS_HARDWARE_GCM=y CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y CONFIG_MBEDTLS_HARDWARE_MPI=y # CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI is not set CONFIG_MBEDTLS_MPI_USE_INTERRUPT=y CONFIG_MBEDTLS_MPI_INTERRUPT_LEVEL=0 CONFIG_MBEDTLS_HARDWARE_SHA=y CONFIG_MBEDTLS_HARDWARE_ECC=y CONFIG_MBEDTLS_ECC_OTHER_CURVES_SOFT_FALLBACK=y CONFIG_MBEDTLS_ROM_MD5=y # CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set # CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set CONFIG_MBEDTLS_HAVE_TIME=y # CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set # CONFIG_MBEDTLS_HAVE_TIME_DATE is not set CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y CONFIG_MBEDTLS_SHA1_C=y CONFIG_MBEDTLS_SHA512_C=y # CONFIG_MBEDTLS_SHA3_C is not set CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT=y # CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set # CONFIG_MBEDTLS_TLS_CLIENT_ONLY is not set # CONFIG_MBEDTLS_TLS_DISABLED is not set CONFIG_MBEDTLS_TLS_SERVER=y CONFIG_MBEDTLS_TLS_CLIENT=y CONFIG_MBEDTLS_TLS_ENABLED=y # # TLS Key Exchange Methods # # CONFIG_MBEDTLS_PSK_MODES is not set CONFIG_MBEDTLS_KEY_EXCHANGE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA=y # end of TLS Key Exchange Methods CONFIG_MBEDTLS_SSL_RENEGOTIATION=y CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y # CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set # CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set CONFIG_MBEDTLS_SSL_ALPN=y CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS=y CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS=y # # Symmetric Ciphers # CONFIG_MBEDTLS_AES_C=y # CONFIG_MBEDTLS_CAMELLIA_C is not set # CONFIG_MBEDTLS_DES_C is not set # CONFIG_MBEDTLS_BLOWFISH_C is not set # CONFIG_MBEDTLS_XTEA_C is not set CONFIG_MBEDTLS_CCM_C=y CONFIG_MBEDTLS_GCM_C=y # CONFIG_MBEDTLS_NIST_KW_C is not set # end of Symmetric Ciphers # CONFIG_MBEDTLS_RIPEMD160_C is not set # # Certificates # CONFIG_MBEDTLS_PEM_PARSE_C=y CONFIG_MBEDTLS_PEM_WRITE_C=y CONFIG_MBEDTLS_X509_CRL_PARSE_C=y CONFIG_MBEDTLS_X509_CSR_PARSE_C=y # end of Certificates CONFIG_MBEDTLS_ECP_C=y CONFIG_MBEDTLS_PK_PARSE_EC_EXTENDED=y CONFIG_MBEDTLS_PK_PARSE_EC_COMPRESSED=y # CONFIG_MBEDTLS_DHM_C is not set CONFIG_MBEDTLS_ECDH_C=y CONFIG_MBEDTLS_ECDSA_C=y # CONFIG_MBEDTLS_ECJPAKE_C is not set CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y CONFIG_MBEDTLS_ECP_NIST_OPTIM=y # CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM is not set # CONFIG_MBEDTLS_POLY1305_C is not set # CONFIG_MBEDTLS_CHACHA20_C is not set # CONFIG_MBEDTLS_HKDF_C is not set # CONFIG_MBEDTLS_THREADING_C is not set CONFIG_MBEDTLS_ERROR_STRINGS=y CONFIG_MBEDTLS_FS_IO=y # CONFIG_MBEDTLS_ALLOW_WEAK_CERTIFICATE_VERIFICATION is not set # end of mbedTLS # # ESP-MQTT Configurations # CONFIG_MQTT_PROTOCOL_311=y # CONFIG_MQTT_PROTOCOL_5 is not set CONFIG_MQTT_TRANSPORT_SSL=y CONFIG_MQTT_TRANSPORT_WEBSOCKET=y CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y # CONFIG_MQTT_MSG_ID_INCREMENTAL is not set # CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED is not set # CONFIG_MQTT_REPORT_DELETED_MESSAGES is not set # CONFIG_MQTT_USE_CUSTOM_CONFIG is not set # CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set # CONFIG_MQTT_CUSTOM_OUTBOX is not set # end of ESP-MQTT Configurations # # Newlib # CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y # CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set # CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set # CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set # CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y # CONFIG_NEWLIB_NANO_FORMAT is not set CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y # CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set # CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set # CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set # end of Newlib # # NVS # # CONFIG_NVS_ENCRYPTION is not set # CONFIG_NVS_ASSERT_ERROR_CHECK is not set # CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY is not set # CONFIG_NVS_ALLOCATE_CACHE_IN_SPIRAM is not set # end of NVS # # OpenThread # # CONFIG_OPENTHREAD_ENABLED is not set # # OpenThread Spinel # # CONFIG_OPENTHREAD_SPINEL_ONLY is not set # end of OpenThread Spinel # end of OpenThread # # Protocomm # CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_PATCH_VERSION=y # end of Protocomm # # PThreads # CONFIG_PTHREAD_TASK_PRIO_DEFAULT=5 CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 CONFIG_PTHREAD_STACK_MIN=768 CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY=y # CONFIG_PTHREAD_DEFAULT_CORE_0 is not set # CONFIG_PTHREAD_DEFAULT_CORE_1 is not set CONFIG_PTHREAD_TASK_CORE_DEFAULT=-1 CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread" # end of PThreads # # MMU Config # CONFIG_MMU_PAGE_SIZE_64KB=y CONFIG_MMU_PAGE_MODE="64KB" CONFIG_MMU_PAGE_SIZE=0x10000 # end of MMU Config # # Main Flash configuration # # # SPI Flash behavior when brownout # CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC=y CONFIG_SPI_FLASH_BROWNOUT_RESET=y # end of SPI Flash behavior when brownout # # Optional and Experimental Features (READ DOCS FIRST) # # # Features here require specific hardware (READ DOCS FIRST!) # # CONFIG_SPI_FLASH_AUTO_SUSPEND is not set CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50 # CONFIG_SPI_FLASH_FORCE_ENABLE_XMC_C_SUSPEND is not set # CONFIG_SPI_FLASH_FORCE_ENABLE_C6_H2_SUSPEND is not set # end of Optional and Experimental Features (READ DOCS FIRST) # end of Main Flash configuration # # SPI Flash driver # # CONFIG_SPI_FLASH_VERIFY_WRITE is not set # CONFIG_SPI_FLASH_ENABLE_COUNTERS is not set CONFIG_SPI_FLASH_ROM_DRIVER_PATCH=y CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS=y # CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS is not set # CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED is not set # CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE is not set CONFIG_SPI_FLASH_YIELD_DURING_ERASE=y CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS=20 CONFIG_SPI_FLASH_ERASE_YIELD_TICKS=1 CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE=8192 # CONFIG_SPI_FLASH_SIZE_OVERRIDE is not set # CONFIG_SPI_FLASH_CHECK_ERASE_TIMEOUT_DISABLED is not set # CONFIG_SPI_FLASH_OVERRIDE_CHIP_DRIVER_LIST is not set # # Auto-detect flash chips # CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORTED=y # CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP is not set # CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP is not set CONFIG_SPI_FLASH_SUPPORT_GD_CHIP=y # CONFIG_SPI_FLASH_SUPPORT_WINBOND_CHIP is not set # CONFIG_SPI_FLASH_SUPPORT_BOYA_CHIP is not set # CONFIG_SPI_FLASH_SUPPORT_TH_CHIP is not set # end of Auto-detect flash chips CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE=y # end of SPI Flash driver # # SPIFFS Configuration # CONFIG_SPIFFS_MAX_PARTITIONS=3 # # SPIFFS Cache Configuration # CONFIG_SPIFFS_CACHE=y CONFIG_SPIFFS_CACHE_WR=y # CONFIG_SPIFFS_CACHE_STATS is not set # end of SPIFFS Cache Configuration CONFIG_SPIFFS_PAGE_CHECK=y CONFIG_SPIFFS_GC_MAX_RUNS=10 # CONFIG_SPIFFS_GC_STATS is not set CONFIG_SPIFFS_PAGE_SIZE=256 CONFIG_SPIFFS_OBJ_NAME_LEN=32 # CONFIG_SPIFFS_FOLLOW_SYMLINKS is not set CONFIG_SPIFFS_USE_MAGIC=y CONFIG_SPIFFS_USE_MAGIC_LENGTH=y CONFIG_SPIFFS_META_LENGTH=4 CONFIG_SPIFFS_USE_MTIME=y # # Debug Configuration # # CONFIG_SPIFFS_DBG is not set # CONFIG_SPIFFS_API_DBG is not set # CONFIG_SPIFFS_GC_DBG is not set # CONFIG_SPIFFS_CACHE_DBG is not set # CONFIG_SPIFFS_CHECK_DBG is not set # CONFIG_SPIFFS_TEST_VISUALISATION is not set # end of Debug Configuration # end of SPIFFS Configuration # # TCP Transport # # # Websocket # CONFIG_WS_TRANSPORT=y CONFIG_WS_BUFFER_SIZE=1024 # CONFIG_WS_DYNAMIC_BUFFER is not set # end of Websocket # end of TCP Transport # # Ultra Low Power (ULP) Co-processor # # CONFIG_ULP_COPROC_ENABLED is not set # # ULP Debugging Options # # end of ULP Debugging Options # end of Ultra Low Power (ULP) Co-processor # # Unity unit testing library # CONFIG_UNITY_ENABLE_FLOAT=y CONFIG_UNITY_ENABLE_DOUBLE=y # CONFIG_UNITY_ENABLE_64BIT is not set # CONFIG_UNITY_ENABLE_COLOR is not set CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER=y # CONFIG_UNITY_ENABLE_FIXTURE is not set # CONFIG_UNITY_ENABLE_BACKTRACE_ON_FAIL is not set # end of Unity unit testing library # # USB-OTG # CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE=256 CONFIG_USB_HOST_HW_BUFFER_BIAS_BALANCED=y # CONFIG_USB_HOST_HW_BUFFER_BIAS_IN is not set # CONFIG_USB_HOST_HW_BUFFER_BIAS_PERIODIC_OUT is not set # # Hub Driver Configuration # # # Root Port configuration # CONFIG_USB_HOST_DEBOUNCE_DELAY_MS=250 CONFIG_USB_HOST_RESET_HOLD_MS=30 CONFIG_USB_HOST_RESET_RECOVERY_MS=30 CONFIG_USB_HOST_SET_ADDR_RECOVERY_MS=10 # end of Root Port configuration # CONFIG_USB_HOST_HUBS_SUPPORTED is not set # end of Hub Driver Configuration # CONFIG_USB_HOST_ENABLE_ENUM_FILTER_CALLBACK is not set # CONFIG_USB_HOST_DWC_DMA_CAP_MEMORY_IN_PSRAM is not set CONFIG_USB_OTG_SUPPORTED=y # end of USB-OTG # # Virtual file system # CONFIG_VFS_SUPPORT_IO=y CONFIG_VFS_SUPPORT_DIR=y CONFIG_VFS_SUPPORT_SELECT=y CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT=y # CONFIG_VFS_SELECT_IN_RAM is not set CONFIG_VFS_SUPPORT_TERMIOS=y CONFIG_VFS_MAX_COUNT=8 # # Host File System I/O (Semihosting) # CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1 # end of Host File System I/O (Semihosting) CONFIG_VFS_INITIALIZE_DEV_NULL=y # end of Virtual file system # # Wear Levelling # # CONFIG_WL_SECTOR_SIZE_512 is not set CONFIG_WL_SECTOR_SIZE_4096=y CONFIG_WL_SECTOR_SIZE=4096 # end of Wear Levelling # # Wi-Fi Provisioning Manager # CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=16 CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=30 CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y # CONFIG_WIFI_PROV_STA_FAST_SCAN is not set # end of Wi-Fi Provisioning Manager # # Board Support Package # CONFIG_BSP_I2S_NUM=1 # end of Board Support Package # # Audio playback # CONFIG_AUDIO_PLAYER_ENABLE_MP3=y CONFIG_AUDIO_PLAYER_ENABLE_WAV=y CONFIG_AUDIO_PLAYER_LOG_LEVEL=0 # end of Audio playback # # CMake Utilities # # CONFIG_CU_RELINKER_ENABLE is not set # CONFIG_CU_DIAGNOSTICS_COLOR_NEVER is not set CONFIG_CU_DIAGNOSTICS_COLOR_ALWAYS=y # CONFIG_CU_DIAGNOSTICS_COLOR_AUTO is not set # CONFIG_CU_GCC_LTO_ENABLE is not set # CONFIG_CU_GCC_STRING_1BYTE_ALIGN is not set # end of CMake Utilities # # Audio Codec Device Configuration # CONFIG_CODEC_ES8311_SUPPORT=y CONFIG_CODEC_ES7210_SUPPORT=y CONFIG_CODEC_ES7243_SUPPORT=y CONFIG_CODEC_ES7243E_SUPPORT=y CONFIG_CODEC_ES8156_SUPPORT=y CONFIG_CODEC_AW88298_SUPPORT=y CONFIG_CODEC_ES8374_SUPPORT=y CONFIG_CODEC_ES8388_SUPPORT=y CONFIG_CODEC_TAS5805M_SUPPORT=y # CONFIG_CODEC_ZL38063_SUPPORT is not set # end of Audio Codec Device Configuration # # ESP LCD TOUCH # CONFIG_ESP_LCD_TOUCH_MAX_POINTS=5 CONFIG_ESP_LCD_TOUCH_MAX_BUTTONS=1 # end of ESP LCD TOUCH # # ESP LVGL PORT # # CONFIG_LVGL_PORT_ENABLE_PPA is not set # end of ESP LVGL PORT # # LVGL configuration # CONFIG_LV_CONF_SKIP=y # CONFIG_LV_CONF_MINIMAL is not set # # Color Settings # # CONFIG_LV_COLOR_DEPTH_32 is not set # CONFIG_LV_COLOR_DEPTH_24 is not set CONFIG_LV_COLOR_DEPTH_16=y # CONFIG_LV_COLOR_DEPTH_8 is not set # CONFIG_LV_COLOR_DEPTH_1 is not set CONFIG_LV_COLOR_DEPTH=16 # end of Color Settings # # Memory Settings # # CONFIG_LV_USE_BUILTIN_MALLOC is not set CONFIG_LV_USE_CLIB_MALLOC=y # CONFIG_LV_USE_MICROPYTHON_MALLOC is not set # CONFIG_LV_USE_RTTHREAD_MALLOC is not set # CONFIG_LV_USE_CUSTOM_MALLOC is not set # CONFIG_LV_USE_BUILTIN_STRING is not set CONFIG_LV_USE_CLIB_STRING=y # CONFIG_LV_USE_CUSTOM_STRING is not set # CONFIG_LV_USE_BUILTIN_SPRINTF is not set CONFIG_LV_USE_CLIB_SPRINTF=y # CONFIG_LV_USE_CUSTOM_SPRINTF is not set # end of Memory Settings # # HAL Settings # CONFIG_LV_DEF_REFR_PERIOD=15 CONFIG_LV_DPI_DEF=130 # end of HAL Settings # # Operating System (OS) # # CONFIG_LV_OS_NONE is not set # CONFIG_LV_OS_PTHREAD is not set CONFIG_LV_OS_FREERTOS=y # CONFIG_LV_OS_CMSIS_RTOS2 is not set # CONFIG_LV_OS_RTTHREAD is not set # CONFIG_LV_OS_WINDOWS is not set # CONFIG_LV_OS_MQX is not set # CONFIG_LV_OS_CUSTOM is not set CONFIG_LV_USE_FREERTOS_TASK_NOTIFY=y # end of Operating System (OS) # # Rendering Configuration # CONFIG_LV_DRAW_BUF_STRIDE_ALIGN=1 CONFIG_LV_DRAW_BUF_ALIGN=4 CONFIG_LV_DRAW_LAYER_SIMPLE_BUF_SIZE=24576 CONFIG_LV_DRAW_LAYER_MAX_MEMORY=0 CONFIG_LV_DRAW_THREAD_STACK_SIZE=8192 CONFIG_LV_DRAW_THREAD_PRIO=3 CONFIG_LV_USE_DRAW_SW=y CONFIG_LV_DRAW_SW_SUPPORT_RGB565=y CONFIG_LV_DRAW_SW_SUPPORT_RGB565A8=y CONFIG_LV_DRAW_SW_SUPPORT_RGB888=y CONFIG_LV_DRAW_SW_SUPPORT_XRGB8888=y CONFIG_LV_DRAW_SW_SUPPORT_ARGB8888=y CONFIG_LV_DRAW_SW_SUPPORT_L8=y CONFIG_LV_DRAW_SW_SUPPORT_AL88=y CONFIG_LV_DRAW_SW_SUPPORT_A8=y CONFIG_LV_DRAW_SW_SUPPORT_I1=y CONFIG_LV_DRAW_SW_I1_LUM_THRESHOLD=127 CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT=2 # CONFIG_LV_USE_DRAW_ARM2D_SYNC is not set # CONFIG_LV_USE_NATIVE_HELIUM_ASM is not set CONFIG_LV_DRAW_SW_COMPLEX=y # CONFIG_LV_USE_DRAW_SW_COMPLEX_GRADIENTS is not set CONFIG_LV_DRAW_SW_SHADOW_CACHE_SIZE=0 CONFIG_LV_DRAW_SW_CIRCLE_CACHE_SIZE=4 CONFIG_LV_DRAW_SW_ASM_NONE=y # CONFIG_LV_DRAW_SW_ASM_NEON is not set # CONFIG_LV_DRAW_SW_ASM_HELIUM is not set # CONFIG_LV_DRAW_SW_ASM_CUSTOM is not set CONFIG_LV_USE_DRAW_SW_ASM=0 # CONFIG_LV_USE_DRAW_VGLITE is not set # CONFIG_LV_USE_PXP is not set # CONFIG_LV_USE_DRAW_G2D is not set # CONFIG_LV_USE_DRAW_DAVE2D is not set # CONFIG_LV_USE_DRAW_SDL is not set # CONFIG_LV_USE_DRAW_VG_LITE is not set # CONFIG_LV_USE_VECTOR_GRAPHIC is not set # CONFIG_LV_USE_DRAW_DMA2D is not set # end of Rendering Configuration # # Feature Configuration # # # Logging # # CONFIG_LV_USE_LOG is not set # end of Logging # # Asserts # CONFIG_LV_USE_ASSERT_NULL=y CONFIG_LV_USE_ASSERT_MALLOC=y # CONFIG_LV_USE_ASSERT_STYLE is not set # CONFIG_LV_USE_ASSERT_MEM_INTEGRITY is not set # CONFIG_LV_USE_ASSERT_OBJ is not set CONFIG_LV_ASSERT_HANDLER_INCLUDE="assert.h" # end of Asserts # # Debug # # CONFIG_LV_USE_REFR_DEBUG is not set # CONFIG_LV_USE_LAYER_DEBUG is not set # CONFIG_LV_USE_PARALLEL_DRAW_DEBUG is not set # end of Debug # # Others # # CONFIG_LV_ENABLE_GLOBAL_CUSTOM is not set CONFIG_LV_CACHE_DEF_SIZE=0 CONFIG_LV_IMAGE_HEADER_CACHE_DEF_CNT=0 CONFIG_LV_GRADIENT_MAX_STOPS=2 CONFIG_LV_COLOR_MIX_ROUND_OFS=128 # CONFIG_LV_OBJ_STYLE_CACHE is not set # CONFIG_LV_USE_OBJ_ID is not set # CONFIG_LV_USE_OBJ_NAME is not set # CONFIG_LV_USE_OBJ_PROPERTY is not set # end of Others # end of Feature Configuration # # Compiler Settings # # CONFIG_LV_BIG_ENDIAN_SYSTEM is not set CONFIG_LV_ATTRIBUTE_MEM_ALIGN_SIZE=1 CONFIG_LV_ATTRIBUTE_FAST_MEM_USE_IRAM=y # CONFIG_LV_USE_FLOAT is not set # CONFIG_LV_USE_MATRIX is not set # CONFIG_LV_USE_PRIVATE_API is not set # end of Compiler Settings # # Font Usage # # # Enable built-in fonts # # CONFIG_LV_FONT_MONTSERRAT_8 is not set # CONFIG_LV_FONT_MONTSERRAT_10 is not set CONFIG_LV_FONT_MONTSERRAT_12=y CONFIG_LV_FONT_MONTSERRAT_14=y CONFIG_LV_FONT_MONTSERRAT_16=y CONFIG_LV_FONT_MONTSERRAT_18=y CONFIG_LV_FONT_MONTSERRAT_20=y CONFIG_LV_FONT_MONTSERRAT_22=y CONFIG_LV_FONT_MONTSERRAT_24=y CONFIG_LV_FONT_MONTSERRAT_26=y # CONFIG_LV_FONT_MONTSERRAT_28 is not set # CONFIG_LV_FONT_MONTSERRAT_30 is not set # CONFIG_LV_FONT_MONTSERRAT_32 is not set # CONFIG_LV_FONT_MONTSERRAT_34 is not set # CONFIG_LV_FONT_MONTSERRAT_36 is not set # CONFIG_LV_FONT_MONTSERRAT_38 is not set # CONFIG_LV_FONT_MONTSERRAT_40 is not set # CONFIG_LV_FONT_MONTSERRAT_42 is not set # CONFIG_LV_FONT_MONTSERRAT_44 is not set # CONFIG_LV_FONT_MONTSERRAT_46 is not set # CONFIG_LV_FONT_MONTSERRAT_48 is not set # CONFIG_LV_FONT_MONTSERRAT_28_COMPRESSED is not set # CONFIG_LV_FONT_DEJAVU_16_PERSIAN_HEBREW is not set # CONFIG_LV_FONT_SIMSUN_14_CJK is not set # CONFIG_LV_FONT_SIMSUN_16_CJK is not set # CONFIG_LV_FONT_SOURCE_HAN_SANS_SC_14_CJK is not set # CONFIG_LV_FONT_SOURCE_HAN_SANS_SC_16_CJK is not set # CONFIG_LV_FONT_UNSCII_8 is not set # CONFIG_LV_FONT_UNSCII_16 is not set # end of Enable built-in fonts # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_8 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_10 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_12 is not set CONFIG_LV_FONT_DEFAULT_MONTSERRAT_14=y # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_16 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_18 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_20 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_22 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_24 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_26 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_30 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_32 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_34 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_36 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_38 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_40 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_42 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_44 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_46 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_48 is not set # CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28_COMPRESSED is not set # CONFIG_LV_FONT_DEFAULT_DEJAVU_16_PERSIAN_HEBREW is not set # CONFIG_LV_FONT_DEFAULT_SIMSUN_14_CJK is not set # CONFIG_LV_FONT_DEFAULT_SIMSUN_16_CJK is not set # CONFIG_LV_FONT_DEFAULT_SOURCE_HAN_SANS_SC_14_CJK is not set # CONFIG_LV_FONT_DEFAULT_SOURCE_HAN_SANS_SC_16_CJK is not set # CONFIG_LV_FONT_DEFAULT_UNSCII_8 is not set # CONFIG_LV_FONT_DEFAULT_UNSCII_16 is not set # CONFIG_LV_FONT_FMT_TXT_LARGE is not set CONFIG_LV_USE_FONT_COMPRESSED=y CONFIG_LV_USE_FONT_PLACEHOLDER=y # # Enable static fonts # # CONFIG_LV_DEMO_BENCHMARK_ALIGNED_FONTS is not set # end of Enable static fonts # end of Font Usage # # Text Settings # CONFIG_LV_TXT_ENC_UTF8=y # CONFIG_LV_TXT_ENC_ASCII is not set CONFIG_LV_TXT_BREAK_CHARS=" ,.;:-_" CONFIG_LV_TXT_LINE_BREAK_LONG_LEN=0 CONFIG_LV_TXT_COLOR_CMD="#" # CONFIG_LV_USE_BIDI is not set # CONFIG_LV_USE_ARABIC_PERSIAN_CHARS is not set # end of Text Settings # # Widget Usage # CONFIG_LV_WIDGETS_HAS_DEFAULT_VALUE=y CONFIG_LV_USE_ANIMIMG=y CONFIG_LV_USE_ARC=y CONFIG_LV_USE_BAR=y CONFIG_LV_USE_BUTTON=y CONFIG_LV_USE_BUTTONMATRIX=y CONFIG_LV_USE_CALENDAR=y # CONFIG_LV_CALENDAR_WEEK_STARTS_MONDAY is not set # # Days name configuration # CONFIG_LV_MONDAY_STR="Mo" CONFIG_LV_TUESDAY_STR="Tu" CONFIG_LV_WEDNESDAY_STR="We" CONFIG_LV_THURSDAY_STR="Th" CONFIG_LV_FRIDAY_STR="Fr" CONFIG_LV_SATURDAY_STR="Sa" CONFIG_LV_SUNDAY_STR="Su" # end of Days name configuration CONFIG_LV_USE_CALENDAR_HEADER_ARROW=y CONFIG_LV_USE_CALENDAR_HEADER_DROPDOWN=y # CONFIG_LV_USE_CALENDAR_CHINESE is not set CONFIG_LV_USE_CANVAS=y CONFIG_LV_USE_CHART=y CONFIG_LV_USE_CHECKBOX=y CONFIG_LV_USE_DROPDOWN=y CONFIG_LV_USE_IMAGE=y CONFIG_LV_USE_IMAGEBUTTON=y CONFIG_LV_USE_KEYBOARD=y CONFIG_LV_USE_LABEL=y CONFIG_LV_LABEL_TEXT_SELECTION=y CONFIG_LV_LABEL_LONG_TXT_HINT=y CONFIG_LV_LABEL_WAIT_CHAR_COUNT=3 CONFIG_LV_USE_LED=y CONFIG_LV_USE_LINE=y CONFIG_LV_USE_LIST=y CONFIG_LV_USE_MENU=y CONFIG_LV_USE_MSGBOX=y CONFIG_LV_USE_ROLLER=y CONFIG_LV_USE_SCALE=y CONFIG_LV_USE_SLIDER=y CONFIG_LV_USE_SPAN=y CONFIG_LV_SPAN_SNIPPET_STACK_SIZE=64 CONFIG_LV_USE_SPINBOX=y CONFIG_LV_USE_SPINNER=y CONFIG_LV_USE_SWITCH=y CONFIG_LV_USE_TEXTAREA=y CONFIG_LV_TEXTAREA_DEF_PWD_SHOW_TIME=1500 CONFIG_LV_USE_TABLE=y CONFIG_LV_USE_TABVIEW=y CONFIG_LV_USE_TILEVIEW=y CONFIG_LV_USE_WIN=y # end of Widget Usage # # Themes # CONFIG_LV_USE_THEME_DEFAULT=y # CONFIG_LV_THEME_DEFAULT_DARK is not set CONFIG_LV_THEME_DEFAULT_GROW=y CONFIG_LV_THEME_DEFAULT_TRANSITION_TIME=80 CONFIG_LV_USE_THEME_SIMPLE=y # CONFIG_LV_USE_THEME_MONO is not set # end of Themes # # Layouts # CONFIG_LV_USE_FLEX=y CONFIG_LV_USE_GRID=y # end of Layouts # # 3rd Party Libraries # CONFIG_LV_FS_DEFAULT_DRIVER_LETTER=0 # CONFIG_LV_USE_FS_STDIO is not set # CONFIG_LV_USE_FS_POSIX is not set # CONFIG_LV_USE_FS_WIN32 is not set # CONFIG_LV_USE_FS_FATFS is not set # CONFIG_LV_USE_FS_MEMFS is not set # CONFIG_LV_USE_FS_LITTLEFS is not set # CONFIG_LV_USE_FS_ARDUINO_ESP_LITTLEFS is not set # CONFIG_LV_USE_FS_ARDUINO_SD is not set # CONFIG_LV_USE_FS_UEFI is not set # CONFIG_LV_USE_LODEPNG is not set # CONFIG_LV_USE_LIBPNG is not set # CONFIG_LV_USE_BMP is not set # CONFIG_LV_USE_TJPGD is not set # CONFIG_LV_USE_LIBJPEG_TURBO is not set # CONFIG_LV_USE_GIF is not set # CONFIG_LV_BIN_DECODER_RAM_LOAD is not set # CONFIG_LV_USE_RLE is not set # CONFIG_LV_USE_QRCODE is not set # CONFIG_LV_USE_BARCODE is not set # CONFIG_LV_USE_FREETYPE is not set # CONFIG_LV_USE_TINY_TTF is not set # CONFIG_LV_USE_RLOTTIE is not set # CONFIG_LV_USE_THORVG is not set # CONFIG_LV_USE_LZ4 is not set # CONFIG_LV_USE_FFMPEG is not set # end of 3rd Party Libraries # # Others # # CONFIG_LV_USE_SNAPSHOT is not set CONFIG_LV_USE_SYSMON=y CONFIG_LV_USE_PERF_MONITOR=y # CONFIG_LV_PERF_MONITOR_ALIGN_TOP_LEFT is not set # CONFIG_LV_PERF_MONITOR_ALIGN_TOP_MID is not set # CONFIG_LV_PERF_MONITOR_ALIGN_TOP_RIGHT is not set # CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_LEFT is not set # CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_MID is not set CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_RIGHT=y # CONFIG_LV_PERF_MONITOR_ALIGN_LEFT_MID is not set # CONFIG_LV_PERF_MONITOR_ALIGN_RIGHT_MID is not set # CONFIG_LV_PERF_MONITOR_ALIGN_CENTER is not set # CONFIG_LV_USE_PERF_MONITOR_LOG_MODE is not set # CONFIG_LV_USE_PROFILER is not set # CONFIG_LV_USE_MONKEY is not set # CONFIG_LV_USE_GRIDNAV is not set # CONFIG_LV_USE_FRAGMENT is not set CONFIG_LV_USE_IMGFONT=y CONFIG_LV_USE_OBSERVER=y # CONFIG_LV_USE_IME_PINYIN is not set # CONFIG_LV_USE_FILE_EXPLORER is not set # CONFIG_LV_USE_FONT_MANAGER is not set # CONFIG_LV_USE_TEST is not set # CONFIG_LV_USE_XML is not set # CONFIG_LV_USE_COLOR_FILTER is not set CONFIG_LVGL_VERSION_MAJOR=9 CONFIG_LVGL_VERSION_MINOR=3 CONFIG_LVGL_VERSION_PATCH=0 # end of Others # # Devices # # CONFIG_LV_USE_SDL is not set # CONFIG_LV_USE_X11 is not set # CONFIG_LV_USE_WAYLAND is not set # CONFIG_LV_USE_LINUX_FBDEV is not set # CONFIG_LV_USE_NUTTX is not set # CONFIG_LV_USE_LINUX_DRM is not set # CONFIG_LV_USE_TFT_ESPI is not set # CONFIG_LV_USE_EVDEV is not set # CONFIG_LV_USE_LIBINPUT is not set # CONFIG_LV_USE_ST7735 is not set # CONFIG_LV_USE_ST7789 is not set # CONFIG_LV_USE_ST7796 is not set # CONFIG_LV_USE_ILI9341 is not set # CONFIG_LV_USE_GENERIC_MIPI is not set # CONFIG_LV_USE_RENESAS_GLCDC is not set # CONFIG_LV_USE_ST_LTDC is not set # CONFIG_LV_USE_FT81X is not set # CONFIG_LV_USE_UEFI is not set # CONFIG_LV_USE_OPENGLES is not set # CONFIG_LV_USE_QNX is not set # end of Devices # # Examples # CONFIG_LV_BUILD_EXAMPLES=y # end of Examples # # Demos # CONFIG_LV_BUILD_DEMOS=y CONFIG_LV_USE_DEMO_WIDGETS=y # CONFIG_LV_USE_DEMO_KEYPAD_AND_ENCODER is not set CONFIG_LV_USE_DEMO_BENCHMARK=y CONFIG_LV_USE_DEMO_RENDER=y CONFIG_LV_USE_DEMO_SCROLL=y CONFIG_LV_USE_DEMO_STRESS=y CONFIG_LV_USE_DEMO_TRANSFORM=y CONFIG_LV_USE_DEMO_MUSIC=y # CONFIG_LV_DEMO_MUSIC_SQUARE is not set # CONFIG_LV_DEMO_MUSIC_LANDSCAPE is not set # CONFIG_LV_DEMO_MUSIC_ROUND is not set # CONFIG_LV_DEMO_MUSIC_LARGE is not set CONFIG_LV_DEMO_MUSIC_AUTO_PLAY=y CONFIG_LV_USE_DEMO_FLEX_LAYOUT=y CONFIG_LV_USE_DEMO_MULTILANG=y # CONFIG_LV_USE_DEMO_SMARTWATCH is not set # CONFIG_LV_USE_DEMO_EBIKE is not set # CONFIG_LV_USE_DEMO_HIGH_RES is not set # end of Demos # end of LVGL configuration # # Board Support Package(ESP32-P4) # CONFIG_BSP_ERROR_CHECK=y # # I2C # CONFIG_BSP_I2C_NUM=1 CONFIG_BSP_I2C_FAST_MODE=y CONFIG_BSP_I2C_CLK_SPEED_HZ=400000 # end of I2C # # I2S # # end of I2S # # uSD card - Virtual File System # # CONFIG_BSP_SD_FORMAT_ON_MOUNT_FAIL is not set CONFIG_BSP_SD_MOUNT_POINT="/sdcard" # end of uSD card - Virtual File System # # SPIFFS - Virtual File System # # CONFIG_BSP_SPIFFS_FORMAT_ON_MOUNT_FAIL is not set CONFIG_BSP_SPIFFS_MOUNT_POINT="/spiffs" CONFIG_BSP_SPIFFS_PARTITION_LABEL="storage" CONFIG_BSP_SPIFFS_MAX_FILES=5 # end of SPIFFS - Virtual File System # # Display # CONFIG_BSP_LCD_DPI_BUFFER_NUMS=1 CONFIG_BSP_DISPLAY_BRIGHTNESS_LEDC_CH=1 CONFIG_BSP_LCD_COLOR_FORMAT_RGB565=y # CONFIG_BSP_LCD_COLOR_FORMAT_RGB888 is not set # CONFIG_BSP_LCD_TYPE_800_800_3_4_INCH is not set CONFIG_BSP_LCD_TYPE_720_720_4_INCH=y # end of Display # end of Board Support Package(ESP32-P4) # end of Component config CONFIG_IDF_EXPERIMENTAL_FEATURES=y # Deprecated options for backward compatibility # CONFIG_APP_BUILD_TYPE_ELF_RAM is not set # CONFIG_NO_BLOBS is not set # CONFIG_LOG_BOOTLOADER_LEVEL_NONE is not set # CONFIG_LOG_BOOTLOADER_LEVEL_ERROR is not set # CONFIG_LOG_BOOTLOADER_LEVEL_WARN is not set CONFIG_LOG_BOOTLOADER_LEVEL_INFO=y # CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG is not set # CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE is not set CONFIG_LOG_BOOTLOADER_LEVEL=3 # CONFIG_SPI_FLASH_32BIT_ADDR_ENABLE is not set # CONFIG_SPI_FLASH_QUAD_32BIT_ADDR_ENABLE is not set # CONFIG_APP_ROLLBACK_ENABLE is not set # CONFIG_FLASH_ENCRYPTION_ENABLED is not set CONFIG_FLASHMODE_QIO=y # CONFIG_FLASHMODE_QOUT is not set # CONFIG_FLASHMODE_DIO is not set # CONFIG_FLASHMODE_DOUT is not set CONFIG_MONITOR_BAUD=115200 # CONFIG_OPTIMIZATION_LEVEL_DEBUG is not set # CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG is not set # CONFIG_COMPILER_OPTIMIZATION_DEFAULT is not set # CONFIG_OPTIMIZATION_LEVEL_RELEASE is not set # CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE is not set CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED=y # CONFIG_OPTIMIZATION_ASSERTIONS_SILENT is not set # CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED is not set CONFIG_OPTIMIZATION_ASSERTION_LEVEL=2 # CONFIG_CXX_EXCEPTIONS is not set CONFIG_STACK_CHECK_NONE=y # CONFIG_STACK_CHECK_NORM is not set # CONFIG_STACK_CHECK_STRONG is not set # CONFIG_STACK_CHECK_ALL is not set # CONFIG_WARN_WRITE_STRINGS is not set # CONFIG_ESP32_APPTRACE_DEST_TRAX is not set CONFIG_ESP32_APPTRACE_DEST_NONE=y CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y # CONFIG_CAM_CTLR_MIPI_CSI_ISR_IRAM_SAFE is not set # CONFIG_CAM_CTLR_ISP_DVP_ISR_IRAM_SAFE is not set # CONFIG_CAM_CTLR_DVP_CAM_ISR_IRAM_SAFE is not set # CONFIG_MCPWM_ISR_IN_IRAM is not set # CONFIG_EVENT_LOOP_PROFILING is not set CONFIG_POST_EVENTS_FROM_ISR=y CONFIG_POST_EVENTS_FROM_IRAM_ISR=y CONFIG_GDBSTUB_SUPPORT_TASKS=y CONFIG_GDBSTUB_MAX_TASKS=32 # CONFIG_OTA_ALLOW_HTTP is not set CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304 CONFIG_MAIN_TASK_STACK_SIZE=10240 CONFIG_CONSOLE_UART_DEFAULT=y # CONFIG_CONSOLE_UART_CUSTOM is not set # CONFIG_CONSOLE_UART_NONE is not set # CONFIG_ESP_CONSOLE_UART_NONE is not set CONFIG_CONSOLE_UART=y CONFIG_CONSOLE_UART_NUM=0 CONFIG_CONSOLE_UART_BAUDRATE=115200 CONFIG_INT_WDT=y CONFIG_INT_WDT_TIMEOUT_MS=300 CONFIG_INT_WDT_CHECK_CPU1=y CONFIG_TASK_WDT=y CONFIG_ESP_TASK_WDT=y # CONFIG_TASK_WDT_PANIC is not set CONFIG_TASK_WDT_TIMEOUT_S=5 CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0=y CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1=y # CONFIG_ESP32_DEBUG_STUBS_ENABLE is not set CONFIG_BROWNOUT_DET=y CONFIG_BROWNOUT_DET_LVL_SEL_7=y # CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set # CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set CONFIG_BROWNOUT_DET_LVL=7 CONFIG_IPC_TASK_STACK_SIZE=1024 CONFIG_TIMER_TASK_STACK_SIZE=3584 # CONFIG_ESP32_ENABLE_COREDUMP_TO_FLASH is not set # CONFIG_ESP32_ENABLE_COREDUMP_TO_UART is not set CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE=y CONFIG_TIMER_TASK_PRIORITY=1 CONFIG_TIMER_TASK_STACK_DEPTH=2048 CONFIG_TIMER_QUEUE_LENGTH=10 # CONFIG_ENABLE_STATIC_TASK_CLEAN_UP_HOOK is not set CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY=y # CONFIG_HAL_ASSERTION_SILIENT is not set # CONFIG_L2_TO_L3_COPY is not set CONFIG_ESP_GRATUITOUS_ARP=y CONFIG_GARP_TMR_INTERVAL=60 CONFIG_TCPIP_RECVMBOX_SIZE=32 CONFIG_TCP_MAXRTX=12 CONFIG_TCP_SYNMAXRTX=12 CONFIG_TCP_MSS=1440 CONFIG_TCP_MSL=60000 CONFIG_TCP_SND_BUF_DEFAULT=5760 CONFIG_TCP_WND_DEFAULT=5760 CONFIG_TCP_RECVMBOX_SIZE=6 CONFIG_TCP_QUEUE_OOSEQ=y CONFIG_TCP_OVERSIZE_MSS=y # CONFIG_TCP_OVERSIZE_QUARTER_MSS is not set # CONFIG_TCP_OVERSIZE_DISABLE is not set CONFIG_UDP_RECVMBOX_SIZE=6 CONFIG_TCPIP_TASK_STACK_SIZE=3072 CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_TCPIP_TASK_AFFINITY_CPU0 is not set # CONFIG_TCPIP_TASK_AFFINITY_CPU1 is not set CONFIG_TCPIP_TASK_AFFINITY=0x7FFFFFFF # CONFIG_PPP_SUPPORT is not set CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5 CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 CONFIG_ESP32_PTHREAD_STACK_MIN=768 CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY=y # CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0 is not set # CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1 is not set CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT=-1 CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT="pthread" CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS=y # CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS is not set # CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED is not set CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT=y CONFIG_SUPPORT_TERMIOS=y CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS=1 # End of deprecated options
84,971
sdkconfig
en
unknown
unknown
{}
0
{}
0015/map_tiles_projects
waveshare_esp32_p4_wifi6_touch_lcd_xc/README.md
# Simple Map Test - ESP32 Map Display Example This project demonstrates how to use the **0015__map_tiles** component to create an interactive map display on ESP32 devices with LVGL 9.x. It provides a complete example of GPS-based map navigation with touch scrolling, zoom controls, and real-time coordinate updates. ## Features - **Interactive Map Display**: Touch-scrollable map with smooth tile loading - **Real-time GPS Coordinates**: Automatically updates latitude/longitude as you scroll - **Zoom Control**: Adjustable zoom levels (10-19) with dynamic tile reloading - **GPS Input Panel**: Manual coordinate entry with on-screen keyboard - **Smart Tile Loading**: Preserves old tiles during updates for smooth transitions - **Multiple Tile Types**: Support for different map styles (street, satellite, etc.) - **Touch-optimized UI**: Designed for touchscreen interaction ## Hardware Requirements - ESP32-S3 with at least 8MB PSRAM (recommended) - Display with LVGL 9.x support - Touch panel support - SD card for map tile storage - Minimum 4MB flash memory ## Dependencies - **ESP-IDF 5.0+**: ESP32 development framework - **LVGL 9.3+**: Graphics library - **0015__map_tiles**: Map tiles component (included in managed_components) - **SD card support**: For tile storage (FAT filesystem) ## Map Tiles Format The map tiles should be stored on SD card in the following format: - **Format**: RGB565 binary files - **Size**: 256x256 pixels per tile - **Structure**: `/sdcard/tiles1/zoom/x/y.bin` - **Zoom levels**: 10-19 (configurable) Example directory structure: ``` /sdcard/ ├── tiles1/ │ ├── 15/ │ │ ├── 10485/ │ │ │ ├── 12733.bin │ │ │ ├── 12734.bin │ │ │ └── ... │ │ └── ... │ ├── 16/ │ └── ... ``` ## Installation 1. **Clone or download this project** 2. **Set up ESP-IDF environment**: ```bash # Install ESP-IDF 5.0 or later # Set IDF_PATH environment variable ``` 3. **Configure the project**: ```bash cd simple_map_test idf.py menuconfig ``` - Configure PSRAM settings - Set display resolution and interface - Configure SD card pins 4. **Build and flash**: ```bash idf.py build idf.py flash monitor ``` ## Usage ### Basic Operation 1. **Power on**: The map initializes and displays a default location 2. **Scroll**: Touch and drag to pan around the map 3. **View coordinates**: Current GPS coordinates are shown in the input panel 4. **Zoom**: Use the slider to select zoom level, then press "Update Map" 5. **Go to location**: Enter coordinates manually and press "Update Map" ### Map Controls - **Touch scrolling**: Drag to move around the map - **GPS coordinates**: Real-time updates as you scroll - **Zoom slider**: Select zoom level (10-19) - **Update button**: Apply coordinate/zoom changes - **Keyboard**: Appears when editing coordinates ### Key Features #### Real-time GPS Updates ```cpp // GPS coordinates update automatically as you scroll void SimpleMap::update_current_gps_from_map_center(); ``` #### Smooth Tile Loading - Old tiles remain visible during updates - Loading indicators show progress - Automatic tile caching and management #### Touch-optimized Interface - Debounced scroll events for smooth performance - Responsive coordinate updates - User-friendly input validation ## Code Structure ### Main Components - **`SimpleMap` class**: Main map interface and logic - **`map_tiles` component**: Low-level tile management - **Input panel**: GPS coordinate entry and zoom control - **Event handlers**: Touch, scroll, and button events ### Key Functions ```cpp // Initialize the map system bool SimpleMap::init(lv_obj_t* parent_screen); // Display map at specific location void SimpleMap::show_location(double lat, double lon, int zoom); // Handle user interactions void SimpleMap::map_scroll_event_cb(lv_event_t *e); void SimpleMap::update_button_event_cb(lv_event_t *e); // GPS coordinate management void SimpleMap::update_current_gps_from_map_center(); void SimpleMap::get_current_location(double* lat, double* lon); ``` ### Configuration The map system is configured in `SimpleMap::init()`: ```cpp map_tiles_config_t config = { .base_path = "/sdcard", // SD card mount point .tile_folders = {"tiles1"}, // Tile directory names .tile_type_count = 1, // Number of tile types .grid_cols = 5, // Tile grid width .grid_rows = 5, // Tile grid height .default_zoom = 18, // Initial zoom level .use_spiram = true, // Use PSRAM for tiles .default_tile_type = 0 // Default tile type }; ``` ## Performance Optimization ### Memory Management - Uses PSRAM for tile storage when available - Efficient tile caching and cleanup - Minimal memory fragmentation ### Rendering Optimization - Preserves old tiles during updates - Debounced scroll events (50ms for GPS updates) - Optimized LVGL object management ### Touch Response - Smooth scrolling with momentum disabled - Real-time coordinate feedback - Responsive zoom controls ## API Reference ### Public Methods ```cpp class SimpleMap { public: // Core functionality static bool init(lv_obj_t* parent_screen); static void show_location(double lat, double lon, int zoom = 18); static void update_location(double lat, double lon); static void cleanup(); // Tile management static bool set_tile_type(int tile_type); static int get_tile_type(); static int get_tile_type_count(); // Coordinate access static void get_current_location(double* lat, double* lon); static int get_current_zoom(); // Map positioning static void center_map_on_gps(); }; ``` ### Configuration Options - **Grid size**: 5x5 to 9x9 tiles (5x5 recommended) - **Zoom range**: 10-19 (standard map zoom levels) - **Tile types**: Up to 8 different tile sets - **Memory**: PSRAM or regular RAM for tile storage ## Troubleshooting ### Common Issues 1. **Map not displaying**: - Check SD card mount and tile directory structure - Verify tile format (RGB565, 256x256 pixels) - Ensure sufficient PSRAM/memory 2. **Slow performance**: - Enable PSRAM in menuconfig - Reduce grid size if memory limited - Check SD card speed class 3. **Touch not working**: - Verify touch panel configuration - Check LVGL input device setup - Ensure proper touch calibration 4. **Coordinates incorrect**: - Verify tile coordinate system matches your map data - Check zoom level calculations - Ensure proper GPS coordinate conversion ### Debug Output Enable debug output to troubleshoot issues: ```cpp // Key debug messages "SimpleMap: Initialized with grid size %dx%d" "SimpleMap: Loading %dx%d grid at position (%d,%d)" "SimpleMap: Updated GPS from map center: %.6f, %.6f" "SimpleMap: Zoom changed from %d to %d" ``` ## Example Integration ### Basic Usage ```cpp #include "simple_map.hpp" void app_main() { // Initialize LVGL and display lv_init(); // Create main screen lv_obj_t* screen = lv_screen_active(); // Initialize map if (SimpleMap::init(screen)) { // Show initial location (San Francisco) SimpleMap::show_location(37.7749, -122.4194, 15); } // LVGL task loop while (1) { lv_task_handler(); vTaskDelay(pdMS_TO_TICKS(10)); } } ``` ### Advanced Features ```cpp // Change tile type (e.g., satellite view) SimpleMap::set_tile_type(1); // Get current position double lat, lon; SimpleMap::get_current_location(&lat, &lon); printf("Current position: %.6f, %.6f\n", lat, lon); // Update to new location SimpleMap::update_location(40.7128, -74.0060); // New York ``` ## License This project is provided as an example for the 0015__map_tiles component. Check individual component licenses for specific terms. ## Contributing This is an example project demonstrating the 0015__map_tiles component. For improvements or bug fixes, please contribute to the main component repository. ## Acknowledgments - **LVGL Team**: For the excellent graphics library - **Espressif**: For the ESP-IDF framework - **Map tile providers**: For map data (ensure proper attribution) ## Support For questions and support: 1. Check the troubleshooting section above 2. Review the 0015__map_tiles component documentation 3. Post issues with full debug output and hardware configuration
8,442
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.00142146, "qsc_doc_frac_words_redpajama_stop": 0.09608091, "qsc_doc_num_sentences": 56.0, "qsc_doc_num_words": 1143, "qsc_doc_num_chars": 8442.0, "qsc_doc_num_lines": 304.0, "qsc_doc_mean_word_length": 5.12860892, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.00986842, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.34295713, "qsc_doc_entropy_unigram": 5.4643268, "qsc_doc_frac_words_all_caps": 0.03539823, "qsc_doc_frac_lines_dupe_lines": 0.12554113, "qsc_doc_frac_chars_dupe_lines": 0.02692405, "qsc_doc_frac_chars_top_2grams": 0.01364722, "qsc_doc_frac_chars_top_3grams": 0.0174002, "qsc_doc_frac_chars_top_4grams": 0.01961788, "qsc_doc_frac_chars_dupe_5grams": 0.09348345, "qsc_doc_frac_chars_dupe_6grams": 0.06687137, "qsc_doc_frac_chars_dupe_7grams": 0.04742409, "qsc_doc_frac_chars_dupe_8grams": 0.02695326, "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": 22.06830601, "qsc_doc_frac_chars_hyperlink_html_tag": 0.0, "qsc_doc_frac_chars_alphabet": 0.82799005, "qsc_doc_frac_chars_digital": 0.02386181, "qsc_doc_frac_chars_whitespace": 0.19083156, "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/map_tiles_projects
waveshare_esp32_p4_wifi6_touch_lcd_xc/sdkconfig.defaults
# This file was generated using idf.py save-defconfig. It can be edited manually. # Espressif IoT Development Framework (ESP-IDF) 5.4.0 Project Minimal Configuration # CONFIG_IDF_TARGET="esp32p4" CONFIG_ESPTOOLPY_FLASHMODE_QIO=y CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y CONFIG_PARTITION_TABLE_CUSTOM=y CONFIG_COMPILER_OPTIMIZATION_PERF=y CONFIG_SPIRAM=y CONFIG_SPIRAM_SPEED_200M=y CONFIG_SPIRAM_XIP_FROM_PSRAM=y CONFIG_CACHE_L2_CACHE_256KB=y CONFIG_CACHE_L2_CACHE_LINE_128B=y CONFIG_ESP_MAIN_TASK_STACK_SIZE=10240 CONFIG_FREERTOS_HZ=1000 CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID=y CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS=y CONFIG_LV_USE_CLIB_MALLOC=y CONFIG_LV_USE_CLIB_STRING=y CONFIG_LV_USE_CLIB_SPRINTF=y CONFIG_LV_DEF_REFR_PERIOD=15 CONFIG_LV_OS_FREERTOS=y CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT=2 CONFIG_LV_ATTRIBUTE_FAST_MEM_USE_IRAM=y CONFIG_LV_FONT_MONTSERRAT_12=y CONFIG_LV_FONT_MONTSERRAT_16=y CONFIG_LV_FONT_MONTSERRAT_18=y CONFIG_LV_FONT_MONTSERRAT_20=y CONFIG_LV_FONT_MONTSERRAT_22=y CONFIG_LV_FONT_MONTSERRAT_24=y CONFIG_LV_FONT_MONTSERRAT_26=y CONFIG_LV_USE_FONT_COMPRESSED=y CONFIG_LV_TXT_BREAK_CHARS=" ,.;:-_" CONFIG_LV_USE_SYSMON=y CONFIG_LV_USE_PERF_MONITOR=y CONFIG_LV_USE_IMGFONT=y CONFIG_LV_USE_DEMO_WIDGETS=y CONFIG_LV_USE_DEMO_BENCHMARK=y CONFIG_LV_USE_DEMO_RENDER=y CONFIG_LV_USE_DEMO_SCROLL=y CONFIG_LV_USE_DEMO_STRESS=y CONFIG_LV_USE_DEMO_TRANSFORM=y CONFIG_LV_USE_DEMO_MUSIC=y CONFIG_LV_DEMO_MUSIC_AUTO_PLAY=y CONFIG_LV_USE_DEMO_FLEX_LAYOUT=y CONFIG_LV_USE_DEMO_MULTILANG=y CONFIG_IDF_EXPERIMENTAL_FEATURES=y CONFIG_SPI_FLASH_SUPPORT_GD_CHIP=y CONFIG_ESPTOOLPY_FLASHSIZE_32MB=y CONFIG_ESPTOOLPY_FLASHSIZE="32MB"
1,625
sdkconfig
defaults
en
unknown
unknown
{}
0
{}
0015/map_tiles_projects
waveshare_esp32_s3_touch_amoled_1_75/main/main.cpp
#include "nvs_flash.h" #include "esp_log.h" #include "esp_err.h" #include "esp_check.h" #include "lvgl.h" #include "bsp/esp-bsp.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)); } esp_io_expander_handle_t expander = bsp_io_expander_init(); if (expander == NULL) { printf("Failed to initialize IO expander\n"); return; } esp_io_expander_set_dir(expander, IO_EXPANDER_PIN_NUM_7, IO_EXPANDER_OUTPUT); esp_io_expander_set_level(expander, IO_EXPANDER_PIN_NUM_7, 0); vTaskDelay(pdMS_TO_TICKS(1000)); esp_io_expander_set_level(expander, IO_EXPANDER_PIN_NUM_7, 1); vTaskDelay(pdMS_TO_TICKS(500)); lv_disp_t *disp = bsp_display_start(); bsp_display_backlight_on(); 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,469
main
cpp
en
cpp
code
{"qsc_code_num_words": 220, "qsc_code_num_chars": 1469.0, "qsc_code_mean_word_length": 4.13636364, "qsc_code_frac_words_unique": 0.39090909, "qsc_code_frac_chars_top_2grams": 0.10989011, "qsc_code_frac_chars_top_3grams": 0.05714286, "qsc_code_frac_chars_top_4grams": 0.05274725, "qsc_code_frac_chars_dupe_5grams": 0.12857143, "qsc_code_frac_chars_dupe_6grams": 0.12857143, "qsc_code_frac_chars_dupe_7grams": 0.1010989, "qsc_code_frac_chars_dupe_8grams": 0.1010989, "qsc_code_frac_chars_dupe_9grams": 0.1010989, "qsc_code_frac_chars_dupe_10grams": 0.1010989, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02618243, "qsc_code_frac_chars_whitespace": 0.19400953, "qsc_code_size_file_byte": 1469.0, "qsc_code_num_lines": 53.0, "qsc_code_num_chars_line_max": 84.0, "qsc_code_num_chars_line_mean": 27.71698113, "qsc_code_frac_chars_alphabet": 0.74239865, "qsc_code_frac_chars_comments": 0.04765146, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.04878049, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.12142857, "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.17073171, "qsc_codecpp_frac_lines_func_ratio": 0.02439024, "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.24390244, "qsc_codecpp_frac_lines_print": 0.07317073}
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}
000haoji/deep-student
src/components/Dashboard.tsx
import React, { useState, useEffect } from 'react'; import { TauriAPI } from '../utils/tauriApi'; import { BarChart3, Settings, AlertTriangle, FileText, Search, BookOpen, Tag, PieChart } from 'lucide-react'; interface DashboardProps { onBack: () => void; } interface Statistics { totalMistakes: number; totalReviews: number; subjectStats: Record<string, number>; typeStats: Record<string, number>; tagStats: Record<string, number>; recentMistakes: any[]; } export const Dashboard: React.FC<DashboardProps> = ({ onBack }) => { const [stats, setStats] = useState<Statistics | null>(null); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null); const [debugMode, setDebugMode] = useState(false); useEffect(() => { const loadStatistics = async () => { setLoading(true); setError(null); try { console.log('开始加载统计数据...'); // 先尝试加载真实数据 const statistics = await TauriAPI.getStatistics(); console.log('统计数据加载成功:', statistics); // 转换后端数据格式到前端格式 const formattedStats: Statistics = { totalMistakes: statistics.total_mistakes || 0, totalReviews: statistics.total_reviews || 0, subjectStats: statistics.subject_stats || {}, typeStats: statistics.type_stats || {}, tagStats: statistics.tag_stats || {}, recentMistakes: statistics.recent_mistakes || [] }; setStats(formattedStats); } catch (error) { console.error('加载统计数据失败:', error); setError(`加载统计数据失败: ${error}`); } finally { setLoading(false); } }; loadStatistics(); }, []); // 简化的渲染逻辑,确保总是有内容显示 return ( <div style={{ width: '100%', height: '100%', overflow: 'auto', background: '#f8fafc' }}> {/* 头部区域 - 统一白色样式 */} <div style={{ background: 'white', borderBottom: '1px solid #e5e7eb', padding: '24px 32px', position: 'relative' }}> <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: '4px', background: 'linear-gradient(90deg, #667eea, #764ba2)' }}></div> <div style={{ position: 'relative', zIndex: 1 }}> <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}> <svg style={{ width: '32px', height: '32px', marginRight: '12px', color: '#667eea' }} fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}> <path d="M3 3v16a2 2 0 0 0 2 2h16" /> <path d="M18 17V9" /> <path d="M13 17V5" /> <path d="M8 17v-3" /> </svg> <h1 style={{ fontSize: '28px', fontWeight: '700', margin: 0, color: '#1f2937' }}>数据统计</h1> </div> <p style={{ fontSize: '16px', color: '#6b7280', margin: 0, lineHeight: '1.5' }}> 全面了解学习数据和进度分析,洞察知识掌握情况 </p> {debugMode && ( <div style={{ marginTop: '24px' }}> <button onClick={() => setDebugMode(!debugMode)} style={{ background: '#ef4444', border: '1px solid #ef4444', color: 'white', padding: '12px 24px', borderRadius: '12px', fontSize: '16px', fontWeight: '600', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: '8px', transition: 'all 0.3s ease' }} onMouseOver={(e) => { e.currentTarget.style.background = '#dc2626'; e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 8px 25px rgba(239, 68, 68, 0.3)'; }} onMouseOut={(e) => { e.currentTarget.style.background = '#ef4444'; e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = 'none'; }} > <svg style={{ width: '20px', height: '20px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4" /> </svg> 关闭调试 </button> </div> )} {!debugMode && ( <div style={{ marginTop: '24px' }}> <button onClick={() => setDebugMode(!debugMode)} style={{ background: '#667eea', border: '1px solid #667eea', color: 'white', padding: '12px 24px', borderRadius: '12px', fontSize: '16px', fontWeight: '600', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: '8px', transition: 'all 0.3s ease' }} onMouseOver={(e) => { e.currentTarget.style.background = '#5a67d8'; e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 8px 25px rgba(102, 126, 234, 0.3)'; }} onMouseOut={(e) => { e.currentTarget.style.background = '#667eea'; e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = 'none'; }} > <svg style={{ width: '20px', height: '20px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4" /> </svg> 开启调试 </button> </div> )} </div> </div> <div className="dashboard-content" style={{ padding: '24px', background: 'transparent' }}> {debugMode && ( <div style={{ backgroundColor: 'rgba(255, 255, 255, 0.7)', padding: '1rem', borderRadius: '12px', marginBottom: '2rem', border: '1px solid rgba(255, 255, 255, 0.2)', backdropFilter: 'blur(10px)' }}> <h3 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}> <Settings size={20} /> 调试信息 </h3> <p><strong>加载状态:</strong> {loading ? '加载中' : '已完成'}</p> <p><strong>错误状态:</strong> {error || '无错误'}</p> <p><strong>数据状态:</strong> {stats ? '有数据' : '无数据'}</p> <p><strong>组件渲染:</strong> 正常</p> <div style={{ marginTop: '1rem' }}> <button onClick={async () => { try { console.log('手动测试API调用...'); const result = await TauriAPI.getStatistics(); console.log('手动测试结果:', result); alert('API调用成功,请查看控制台日志'); } catch (err) { console.error('手动测试失败:', err); alert(`API调用失败: ${err}`); } }} style={{ padding: '8px 16px', backgroundColor: '#007bff', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer', marginRight: '8px' }} > 测试API </button> <button onClick={() => { setError(null); setLoading(true); window.location.reload(); }} style={{ padding: '8px 16px', backgroundColor: '#28a745', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }} > 重新加载 </button> </div> </div> )} {loading ? ( <div style={{ textAlign: 'center', padding: '4rem', fontSize: '18px', color: '#666' }}> <div style={{ fontSize: '48px', marginBottom: '16px', display: 'flex', justifyContent: 'center' }}> <BarChart3 size={48} color="#667eea" /> </div> <div>加载统计数据中...</div> </div> ) : error && !stats ? ( <div style={{ textAlign: 'center', padding: '4rem', color: '#dc3545', backgroundColor: '#f8d7da', border: '1px solid #f5c6cb', borderRadius: '8px' }}> <div style={{ fontSize: '48px', marginBottom: '16px', display: 'flex', justifyContent: 'center' }}> <AlertTriangle size={48} color="#dc3545" /> </div> <div style={{ fontSize: '18px', marginBottom: '8px' }}>加载统计数据失败</div> <div style={{ fontSize: '14px', color: '#721c24' }}>{error}</div> </div> ) : ( <div> {/* 总览卡片 */} <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '1rem', marginBottom: '2rem' }}> <div style={{ backgroundColor: 'white', padding: '1.5rem', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)', display: 'flex', alignItems: 'center', gap: '1rem' }}> <div style={{ fontSize: '2rem', display: 'flex', alignItems: 'center' }}> <FileText size={32} color="#667eea" /> </div> <div> <div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#333' }}> {stats?.totalMistakes || 0} </div> <div style={{ color: '#666' }}>总错题数</div> </div> </div> <div style={{ backgroundColor: 'white', padding: '1.5rem', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)', display: 'flex', alignItems: 'center', gap: '1rem' }}> <div style={{ fontSize: '2rem', display: 'flex', alignItems: 'center' }}> <Search size={32} color="#28a745" /> </div> <div> <div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#333' }}> {stats?.totalReviews || 0} </div> <div style={{ color: '#666' }}>回顾分析次数</div> </div> </div> <div style={{ backgroundColor: 'white', padding: '1.5rem', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)', display: 'flex', alignItems: 'center', gap: '1rem' }}> <div style={{ fontSize: '2rem', display: 'flex', alignItems: 'center' }}> <BookOpen size={32} color="#ffc107" /> </div> <div> <div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#333' }}> {Object.keys(stats?.subjectStats || {}).length} </div> <div style={{ color: '#666' }}>涉及科目</div> </div> </div> <div style={{ backgroundColor: 'white', padding: '1.5rem', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)', display: 'flex', alignItems: 'center', gap: '1rem' }}> <div style={{ fontSize: '2rem', display: 'flex', alignItems: 'center' }}> <Tag size={32} color="#6f42c1" /> </div> <div> <div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#333' }}> {Object.keys(stats?.tagStats || {}).length} </div> <div style={{ color: '#666' }}>知识点标签</div> </div> </div> </div> {/* 详细统计 */} {stats && (stats.totalMistakes > 0 || Object.keys(stats.subjectStats).length > 0) ? ( <div style={{ display: 'grid', gap: '2rem' }}> {/* 科目分布 */} {Object.keys(stats.subjectStats).length > 0 && ( <div style={{ backgroundColor: 'white', padding: '1.5rem', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }}> <h3 style={{ marginBottom: '1rem', display: 'flex', alignItems: 'center', gap: '8px' }}> <BookOpen size={20} /> 科目分布 </h3> <div> {Object.entries(stats.subjectStats).map(([subject, count]) => ( <div key={subject} style={{ display: 'flex', alignItems: 'center', marginBottom: '0.5rem' }}> <div style={{ minWidth: '80px' }}>{subject}</div> <div style={{ flex: 1, backgroundColor: '#f0f0f0', height: '20px', borderRadius: '10px', margin: '0 1rem' }}> <div style={{ width: `${stats.totalMistakes > 0 ? (count / stats.totalMistakes) * 100 : 0}%`, height: '100%', backgroundColor: '#007bff', borderRadius: '10px' }} /> </div> <div style={{ minWidth: '30px', textAlign: 'right' }}>{count}</div> </div> ))} </div> </div> )} {/* 题目类型分布 */} {Object.keys(stats.typeStats).length > 0 && ( <div style={{ backgroundColor: 'white', padding: '1.5rem', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }}> <h3 style={{ marginBottom: '1rem', display: 'flex', alignItems: 'center', gap: '8px' }}> <PieChart size={20} /> 题目类型分布 </h3> <div> {Object.entries(stats.typeStats).map(([type, count]) => ( <div key={type} style={{ display: 'flex', alignItems: 'center', marginBottom: '0.5rem' }}> <div style={{ minWidth: '120px' }}>{type}</div> <div style={{ flex: 1, backgroundColor: '#f0f0f0', height: '20px', borderRadius: '10px', margin: '0 1rem' }}> <div style={{ width: `${stats.totalMistakes > 0 ? (count / stats.totalMistakes) * 100 : 0}%`, height: '100%', backgroundColor: '#28a745', borderRadius: '10px' }} /> </div> <div style={{ minWidth: '30px', textAlign: 'right' }}>{count}</div> </div> ))} </div> </div> )} </div> ) : ( <div style={{ textAlign: 'center', padding: '4rem', backgroundColor: 'white', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }}> <div style={{ fontSize: '48px', marginBottom: '16px', display: 'flex', justifyContent: 'center' }}> <BarChart3 size={48} color="#667eea" /> </div> <h3 style={{ marginBottom: '8px', color: '#333' }}>暂无数据</h3> <p style={{ color: '#666' }}>开始分析错题后,这里将显示详细的统计信息</p> </div> )} </div> )} </div> </div> ); };
17,018
Dashboard
tsx
en
tsx
code
{"qsc_code_num_words": 1369, "qsc_code_num_chars": 17018.0, "qsc_code_mean_word_length": 5.25931337, "qsc_code_frac_words_unique": 0.21256392, "qsc_code_frac_chars_top_2grams": 0.04166667, "qsc_code_frac_chars_top_3grams": 0.02875, "qsc_code_frac_chars_top_4grams": 0.0525, "qsc_code_frac_chars_dupe_5grams": 0.57291667, "qsc_code_frac_chars_dupe_6grams": 0.54041667, "qsc_code_frac_chars_dupe_7grams": 0.50305556, "qsc_code_frac_chars_dupe_8grams": 0.50305556, "qsc_code_frac_chars_dupe_9grams": 0.46847222, "qsc_code_frac_chars_dupe_10grams": 0.46305556, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.07188074, "qsc_code_frac_chars_whitespace": 0.42449171, "qsc_code_size_file_byte": 17018.0, "qsc_code_num_lines": 427.0, "qsc_code_num_chars_line_max": 228.0, "qsc_code_num_chars_line_mean": 39.85480094, "qsc_code_frac_chars_alphabet": 0.66326322, "qsc_code_frac_chars_comments": 0.00640498, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.60987654, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00493827, "qsc_code_frac_chars_string_length": 0.12667061, "qsc_code_frac_chars_long_word_length": 0.00130101, "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}
0000cd/wolf-set
readme.md
## 一、简介 Bluf 是一款**慵懒**的瀑布流网址导航 Hugo 主题,源于 Wolf Set([狼集](https://ws.0000cd.com/)) 导航的实践。 与传统“规整”的网址导航相比,**自适应瀑布流**的 bluf 要随性得多,长短随意,插图随心。还有标签或颜色**筛选**、**深色**模式、网站统计、访客问候等贴心功能,更支持**多链接、多图画廊**等模式。 一切只需 YAML 轻松配置。 ![狼集演示](static/狼集演示.gif) ## 二、安装 ### 2.1 快速上手 本教程基于“无需修改代码”的难度,几乎无需付费,只需三步在 [狼集](https://ws.0000cd.com/) 内容的基础上有一个属于自己的网址导航。 #### 步骤 0:准备 1. 确保你已注册 Github 与 Cloudflare 账号,我们将用此存储与发布网页。 2. (可选但推荐)准备一个你自己的域名,有助于提高国内的访问速度。 <details> <summary>继续浏览安装步骤…</summary> --- #### 步骤 1:复制仓库到你的 Github 1. 点击 [本页面](https://github.com/0000cd/wolf-set) 右上角的 fork 按钮,复制项目到你的 Github 仓库。 2. 记住你复制时的仓库名。(稍后会用到) #### 步骤 2:修改网站的基础配置 1. 在你刚 fork 的仓库首页,点开 `hugo.toml` 文件(根目录)。 2. 根据文件中的注释,编辑文件,修改以下内容: - 网址、网站名称、首页标题、SEO 信息、授权信息、网站统计等。 - 注意:如你还不确定网址,可先跳过,稍后记得修改。 - 注意:toml 格式,不要丢失两侧的英文引号`"`。 ```toml # hugo.toml 文件部分示例: baseURL = "https://ws.0000cd.com/" #你的网址 languageCode = "zh-CN" title = "狼牌网址导航 - 狼集 Wolf Set" #网站名称 theme = "bluf" #…… ``` #### 步骤 3:使用 Cloudflare Pages 发布网页 1. 打开 [Cloudflare Pages](https://pages.cloudflare.com/),点击创建 - Pages - 连接到 Git - Github,选择你刚记住仓库名的项目。 2. 点击开始设置,修改以下内容: - 项目名称(注意:若没有你自己的域名,这将是你默认域名的一部分) - 预设框架,选择 `Hugo` (无需修改其他默认设置)。 3. 点击保存并部署,通常会在一分钟内会完成,**但首次部署你还需再等 2~3 分钟**,才能点开预览链接在网上看到你的网页,请坐和放宽。 4. 修改并绑定域名: - 如果你有自己的域名,请在项目内找到自定义域,按提示绑定域名。 - 如果你没有自己的域名,请记住 Cloudflare 提供的默认域名(如 xxx.pages.dev)。 - 确认之前 `hugo.toml` 的网址已完成修改。 --- #### 常见问题 - 访问异常:如你无法访问 Cloudflare 默认提供的域名,或访问速度过慢,请绑定你自己的域名。 - 部署失败: - 如你部署失败,看一下部署日志,并检查你选对了仓库,以及 `hugo.toml` 内的格式。 - 如你用的不是 Cloudflare,而是 Vercel 或 Netlify 等平台部署失败,你可能需要在选择预设框架时,配置环境变量 hugo 版本为较新版本,如 `HUGO_VERSION = 0.117.0`。 ### 2.2 Hugo 开始 如果你对 Hugo 有一定了解,可直接用我们自写的 Bluf 主题来构建你的网站。只需先复制 themes/bluf 到你的项目,并在 hugo 中设置 `theme = "bluf"`。 Bluf 主题代码已经过多次测试,可稳定上线使用,但部分代码仍在清理中,因此暂不提供详细教程。如有任何问题或建议,欢迎通过 Issues 提交反馈!我们期待你的参与。 </details> ## 三、使用 如果你是按上面的教程 Cloudflare 部署的,您只需编辑对应的文件,在保存后 Cloudflare 会自动部署更改,片刻后更新到网页上。只需留意 TOML 或 YAML 格式,就能规避常见错误。 但即使你熟悉 Hugo,也推荐浏览一下使用说明。因为与大多数 Hugo 内容在 content 不同,Bluf 更接近单页主题,其主要在 data 目录下。 ### 3.1 导航卡片 #### 增删首页的导航卡片 请编辑 `data/cards.yaml`。该文件是 YAML 格式易于使用,如下: ```yaml - title: Humane by Design # 卡片标题 hex: "#14151d" # (可选)卡片颜色,会自动颜色分类。注意引号 tags: # 卡片标签,会标签分类 - 网页 - 设计 - 想法 date: "2024/04" # (可选)卡片时间 description: 人性化的数字产品和服务指南。 # 卡片描述 links: https://humanebydesign.com/ #卡片链接 ``` 提示:在 Markdown 文章中… - 插入 `{{< random >}}` 短码,可让该页面随机跳转所有导航网址。 - 插入 `{{< total >}}` 或 ` {{< total "tags" >}}` 短码,可统计所有或指定标签的导航卡片总数。如:`本站共 {{< total >}} 个有趣网址导航,和 {{< total "开源" >}} 个开源项目!` <details> <summary>继续浏览使用,如:导航卡片、导航栏、筛选、问候语、授权、个性化、SEO…</summary> #### 导航卡片配置多条链接 如果上文的 `links`,需要多条链接,你还可以这样写: ```yaml - title: Neal.fun hex: "#ffc7c7" tags: - 网页 - 有趣 date: "2024/12" description: 希望你有美好的一天… 游戏互动可视化等其他奇怪的东西。 links: - name: 官网 #注意,第一条链接不会展示,而是作为卡片整体的链接 url: https://neal.fun/ - name: 设置密码? url: https://neal.fun/password-game/ - name: 赞助 url: https://buymeacoffee.com/neal ``` #### 导航卡片头图、画廊模式 无需额外配置,只需将与卡片 `title` 名称一致的图片,放入 `assets/img` 文件夹下即可,如 `assets/img/Neal.fun.webp`。支持 jpg、png、gif、webp 格式,建议图片宽度大于 300px,但过大会影响加载速度。提示:可以获取网站的 `Open Graph` 用于插图。 请编辑 `hugo.toml`,先 `gallery = true` 开启画廊模式。之后在 `assets/gallery` 创建与卡片 `title` 名称一致的的文件夹(注意特殊符号),并放入多张图片(按文件名排序),再点击卡片头图就能进入画廊模式,浏览多张图片。适合像相册一样分享图片合集使用,如: ```markdown - assets - gallery - Humane by Design - a.jpg - 2.webp - Cat.gif ``` --- ### 3.2 标签筛选与导航栏 #### 配置导航卡片标签 请编辑 `data/tag_classes.yaml`,将管理用于筛选的标签的映射关系: ```yaml 桌面:"desktop" 移动:"mobile" 网页:"web" ``` 如你配置 `桌面:"desktop"`,在 `cards.yaml` 的 `tags` 只需输入“桌面”,就能按“desktop”筛选导航卡片。 特别的,由于颜色筛选是算法自动完成的,不建议修改颜色筛选的值。 #### 配置导航栏外链、筛选、标签 请编辑 `data/navbar.yaml`,分别在 `external_links`、`categories`、`hot_tags` 下配置外链、筛选、标签。 --- ### 3.3 更多特色功能 #### 网站问候、庆祝撒花 请编辑 `hugo.toml`,会在访问首页时随机展示问候,为空不启用;也可为移动端单独配置问候,用于引导: ```toml [params] greetings = [ #…… "Ctrl+D 收藏本站 ⭐", "点击【标签】,筛选内容 🔖", "点击 ●,切换深浅配色 🐼", ] #访客随机问候,为空不启用 mobileGreetings = [ "推荐电脑访问,体验更佳 💻", ] #移动端访客随机问候,为空使用 greetings ``` 输入喜欢的 emoji,会在用户清除筛选时庆祝撒花,感谢用户的访问,为空不启用: ```toml confettiEmojis = [ '🥟', '🍜', '🍊', '🧧', '🧨', '🏮', '🎉', '🐺' ] # 清除筛选时撒花,为空不启用 ``` #### 配置 CC 授权信息 请编辑 `hugo.toml` 的 `license`,会写入网站的 Meta 信息(游客不会直接看到)。 可进一步在 `layouts/partials/cc.html` 配置页脚的授权信息(只在文章页脚,不会显示在首页),如不需要可删除。 访问 [CC 授权](https://chooser-beta.creativecommons.org/) 选择授权协议,并生成页脚授权的代码。 #### 网站个性化、图标、配色 请在 `static` 下覆盖 `logo`、`favcion` 等文件修改图片,修改图标。推荐使用 [favicon.io](https://favicon.io/)。 请编辑 `hugo.toml`,修改强调色,点击导航栏的 ⚫ 切换深浅配色: ```toml [params] lightColor = "#0000cd" # 浅色强调色,推荐较深 darkColor = "#fafafa" # 深色强调色,推荐较浅 ``` #### 优化 SEO、网站统计 请编辑 `hugo.toml` 优化 SEO,支持隐私友好的开源 [Umami](https://umami.is/) 统计。 如你使用 Cloudflare 部署,可在该项目下的指标,开启 Web Analytics 进行统计。 可在 `content/achrive` 下放置历史数据,辅助优化搜索的 SEO。 如需 Search Console 等平台验证网站所有权,请将验证文件放在 `static` 下。 </details> --- ## Bluf theme [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=0000cd_wolf-set&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=0000cd_wolf-set) Bluf 是一款简明扼要的**瀑布流**卡片式 Hugo 主题,非常适合脑暴、作品集、链接导航、等需要**简单分享**的场景。部分代码由 GPT-4o 与 Claude-3.5 AI 协助。 ### 灵感 Blue + Wolf = Bluf > BLUF (bottom line up front) is the practice of beginning a message with its key information (the "bottom line"). This provides the reader with the most important information first. > BLUF(先行底行)是一种沟通方式,即在信息的开始部分先给出关键信息(即“底行”)。这样做可以让读者首先了解到最重要的信息。 ## License 本项目基于 **[Hugo](https://gohugo.io/)** 框架,并采用自建的 **Bluf** 主题: - `content` 与 `data` 目录下的内容遵循 **[CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh-hans)** 许可协议共享。 - **Bluf** 主题因集成 **[Isotope](https://isotope.metafizzy.co/license)**,遵守 **GPLv3** 许可协议。 - 画廊模式:[baguetteBox.js](https://github.com/feimosi/baguetteBox.js),MIT 协议。 - 庆祝撒花:[js-confetti](https://github.com/loonywizard/js-confetti),MIT 协议。
5,877
readme
md
zh
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0034031, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 141.0, "qsc_doc_num_words": 1606, "qsc_doc_num_chars": 5877.0, "qsc_doc_num_lines": 252.0, "qsc_doc_mean_word_length": 2.50311333, "qsc_doc_frac_words_full_bracket": 0.00077399, "qsc_doc_frac_lines_end_with_readmore": 0.01190476, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.39227895, "qsc_doc_entropy_unigram": 5.9208624, "qsc_doc_frac_words_all_caps": 0.00928793, "qsc_doc_frac_lines_dupe_lines": 0.17964072, "qsc_doc_frac_chars_dupe_lines": 0.02843084, "qsc_doc_frac_chars_top_2grams": 0.01791045, "qsc_doc_frac_chars_top_3grams": 0.00621891, "qsc_doc_frac_chars_top_4grams": 0.01368159, "qsc_doc_frac_chars_dupe_5grams": 0.01542289, "qsc_doc_frac_chars_dupe_6grams": 0.00646766, "qsc_doc_frac_chars_dupe_7grams": 0.0, "qsc_doc_frac_chars_dupe_8grams": 0.0, "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": 16.81212121, "qsc_doc_frac_chars_hyperlink_html_tag": 0.11825761, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.01775148, "qsc_doc_frac_chars_whitespace": 0.13731496, "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/components/StreamingChatInterface.tsx
/** * Streaming Chat Interface for AI SDK Analysis * * A simplified chat interface optimized for handling Tauri streaming events * with proper thinking chain support and real-time rendering. */ import React, { useState, useImperativeHandle, useEffect, useRef } from 'react'; import { MessageWithThinking } from './MessageWithThinking'; import { MarkdownRenderer } from './MarkdownRenderer'; interface StreamingChatMessage { id: string; role: 'user' | 'assistant'; content: string; thinking_content?: string; timestamp: string; rag_sources?: Array<{ document_id: string; file_name: string; chunk_text: string; score: number; chunk_index: number; }>; } interface StreamingChatInterfaceProps { messages: StreamingChatMessage[]; isStreaming: boolean; enableChainOfThought?: boolean; onSendMessage?: (message: string) => void; className?: string; streamingMode?: 'typewriter' | 'instant'; // 流式输出模式 } export interface StreamingChatInterfaceRef { sendMessage: (content: string) => void; clearInput: () => void; clearChat: () => void; setMessages: (messages: StreamingChatMessage[]) => void; } export const StreamingChatInterface = React.forwardRef<StreamingChatInterfaceRef, StreamingChatInterfaceProps>(({ messages, isStreaming, enableChainOfThought = true, onSendMessage, className = '', streamingMode = 'typewriter' // 默认使用打字机模式 }, ref) => { const [input, setInput] = useState(''); const [displayedContent, setDisplayedContent] = useState<{[key: string]: string}>({}); const [isFullscreen, setIsFullscreen] = useState(false); const [isAnimating, setIsAnimating] = useState(false); const messagesEndRef = useRef<HTMLDivElement>(null); const typewriterTimeouts = useRef<{[key: string]: number}>({}); const containerRef = useRef<HTMLDivElement>(null); // Handle form submission const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (!input.trim() || isStreaming) return; if (onSendMessage) { onSendMessage(input); } setInput(''); }; // Handle keyboard shortcuts const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSubmit(e as any); } // ESC键退出全屏 if (e.key === 'Escape' && isFullscreen) { handleToggleFullscreen(); } }; // 全屏切换功能 const handleToggleFullscreen = () => { if (isAnimating) return; setIsAnimating(true); if (isFullscreen) { // 退出全屏 if (containerRef.current) { containerRef.current.classList.add('collapsing'); containerRef.current.classList.remove('fullscreen'); } setTimeout(() => { setIsFullscreen(false); setIsAnimating(false); if (containerRef.current) { containerRef.current.classList.remove('collapsing'); } }, 500); } else { // 进入全屏 setIsFullscreen(true); if (containerRef.current) { containerRef.current.classList.add('expanding'); } setTimeout(() => { if (containerRef.current) { containerRef.current.classList.remove('expanding'); containerRef.current.classList.add('fullscreen'); } setIsAnimating(false); }, 500); } }; // 处理全屏快捷键 useEffect(() => { const handleKeyPress = (e: KeyboardEvent) => { // F11或Ctrl+Enter切换全屏 if (e.key === 'F11' || (e.ctrlKey && e.key === 'Enter')) { e.preventDefault(); handleToggleFullscreen(); } }; if (isFullscreen) { document.addEventListener('keydown', handleKeyPress); return () => document.removeEventListener('keydown', handleKeyPress); } }, [isFullscreen]); // 打字机效果的流式内容显示 useEffect(() => { if (streamingMode === 'instant') return; messages.forEach((message) => { if (message.role === 'assistant' && message.content) { const messageId = message.id; const fullContent = message.content; const currentDisplayed = displayedContent[messageId] || ''; // Only start typewriter if content has changed and is longer if (fullContent !== currentDisplayed && fullContent.length > currentDisplayed.length) { // Clear existing timeout for this message if (typewriterTimeouts.current[messageId]) { clearTimeout(typewriterTimeouts.current[messageId]); } // Start typewriter from current position let currentIndex = currentDisplayed.length; const typeNextChar = () => { if (currentIndex < fullContent.length) { const nextContent = fullContent.substring(0, currentIndex + 1); setDisplayedContent(prev => ({ ...prev, [messageId]: nextContent })); currentIndex++; // 根据字符类型调整显示速度 const char = fullContent[currentIndex - 1]; let delay = 25; // Base typing speed if (char === ' ') delay = 8; else if (char === '.' || char === '!' || char === '?') delay = 150; else if (char === ',' || char === ';' || char === ':') delay = 80; else if (char === '\n') delay = 100; typewriterTimeouts.current[messageId] = setTimeout(typeNextChar, delay); } }; // Start typing animation if (currentIndex < fullContent.length) { typeNextChar(); } } } }); return () => { // Cleanup timeouts Object.values(typewriterTimeouts.current).forEach(timeout => clearTimeout(timeout)); }; }, [messages, streamingMode, displayedContent]); // 自动滚动到底部 useEffect(() => { if (messagesEndRef.current) { messagesEndRef.current.scrollIntoView({ behavior: 'smooth' }); } }, [messages, displayedContent]); // Get content for display (original or typewriter) const getDisplayContent = (message: StreamingChatMessage) => { if (message.role === 'user' || streamingMode === 'instant') { return message.content; } return displayedContent[message.id] || ''; }; // Expose methods to parent component useImperativeHandle(ref, () => ({ sendMessage: (content: string) => { if (onSendMessage) { onSendMessage(content); } }, clearInput: () => { setInput(''); }, clearChat: () => { setDisplayedContent({}); Object.values(typewriterTimeouts.current).forEach(timeout => clearTimeout(timeout)); typewriterTimeouts.current = {}; }, setMessages: (_newMessages: StreamingChatMessage[]) => { // Reset displayed content for new messages setDisplayedContent({}); } })); return ( <div ref={containerRef} className={`streaming-chat-interface ${className} ${isFullscreen ? 'fullscreen' : ''}`} > {/* 全屏工具栏 */} <div className="chat-toolbar"> <div className="toolbar-left"> <span className="chat-title">💬 AI智能对话</span> </div> <div className="toolbar-right"> <button onClick={handleToggleFullscreen} disabled={isAnimating} className="fullscreen-toggle-btn" title={isFullscreen ? "退出全屏 (ESC)" : "进入全屏 (F11)"} > {isFullscreen ? '⤋' : '⤢'} </button> </div> </div> {/* Chat Messages */} <div className="chat-messages"> {messages.map((message, index) => ( <div key={message.id} className={`message-wrapper ${message.role}`}> <div className="message-header"> <span className="role">{message.role === 'user' ? '用户' : 'AI助手'}</span> <span className="timestamp"> {new Date(message.timestamp).toLocaleTimeString()} </span> </div> {message.role === 'assistant' ? ( <MessageWithThinking content={getDisplayContent(message)} thinkingContent={message.thinking_content} isStreaming={isStreaming && index === messages.length - 1} role="assistant" timestamp={message.timestamp} ragSources={message.rag_sources} /> ) : ( <div className="user-message-content"> <MarkdownRenderer content={message.content} /> </div> )} </div> ))} {/* Streaming indicator */} {isStreaming && ( <div className="streaming-indicator"> <div className="typing-dots"> <span></span> <span></span> <span></span> </div> <span className="streaming-text">AI正在思考和回答中...</span> </div> )} {/* Auto-scroll anchor */} <div ref={messagesEndRef} /> </div> {/* Chat Input */} <form onSubmit={handleSubmit} className="chat-input-form"> <div className="input-container"> <textarea value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={handleKeyDown} placeholder="继续提问..." disabled={isStreaming} rows={3} className="chat-input" /> <div className="input-actions"> <button type="submit" disabled={!input.trim() || isStreaming} className="send-button" > {isStreaming ? '回答中...' : '发送'} </button> </div> </div> </form> {/* Chat Info */} <div className="chat-info"> <div className="chat-stats"> <span>消息数: {messages.length}</span> {isStreaming && <span className="streaming-status">🔄 流式回答中</span>} {enableChainOfThought && <span className="thinking-status">🧠 显示思维过程</span>} </div> </div> </div> ); }); StreamingChatInterface.displayName = 'StreamingChatInterface';
10,206
StreamingChatInterface
tsx
en
tsx
code
{"qsc_code_num_words": 786, "qsc_code_num_chars": 10206.0, "qsc_code_mean_word_length": 7.34860051, "qsc_code_frac_words_unique": 0.32188295, "qsc_code_frac_chars_top_2grams": 0.02493075, "qsc_code_frac_chars_top_3grams": 0.02908587, "qsc_code_frac_chars_top_4grams": 0.02285319, "qsc_code_frac_chars_dupe_5grams": 0.08102493, "qsc_code_frac_chars_dupe_6grams": 0.06925208, "qsc_code_frac_chars_dupe_7grams": 0.06128809, "qsc_code_frac_chars_dupe_8grams": 0.02423823, "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.00387382, "qsc_code_frac_chars_whitespace": 0.29178914, "qsc_code_size_file_byte": 10206.0, "qsc_code_num_lines": 330.0, "qsc_code_num_chars_line_max": 114.0, "qsc_code_num_chars_line_mean": 30.92727273, "qsc_code_frac_chars_alphabet": 0.79454898, "qsc_code_frac_chars_comments": 0.08103077, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.26865672, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.06460554, "qsc_code_frac_chars_long_word_length": 0.00682303, "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}
0000cd/wolf-set
hugo.toml
baseURL = "https://ws.0000cd.com/" #你的网址,以斜杠 / 结尾 languageCode = "zh-CN" title = "狼牌网址导航 - 狼集 Wolf Set" #网站名称 theme = "bluf" [params] pagename = "狼集 Wolf Set" #首页标题 description = " 狼集 Wolf Set, 源自“狼牌工作网址导航”,集设计、Markdown、软件、安全、办公必备网址于一体,All in One 最佳选择。" #SEO,你的网站描述 keywords = [ "狼集", "Wolf Set", "狼牌", "狼牌工作网址导航", "网址大全", "网址之家", "网址导航", "设计工具", "Markdown资源", "办公软件", "安全工具", "All in One" ] #SEO,网站关键词 author = "0000CD.COM & 逊狼" #SEO,网站作者 alias ="狼牌网址导航" #SEO,可删除 license="CC BY-NC 4.0" #网站授权信息,https://chooser-beta.creativecommons.org/ enableUmami = true #umami 统计相关,没有请 false,https://umami.is/ UmamiLink = "https://eu.umami.is/script.js" UmamiID = "02cc419c-d758-4a4f-a9bd-1e442b1f8435" lightColor = "#0000cd" # 浅色强调色,推荐较深 darkColor = "#fafafa" # 深色强调色,推荐较浅 gallery = true #启用画廊模式 greetings = [ "你好朋友,你好世界 🎉", "嗷~ 记得早点休息 🌛", "互联网第一条消息是 LO 💡", "互联网重量或是一颗草莓 💡", "互联网第一个表情是:-) 💡", "Ctrl+F 搜索本站 🔎", "Ctrl+D 收藏本站 ⭐", "点击【标签】,筛选内容 🔖", "点击 ●,切换深浅配色 🐼", ] #访客随机问候,为空不启用 mobileGreetings = [ "推荐电脑访问,体验更佳 💻", ] #移动端访客随机问候,为空使用 greetings confettiEmojis = [ '🥟', '🍜', '🍊', '🧧', '🧨', '🏮', '🎉', '🐺' ] # 清除筛选时撒花,为空不启用 [sitemap] changefreq = "weekly" priority = 0.5 filename = "sitemap.xml" [outputs] home = ["HTML", "RSS"] [outputFormats.RSS] mediatype = "application/rss+xml" baseName = "feed" [markup] [markup.highlight] style = "gruvbox" [minify] minifyOutput = true
1,484
hugo
toml
zh
toml
data
{"qsc_code_num_words": 277, "qsc_code_num_chars": 1484.0, "qsc_code_mean_word_length": 3.27075812, "qsc_code_frac_words_unique": 0.6967509, "qsc_code_frac_chars_top_2grams": 0.02207506, "qsc_code_frac_chars_top_3grams": 0.0397351, "qsc_code_frac_chars_top_4grams": 0.01766004, "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.03050847, "qsc_code_frac_chars_whitespace": 0.20485175, "qsc_code_size_file_byte": 1484.0, "qsc_code_num_lines": 72.0, "qsc_code_num_chars_line_max": 103.0, "qsc_code_num_chars_line_mean": 20.61111111, "qsc_code_frac_chars_alphabet": 0.72118644, "qsc_code_frac_chars_comments": 0.15768194, "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.01694915, "qsc_code_frac_chars_string_length": 0.39968026, "qsc_code_frac_chars_long_word_length": 0.0647482, "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_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": 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/GeminiAdapterTest.tsx
import React, { useState, useEffect } from 'react'; import { invoke } from '@tauri-apps/api/core'; import { listen } from '@tauri-apps/api/event'; interface TestResult { success: boolean; message: string; details?: any; duration?: number; } interface ApiConfig { id: string; name: string; apiKey: string; baseUrl: string; model: string; isMultimodal: boolean; isReasoning: boolean; enabled: boolean; modelAdapter: string; maxOutputTokens: number; temperature: number; } export const GeminiAdapterTest: React.FC = () => { const [selectedConfig, setSelectedConfig] = useState<ApiConfig | null>(null); const [apiConfigs, setApiConfigs] = useState<ApiConfig[]>([]); const [testResults, setTestResults] = useState<Record<string, TestResult>>({}); const [isLoading, setIsLoading] = useState<Record<string, boolean>>({}); const [streamingContent, setStreamingContent] = useState(''); const [testPrompt, setTestPrompt] = useState('你好,请用中文简单介绍一下你自己。这是一个测试Gemini适配器的OpenAI兼容接口转换功能。'); const [imageBase64, setImageBase64] = useState<string>(''); const [imagePreview, setImagePreview] = useState<string>(''); const [currentLogPath, setCurrentLogPath] = useState<string>(''); const [allTestLogs, setAllTestLogs] = useState<string[]>([]); useEffect(() => { loadApiConfigs(); loadTestLogs(); }, []); // 生成测试日志内容 const generateTestLog = (testType: string, config: ApiConfig, result: TestResult, additionalData?: any) => { const timestamp = new Date().toISOString(); const logEntry = { timestamp, testType, config: { id: config.id, name: config.name, model: config.model, baseUrl: config.baseUrl, modelAdapter: config.modelAdapter, isMultimodal: config.isMultimodal, temperature: config.temperature, maxOutputTokens: config.maxOutputTokens }, testPrompt, result: { success: result.success, message: result.message, duration: result.duration, details: result.details }, additionalData: additionalData || {}, environment: { userAgent: navigator.userAgent, timestamp: timestamp, testVersion: '1.0.0' } }; return JSON.stringify(logEntry, null, 2); }; // 保存测试日志到文件 const saveTestLog = async (logContent: string, testType: string) => { try { const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); const fileName = `gemini-adapter-test-${testType}-${timestamp}.log`; // 使用 Tauri 的文件管理服务保存日志 await invoke('save_test_log', { fileName, content: logContent, logType: 'gemini-adapter-test' }); const logPath = `logs/gemini-adapter-test/${fileName}`; setCurrentLogPath(logPath); // 更新日志列表 setAllTestLogs(prev => [logPath, ...prev]); console.log(`测试日志已保存: ${logPath}`); return logPath; } catch (error) { console.error('保存测试日志失败:', error); return null; } }; // 加载历史测试日志列表 const loadTestLogs = async () => { try { const logs = await invoke<string[]>('get_test_logs', { logType: 'gemini-adapter-test' }); setAllTestLogs(logs); } catch (error) { console.error('加载历史日志失败:', error); } }; const loadApiConfigs = async () => { try { const configs = await invoke<ApiConfig[]>('get_api_configurations'); const geminiConfigs = configs.filter(c => c.modelAdapter === 'google' && c.enabled); setApiConfigs(geminiConfigs); if (geminiConfigs.length > 0) { setSelectedConfig(geminiConfigs[0]); } } catch (error) { console.error('加载 API 配置失败:', error); } }; // 基础连接测试 const testBasicConnection = async () => { if (!selectedConfig) return; setIsLoading({ ...isLoading, basic: true }); const startTime = Date.now(); let testResult: TestResult; try { const result = await invoke<boolean>('test_api_connection', { apiKey: selectedConfig.apiKey, apiBase: selectedConfig.baseUrl, model: selectedConfig.model }); testResult = { success: result, message: result ? '连接成功!API 密钥和端点有效。' : '连接失败,请检查配置。', duration: Date.now() - startTime, details: { connectionResult: result } }; setTestResults({ ...testResults, basic: testResult }); } catch (error) { const errorMessage = error instanceof Error ? error.message : (typeof error === 'object' ? JSON.stringify(error) : String(error)); testResult = { success: false, message: `连接测试失败: ${errorMessage}`, duration: Date.now() - startTime, details: { error: errorMessage } }; setTestResults({ ...testResults, basic: testResult }); } finally { setIsLoading({ ...isLoading, basic: false }); // 保存测试日志 if (selectedConfig) { const logContent = generateTestLog('basic-connection', selectedConfig, testResult, { testDescription: '基础连接测试 - 验证API密钥和端点有效性' }); await saveTestLog(logContent, 'basic-connection'); } } }; // 非流式OpenAI兼容接口测试(使用流式接口收集完整响应) const testNonStreamingChat = async () => { if (!selectedConfig) return; setIsLoading({ ...isLoading, nonStreaming: true }); const startTime = Date.now(); let testResult: TestResult; let collectedContent = ''; try { // 创建临时会话进行测试 const tempId = `gemini_non_stream_test_${Date.now()}`; const streamEvent = `analysis_stream_${tempId}`; const chatHistory = [{ role: 'user', content: testPrompt, timestamp: new Date().toISOString(), }]; console.log('发送非流式测试请求(使用流式接口),使用适配器:', selectedConfig.modelAdapter); console.log('聊天历史:', chatHistory); // 使用流式接口但收集完整响应 const unlistenContent = await listen(streamEvent, (event: any) => { console.log('收到非流式测试事件:', event.payload); if (event.payload.content) { collectedContent += event.payload.content; } if (event.payload.is_complete) { testResult = { success: true, message: 'Gemini适配器非流式测试成功!OpenAI格式已正确转换为Gemini API调用。', details: { response: { message: collectedContent }, requestData: { tempId, chatHistory }, responseLength: collectedContent.length, method: 'streaming_collected' }, duration: Date.now() - startTime }; setTestResults(prev => ({ ...prev, nonStreaming: testResult })); setIsLoading(prev => ({ ...prev, nonStreaming: false })); // 保存测试日志 if (selectedConfig) { const logContent = generateTestLog('non-streaming', selectedConfig, testResult, { testDescription: '非流式OpenAI兼容接口测试 - 使用流式接口收集完整响应', prompt: testPrompt, collectedContent }); saveTestLog(logContent, 'non-streaming'); } } }); const unlistenError = await listen('stream_error', (event: any) => { console.error('非流式测试流式错误:', event.payload); const errorMessage = typeof event.payload.error === 'object' ? JSON.stringify(event.payload.error) : String(event.payload.error); testResult = { success: false, message: `Gemini适配器非流式测试失败: ${errorMessage}`, duration: Date.now() - startTime, details: { error: errorMessage, collectedContent } }; setTestResults(prev => ({ ...prev, nonStreaming: testResult })); setIsLoading(prev => ({ ...prev, nonStreaming: false })); }); // 发起流式请求 - 使用 analyze_new_mistake_stream 创建临时会话并测试适配器 await invoke('analyze_new_mistake_stream', { request: { subject: "AI适配器测试", question_image_files: [], // 非流式测试不需要图片 analysis_image_files: [], user_question: testPrompt, enable_step_by_step: false } }); // 设置超时清理 setTimeout(() => { unlistenContent(); unlistenError(); }, 30000); } catch (error) { console.error('非流式测试失败:', error); const errorMessage = error instanceof Error ? error.message : (typeof error === 'object' ? JSON.stringify(error) : String(error)); testResult = { success: false, message: `Gemini适配器非流式测试失败: ${errorMessage}`, duration: Date.now() - startTime, details: { error: errorMessage, collectedContent } }; setTestResults(prev => ({ ...prev, nonStreaming: testResult })); setIsLoading(prev => ({ ...prev, nonStreaming: false })); // 保存失败的测试日志 if (selectedConfig) { const logContent = generateTestLog('non-streaming', selectedConfig, testResult, { testDescription: '非流式OpenAI兼容接口测试 - 异常失败', prompt: testPrompt }); await saveTestLog(logContent, 'non-streaming-exception'); } } }; // 流式OpenAI兼容接口测试 const testStreamingChat = async () => { if (!selectedConfig) return; setIsLoading({ ...isLoading, streaming: true }); setStreamingContent(''); const startTime = Date.now(); let testResult: TestResult; let streamData: string[] = []; try { const tempId = `gemini_stream_test_${Date.now()}`; const streamEvent = `analysis_stream_${tempId}`; console.log('发送流式测试请求,使用适配器:', selectedConfig.modelAdapter); // 设置流式事件监听 const unlistenContent = await listen(streamEvent, (event: any) => { console.log('收到流式事件:', event.payload); if (event.payload.content) { streamData.push(event.payload.content); setStreamingContent(prev => prev + event.payload.content); } if (event.payload.is_complete) { testResult = { success: true, message: 'Gemini适配器流式测试成功!OpenAI格式已正确转换为Gemini流式API调用。', duration: Date.now() - startTime, details: { streamChunks: streamData.length, totalContent: streamData.join(''), contentLength: streamData.join('').length, averageChunkSize: streamData.length > 0 ? streamData.join('').length / streamData.length : 0 } }; setTestResults(prev => ({ ...prev, streaming: testResult })); setIsLoading(prev => ({ ...prev, streaming: false })); // 保存流式测试日志 if (selectedConfig) { const logContent = generateTestLog('streaming', selectedConfig, testResult, { testDescription: '流式OpenAI兼容接口测试 - 验证OpenAI流式格式转换为Gemini流式API调用', prompt: testPrompt, streamingData: { chunks: streamData, totalChunks: streamData.length } }); saveTestLog(logContent, 'streaming'); } } }); const unlistenError = await listen('stream_error', (event: any) => { console.error('流式错误:', event.payload); testResult = { success: false, message: `Gemini适配器流式测试错误: ${event.payload.error}`, duration: Date.now() - startTime, details: { error: event.payload.error, streamData } }; setTestResults(prev => ({ ...prev, streaming: testResult })); setIsLoading(prev => ({ ...prev, streaming: false })); // 保存失败的流式测试日志 if (selectedConfig) { const logContent = generateTestLog('streaming', selectedConfig, testResult, { testDescription: '流式OpenAI兼容接口测试 - 失败', prompt: testPrompt, streamingData: { chunks: streamData, totalChunks: streamData.length } }); saveTestLog(logContent, 'streaming-error'); } }); // 发起流式请求 - 使用 analyze_new_mistake_stream 创建临时会话并测试适配器 await invoke('analyze_new_mistake_stream', { request: { subject: "AI适配器流式测试", question_image_files: [], // 流式测试不需要图片 analysis_image_files: [], user_question: testPrompt, enable_step_by_step: false } }); // 清理监听器 return () => { unlistenContent(); unlistenError(); }; } catch (error) { console.error('流式测试失败:', error); const errorMessage = error instanceof Error ? error.message : (typeof error === 'object' ? JSON.stringify(error) : String(error)); testResult = { success: false, message: `Gemini适配器流式测试失败: ${errorMessage}`, duration: Date.now() - startTime, details: { error: errorMessage, streamData } }; setTestResults({ ...testResults, streaming: testResult }); setIsLoading({ ...isLoading, streaming: false }); // 保存失败的流式测试日志 if (selectedConfig) { const logContent = generateTestLog('streaming', selectedConfig, testResult, { testDescription: '流式OpenAI兼容接口测试 - 异常失败', prompt: testPrompt }); await saveTestLog(logContent, 'streaming-exception'); } } }; // 多模态测试(图片+文本) const testMultimodal = async () => { if (!selectedConfig || !selectedConfig.isMultimodal || !imageBase64) { const testResult: TestResult = { success: false, message: selectedConfig?.isMultimodal ? '请先上传一张图片进行测试。' : '当前模型不支持多模态功能。', details: { reason: selectedConfig?.isMultimodal ? 'no_image' : 'not_multimodal', isMultimodal: selectedConfig?.isMultimodal || false } }; setTestResults({ ...testResults, multimodal: testResult }); // 保存跳过的测试日志 if (selectedConfig) { const logContent = generateTestLog('multimodal', selectedConfig, testResult, { testDescription: '多模态测试 - 跳过(条件不满足)', skipReason: testResult.details?.reason }); await saveTestLog(logContent, 'multimodal-skipped'); } return; } setIsLoading({ ...isLoading, multimodal: true }); const startTime = Date.now(); let testResult: TestResult; try { console.log('发送多模态测试请求,使用适配器:', selectedConfig.modelAdapter); const multimodalPrompt = '请描述这张图片的内容。测试Gemini适配器的多模态OpenAI兼容接口转换。'; // 使用分析接口测试多模态(会自动调用gemini_adapter的多模态功能) const response = await invoke('analyze_step_by_step', { request: { subject: '测试', question_image_files: [imageBase64], analysis_image_files: [], user_question: multimodalPrompt, enable_chain_of_thought: false } }); console.log('多模态适配器响应:', response); testResult = { success: true, message: 'Gemini适配器多模态测试成功!OpenAI多模态格式已正确转换为Gemini API调用。', details: { response, imageSize: imageBase64.length, prompt: multimodalPrompt, responseLength: (response as any)?.analysis_result?.length || 0 }, duration: Date.now() - startTime }; setTestResults({ ...testResults, multimodal: testResult }); } catch (error) { console.error('多模态测试失败:', error); const errorMessage = error instanceof Error ? error.message : (typeof error === 'object' ? JSON.stringify(error) : String(error)); testResult = { success: false, message: `Gemini适配器多模态测试失败: ${errorMessage}`, duration: Date.now() - startTime, details: { error: errorMessage, imageSize: imageBase64.length } }; setTestResults({ ...testResults, multimodal: testResult }); } finally { setIsLoading({ ...isLoading, multimodal: false }); // 保存多模态测试日志 if (selectedConfig) { const logContent = generateTestLog('multimodal', selectedConfig, testResult, { testDescription: '多模态OpenAI兼容接口测试 - 验证OpenAI多模态格式转换为Gemini多模态API调用', imageData: { hasImage: !!imageBase64, imageSize: imageBase64?.length || 0, imageType: imageBase64?.substring(0, 50) || '' // 图片头部信息 } }); await saveTestLog(logContent, 'multimodal'); } } }; // 处理图片上传 const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => { const file = event.target.files?.[0]; if (!file) return; const reader = new FileReader(); reader.onload = (e) => { const base64 = e.target?.result as string; setImageBase64(base64); setImagePreview(base64); }; reader.readAsDataURL(file); }; // 运行所有测试 const runAllTests = async () => { if (!selectedConfig) return; const batchStartTime = Date.now(); const batchId = `batch_${Date.now()}`; console.log(`开始批量测试 - Batch ID: ${batchId}`); // 清除之前的测试结果 setTestResults({}); setStreamingContent(''); const testSequence = [ { name: 'basic', func: testBasicConnection }, { name: 'nonStreaming', func: testNonStreamingChat }, { name: 'streaming', func: testStreamingChat } ]; // 如果支持多模态且有图片,添加多模态测试 if (selectedConfig.isMultimodal && imageBase64) { testSequence.push({ name: 'multimodal', func: testMultimodal }); } const batchResults: Record<string, TestResult> = {}; // 依次执行所有测试 for (const test of testSequence) { console.log(`执行测试: ${test.name}`); await test.func(); await new Promise(resolve => setTimeout(resolve, 1000)); // 测试间隔 // 收集测试结果 const currentResults = testResults; if (currentResults[test.name]) { batchResults[test.name] = currentResults[test.name]; } } // 生成批量测试总结日志 const batchDuration = Date.now() - batchStartTime; const successCount = Object.values(batchResults).filter(r => r.success).length; const totalCount = Object.keys(batchResults).length; const batchLogEntry = { timestamp: new Date().toISOString(), batchId, testType: 'batch-all-tests', config: { id: selectedConfig.id, name: selectedConfig.name, model: selectedConfig.model, baseUrl: selectedConfig.baseUrl, modelAdapter: selectedConfig.modelAdapter, isMultimodal: selectedConfig.isMultimodal, temperature: selectedConfig.temperature, maxOutputTokens: selectedConfig.maxOutputTokens }, testPrompt, batchSummary: { totalTests: totalCount, successfulTests: successCount, failedTests: totalCount - successCount, successRate: totalCount > 0 ? (successCount / totalCount * 100).toFixed(2) + '%' : '0%', totalDuration: batchDuration, averageTestDuration: totalCount > 0 ? Math.round(batchDuration / totalCount) : 0 }, individualResults: batchResults, testSequence: testSequence.map(t => t.name), environment: { userAgent: navigator.userAgent, timestamp: new Date().toISOString(), testVersion: '1.0.0', hasImage: !!imageBase64, imageSize: imageBase64?.length || 0 } }; // 保存批量测试日志 const batchLogContent = JSON.stringify(batchLogEntry, null, 2); await saveTestLog(batchLogContent, 'batch-all'); console.log(`批量测试完成 - 成功: ${successCount}/${totalCount}, 耗时: ${batchDuration}ms`); }; const renderTestResult = (key: string, title: string) => { const result = testResults[key]; const loading = isLoading[key]; return ( <div className="flex-1"> <div className="flex items-center mb-2"> <h3 className="font-semibold text-gray-800 flex-1">{title}</h3> <div className="ml-4"> {loading ? ( <div className="inline-flex items-center px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm"> <div className="h-4 w-4 animate-spin rounded-full border-2 border-blue-600 border-t-transparent mr-2" /> 测试中... </div> ) : result ? ( result.success ? ( <div className="inline-flex items-center px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm font-medium"> <span className="mr-1">✅</span> 成功 </div> ) : ( <div className="inline-flex items-center px-3 py-1 bg-red-100 text-red-800 rounded-full text-sm font-medium"> <span className="mr-1">❌</span> 失败 </div> ) ) : ( <div className="inline-flex items-center px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-sm"> 待测试 </div> )} </div> </div> {result && ( <div className="space-y-1"> <p className={`text-sm ${result.success ? 'text-green-700' : 'text-red-700'}`}> {result.message} </p> {result?.duration && ( <p className="text-xs text-gray-500"> ⏱️ 耗时: {result.duration}ms </p> )} </div> )} </div> ); }; if (apiConfigs.length === 0) { return ( <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 p-6"> <div className="max-w-4xl mx-auto"> {/* 页面头部 */} <div className="text-center mb-8"> <div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full mb-4"> <span className="text-2xl text-white">🧪</span> </div> <h1 className="text-4xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent mb-3"> Gemini 适配器测试 </h1> </div> {/* 错误提示卡片 */} <div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden"> <div className="bg-gradient-to-r from-yellow-500 to-orange-600 p-6 text-white"> <h2 className="text-xl font-bold flex items-center"> <span className="mr-3">⚠️</span> 配置缺失 </h2> </div> <div className="p-8"> <div className="text-center"> <div className="inline-flex items-center justify-center w-20 h-20 bg-yellow-100 rounded-full mb-6"> <span className="text-3xl">⚙️</span> </div> <h3 className="text-xl font-semibold text-gray-800 mb-4"> 未找到启用的 Gemini 配置 </h3> <p className="text-gray-600 mb-6 max-w-md mx-auto"> 请先在 API 配置中添加一个 Google (Gemini) 适配器的配置,然后启用该配置。 </p> <div className="bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-6 border border-blue-200 mb-6"> <h4 className="font-semibold text-blue-800 mb-3 flex items-center justify-center"> <span className="mr-2">📝</span> 配置要求 </h4> <div className="text-left text-sm text-blue-700 space-y-2"> <div className="flex items-center"> <span className="w-2 h-2 bg-blue-500 rounded-full mr-3"></span> <span><strong>modelAdapter</strong> 字段必须设置为 <code className="px-2 py-1 bg-blue-100 rounded text-xs">"google"</code></span> </div> <div className="flex items-center"> <span className="w-2 h-2 bg-blue-500 rounded-full mr-3"></span> <span>配置必须处于 <strong>启用</strong> 状态</span> </div> <div className="flex items-center"> <span className="w-2 h-2 bg-blue-500 rounded-full mr-3"></span> <span>需要有效的 Gemini API 密钥</span> </div> </div> </div> <button onClick={() => window.location.reload()} className="px-6 py-3 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-lg hover:from-blue-600 hover:to-purple-700 transition-all duration-200 flex items-center mx-auto font-semibold" > <span className="mr-2">🔄</span> 刷新页面 </button> </div> </div> </div> </div> </div> ); } return ( <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 p-6"> <div className="max-w-7xl mx-auto"> {/* 页面头部 */} <div className="text-center mb-8"> <div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full mb-4"> <span className="text-2xl text-white">🧪</span> </div> <h1 className="text-4xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent mb-3"> Gemini 适配器测试 </h1> <p className="text-lg text-gray-600 max-w-3xl mx-auto"> 此测试页面验证 <code className="px-2 py-1 bg-gray-100 rounded text-sm font-mono">gemini_adapter.rs</code> 是否能正确将 OpenAI 兼容格式转换为 Gemini API 调用并正常工作 </p> </div> {/* 配置卡片 */} <div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden"> <div className="bg-gradient-to-r from-blue-500 to-purple-600 p-6 text-white"> <h2 className="text-xl font-bold flex items-center"> <span className="mr-3">⚙️</span> API 配置选择 </h2> </div> <div className="p-6"> <div className="mb-4"> <label className="block text-sm font-semibold text-gray-700 mb-3">选择 Gemini 配置</label> <select className="w-full p-4 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all duration-200 bg-white text-gray-800" value={selectedConfig?.id || ''} onChange={(e) => { const config = apiConfigs.find(c => c.id === e.target.value); setSelectedConfig(config || null); }} > {apiConfigs.map(config => ( <option key={config.id} value={config.id}> {config.name} - {config.model} </option> ))} </select> </div> {selectedConfig && ( <div className="bg-gradient-to-br from-blue-50 to-purple-50 rounded-lg p-6 border border-blue-200"> <h3 className="font-semibold text-gray-800 mb-4 flex items-center"> <span className="mr-2">📋</span> 配置详情 </h3> <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm"> <div className="bg-white rounded-lg p-3 border"> <span className="font-medium text-gray-600">模型:</span> <div className="text-gray-800 font-mono">{selectedConfig.model}</div> </div> <div className="bg-white rounded-lg p-3 border"> <span className="font-medium text-gray-600">端点:</span> <div className="text-gray-800 font-mono text-xs break-all">{selectedConfig.baseUrl}</div> </div> <div className="bg-white rounded-lg p-3 border"> <span className="font-medium text-gray-600">适配器:</span> <div> <span className="inline-flex items-center px-3 py-1 bg-gradient-to-r from-blue-500 to-purple-600 text-white text-xs font-medium rounded-full"> {selectedConfig.modelAdapter} </span> </div> </div> <div className="bg-white rounded-lg p-3 border"> <span className="font-medium text-gray-600">多模态:</span> <div className="flex items-center"> {selectedConfig.isMultimodal ? ( <span className="inline-flex items-center px-2 py-1 bg-green-100 text-green-800 text-xs font-medium rounded-full"> ✓ 支持 </span> ) : ( <span className="inline-flex items-center px-2 py-1 bg-gray-100 text-gray-800 text-xs font-medium rounded-full"> ✗ 不支持 </span> )} </div> </div> <div className="bg-white rounded-lg p-3 border"> <span className="font-medium text-gray-600">温度:</span> <div className="text-gray-800">{selectedConfig.temperature}</div> </div> <div className="bg-white rounded-lg p-3 border"> <span className="font-medium text-gray-600">最大Token:</span> <div className="text-gray-800">{selectedConfig.maxOutputTokens}</div> </div> </div> </div> )} </div> </div> {/* 测试输入区域 */} <div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden"> <div className="bg-gradient-to-r from-green-500 to-teal-600 p-6 text-white"> <h2 className="text-xl font-bold flex items-center"> <span className="mr-3">📝</span> 测试输入配置 </h2> </div> <div className="p-6 space-y-6"> {/* 测试提示词 */} <div> <label className="block text-sm font-semibold text-gray-700 mb-3">测试提示词</label> <textarea className="w-full p-4 border-2 border-gray-200 rounded-lg focus:border-green-500 focus:ring-2 focus:ring-green-200 transition-all duration-200 resize-vertical bg-white" value={testPrompt} onChange={(e) => setTestPrompt(e.target.value)} rows={4} placeholder="输入测试提示词,用于验证适配器功能..." /> </div> {/* 图片上传 */} {selectedConfig?.isMultimodal && ( <div> <label className="block text-sm font-semibold text-gray-700 mb-3">上传测试图片(多模态测试)</label> <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 hover:border-green-400 transition-colors duration-200"> <div className="flex items-center justify-center"> <div className="text-center"> <input type="file" accept="image/*" onChange={handleImageUpload} className="hidden" id="image-upload" /> <label htmlFor="image-upload" className="cursor-pointer inline-flex items-center px-4 py-2 bg-gradient-to-r from-green-500 to-teal-600 text-white rounded-lg hover:from-green-600 hover:to-teal-700 transition-all duration-200" > <span className="mr-2">📷</span> 选择图片 </label> <p className="text-gray-500 text-sm mt-2">支持 JPG、PNG 等格式</p> </div> {imagePreview && ( <div className="ml-6"> <img src={imagePreview} alt="Preview" className="h-24 w-24 object-cover rounded-lg border-2 border-green-200 shadow-md" /> </div> )} </div> </div> </div> )} </div> </div> {/* 测试控制区域 */} <div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden"> <div className="bg-gradient-to-r from-purple-500 to-pink-600 p-6 text-white"> <h2 className="text-xl font-bold flex items-center"> <span className="mr-3">🚀</span> 测试控制 </h2> </div> <div className="p-6"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4"> <button onClick={runAllTests} disabled={Object.values(isLoading).some(v => v)} className="w-full px-6 py-4 bg-gradient-to-r from-purple-500 to-pink-600 text-white rounded-lg hover:from-purple-600 hover:to-pink-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 flex items-center justify-center font-semibold" > {Object.values(isLoading).some(v => v) ? ( <> <div className="animate-spin rounded-full h-5 w-5 border-2 border-white border-t-transparent mr-3"></div> 测试进行中... </> ) : ( <> <span className="mr-2">🧪</span> 运行所有测试 </> )} </button> <button onClick={() => { setTestResults({}); setStreamingContent(''); }} className="w-full px-6 py-4 bg-gradient-to-r from-gray-500 to-gray-600 text-white rounded-lg hover:from-gray-600 hover:to-gray-700 transition-all duration-200 flex items-center justify-center font-semibold" > <span className="mr-2">🗑️</span> 清除测试结果 </button> </div> {/* 日志管理区域 */} <div className="border-t border-gray-200 pt-4"> <h4 className="text-sm font-semibold text-gray-700 mb-3 flex items-center"> <span className="mr-2">📄</span> 测试日志管理 </h4> <div className="grid grid-cols-1 md:grid-cols-3 gap-3"> <button onClick={loadTestLogs} className="px-4 py-2 bg-gradient-to-r from-blue-500 to-indigo-600 text-white rounded-lg hover:from-blue-600 hover:to-indigo-700 transition-all duration-200 flex items-center justify-center text-sm font-medium" > <span className="mr-1">🔄</span> 刷新日志列表 </button> <button onClick={() => { if (currentLogPath) { invoke('open_log_file', { logPath: currentLogPath }); } }} disabled={!currentLogPath} className="px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-lg hover:from-green-600 hover:to-emerald-700 disabled:opacity-50 transition-all duration-200 flex items-center justify-center text-sm font-medium" > <span className="mr-1">📂</span> 打开最新日志 </button> <button onClick={() => { invoke('open_logs_folder', { logType: 'gemini-adapter-test' }); }} className="px-4 py-2 bg-gradient-to-r from-yellow-500 to-orange-600 text-white rounded-lg hover:from-yellow-600 hover:to-orange-700 transition-all duration-200 flex items-center justify-center text-sm font-medium" > <span className="mr-1">📁</span> 打开日志文件夹 </button> </div> {/* 当前日志路径显示 */} {currentLogPath && ( <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg"> <p className="text-xs text-blue-700"> <span className="font-semibold">最新日志:</span> {currentLogPath} </p> </div> )} {/* 历史日志列表 */} {allTestLogs.length > 0 && ( <div className="mt-4"> <h5 className="text-xs font-semibold text-gray-600 mb-2"> 历史测试日志 ({allTestLogs.length} 个文件) </h5> <div className="max-h-32 overflow-y-auto bg-gray-50 rounded-lg border"> {allTestLogs.slice(0, 10).map((logPath, index) => ( <div key={index} className="px-3 py-2 border-b border-gray-200 last:border-b-0 hover:bg-gray-100 cursor-pointer transition-colors duration-150" onClick={() => { invoke('open_log_file', { logPath }); }} > <p className="text-xs text-gray-700 font-mono truncate"> {logPath.split('/').pop()} </p> </div> ))} {allTestLogs.length > 10 && ( <div className="px-3 py-2 text-xs text-gray-500 italic"> ... 还有 {allTestLogs.length - 10} 个日志文件 </div> )} </div> </div> )} </div> </div> </div> {/* 单项测试 */} <div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden"> <div className="bg-gradient-to-r from-indigo-500 to-blue-600 p-6 text-white"> <h2 className="text-xl font-bold flex items-center"> <span className="mr-3">🔬</span> 单项测试 </h2> <p className="text-blue-100 mt-1">分别验证适配器的各项功能</p> </div> <div className="p-6 space-y-4"> {/* 基础连接测试 */} <div className="bg-gradient-to-r from-gray-50 to-gray-100 rounded-lg p-4 border border-gray-200"> <div className="flex items-center justify-between"> {renderTestResult('basic', '🔗 基础连接测试')} <button onClick={testBasicConnection} disabled={isLoading.basic} className="px-4 py-2 bg-gradient-to-r from-blue-500 to-indigo-600 text-white rounded-lg hover:from-blue-600 hover:to-indigo-700 disabled:opacity-50 transition-all duration-200 flex items-center text-sm font-medium" > {isLoading.basic ? ( <div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent mr-2"></div> ) : ( <span className="mr-1">▶️</span> )} 测试 </button> </div> </div> {/* 非流式转换测试 */} <div className="bg-gradient-to-r from-green-50 to-emerald-100 rounded-lg p-4 border border-green-200"> <div className="flex items-center justify-between"> {renderTestResult('nonStreaming', '📤 OpenAI → Gemini 非流式转换测试')} <button onClick={testNonStreamingChat} disabled={isLoading.nonStreaming} className="px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-lg hover:from-green-600 hover:to-emerald-700 disabled:opacity-50 transition-all duration-200 flex items-center text-sm font-medium" > {isLoading.nonStreaming ? ( <div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent mr-2"></div> ) : ( <span className="mr-1">▶️</span> )} 测试 </button> </div> </div> {/* 流式转换测试 */} <div className="bg-gradient-to-r from-purple-50 to-violet-100 rounded-lg p-4 border border-purple-200"> <div className="flex items-center justify-between"> {renderTestResult('streaming', '🌊 OpenAI → Gemini 流式转换测试')} <button onClick={testStreamingChat} disabled={isLoading.streaming} className="px-4 py-2 bg-gradient-to-r from-purple-500 to-violet-600 text-white rounded-lg hover:from-purple-600 hover:to-violet-700 disabled:opacity-50 transition-all duration-200 flex items-center text-sm font-medium" > {isLoading.streaming ? ( <div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent mr-2"></div> ) : ( <span className="mr-1">▶️</span> )} 测试 </button> </div> </div> {/* 多模态转换测试 */} {selectedConfig?.isMultimodal && ( <div className="bg-gradient-to-r from-orange-50 to-amber-100 rounded-lg p-4 border border-orange-200"> <div className="flex items-center justify-between"> {renderTestResult('multimodal', '🖼️ OpenAI → Gemini 多模态转换测试')} <button onClick={testMultimodal} disabled={isLoading.multimodal || !imageBase64} className="px-4 py-2 bg-gradient-to-r from-orange-500 to-amber-600 text-white rounded-lg hover:from-orange-600 hover:to-amber-700 disabled:opacity-50 transition-all duration-200 flex items-center text-sm font-medium" > {isLoading.multimodal ? ( <div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent mr-2"></div> ) : ( <span className="mr-1">▶️</span> )} 测试 </button> </div> {!imageBase64 && ( <div className="mt-2 text-xs text-orange-600"> 💡 需要先上传图片才能进行多模态测试 </div> )} </div> )} </div> </div> {/* 流式响应内容显示 */} {streamingContent && ( <div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden"> <div className="bg-gradient-to-r from-green-500 to-emerald-600 p-4 text-white"> <h3 className="text-lg font-bold flex items-center"> <span className="mr-2">🌊</span> 流式响应内容 </h3> </div> <div className="p-6"> <div className="bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg p-6 max-h-96 overflow-y-auto border-2 border-gray-200"> <div className="font-mono text-sm leading-relaxed text-gray-800 whitespace-pre-wrap"> {streamingContent} </div> </div> </div> </div> )} {/* 测试结果详情 */} {Object.entries(testResults).some(([key, result]) => result.details) && ( <div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden"> <div className="bg-gradient-to-r from-indigo-500 to-purple-600 p-4 text-white"> <h3 className="text-lg font-bold flex items-center"> <span className="mr-2">📊</span> 测试结果详情 </h3> </div> <div className="p-6 space-y-4"> {Object.entries(testResults).map(([key, result]) => ( result.details && ( <div key={key} className="border border-gray-200 rounded-lg overflow-hidden"> <div className="bg-gray-50 px-4 py-3 border-b border-gray-200"> <h4 className="font-semibold text-gray-800 capitalize">{key} 测试详情</h4> </div> <div className="p-4"> <div className="bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg p-4 max-h-60 overflow-y-auto"> <pre className="text-xs text-gray-700 whitespace-pre-wrap font-mono leading-relaxed"> {JSON.stringify(result.details, null, 2)} </pre> </div> </div> </div> ) ))} </div> </div> )} {/* 说明信息 */} <div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden"> <div className="bg-gradient-to-r from-cyan-500 to-blue-600 p-6 text-white"> <h3 className="text-xl font-bold flex items-center"> <span className="mr-3">📚</span> 测试说明 </h3> </div> <div className="p-6"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="bg-gradient-to-br from-blue-50 to-cyan-50 rounded-lg p-4 border border-blue-200"> <h4 className="font-semibold text-blue-800 mb-2 flex items-center"> <span className="mr-2">🔗</span> 基础连接测试 </h4> <p className="text-blue-700 text-sm">验证API密钥和端点是否有效,确保网络连接正常</p> </div> <div className="bg-gradient-to-br from-green-50 to-emerald-50 rounded-lg p-4 border border-green-200"> <h4 className="font-semibold text-green-800 mb-2 flex items-center"> <span className="mr-2">📤</span> 非流式转换测试 </h4> <p className="text-green-700 text-sm">验证OpenAI格式能否正确转换为Gemini API调用</p> </div> <div className="bg-gradient-to-br from-purple-50 to-violet-50 rounded-lg p-4 border border-purple-200"> <h4 className="font-semibold text-purple-800 mb-2 flex items-center"> <span className="mr-2">🌊</span> 流式转换测试 </h4> <p className="text-purple-700 text-sm">验证OpenAI流式格式能否正确转换为Gemini流式API调用</p> </div> <div className="bg-gradient-to-br from-orange-50 to-amber-50 rounded-lg p-4 border border-orange-200"> <h4 className="font-semibold text-orange-800 mb-2 flex items-center"> <span className="mr-2">🖼️</span> 多模态转换测试 </h4> <p className="text-orange-700 text-sm">验证OpenAI多模态格式能否正确转换为Gemini多模态API调用</p> </div> </div> <div className="mt-6 p-4 bg-gradient-to-r from-yellow-100 to-orange-100 rounded-lg border border-yellow-300"> <div className="flex items-start"> <span className="text-2xl mr-3">💡</span> <div> <h4 className="font-semibold text-yellow-800 mb-1">使用提示</h4> <p className="text-yellow-700 text-sm"> 确保已在设置中正确配置了Gemini API密钥和端点。 测试前请检查网络连接是否正常。 所有测试都会验证适配器是否能正确处理OpenAI兼容格式并转换为Gemini API调用。 </p> </div> </div> </div> </div> </div> </div> </div> ); };
48,374
GeminiAdapterTest
tsx
en
tsx
code
{"qsc_code_num_words": 4721, "qsc_code_num_chars": 48374.0, "qsc_code_mean_word_length": 5.3882652, "qsc_code_frac_words_unique": 0.13132811, "qsc_code_frac_chars_top_2grams": 0.04670178, "qsc_code_frac_chars_top_3grams": 0.02712477, "qsc_code_frac_chars_top_4grams": 0.01533139, "qsc_code_frac_chars_dupe_5grams": 0.52366538, "qsc_code_frac_chars_dupe_6grams": 0.48282098, "qsc_code_frac_chars_dupe_7grams": 0.44681186, "qsc_code_frac_chars_dupe_8grams": 0.41803601, "qsc_code_frac_chars_dupe_9grams": 0.38076893, "qsc_code_frac_chars_dupe_10grams": 0.34208664, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03182781, "qsc_code_frac_chars_whitespace": 0.3459503, "qsc_code_size_file_byte": 48374.0, "qsc_code_num_lines": 1236.0, "qsc_code_num_chars_line_max": 275.0, "qsc_code_num_chars_line_mean": 39.13754045, "qsc_code_frac_chars_alphabet": 0.77047315, "qsc_code_frac_chars_comments": 0.01649647, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.48134668, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.05186533, "qsc_code_frac_chars_string_length": 0.24162936, "qsc_code_frac_chars_long_word_length": 0.01227484, "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/ReviewAnalysisSessionView.tsx
import React, { useState, useEffect, useCallback, useRef } from 'react'; import { useNotification } from '../hooks/useNotification'; import { TauriAPI, ReviewAnalysisItem } from '../utils/tauriApi'; import UniversalAppChatHost from './UniversalAppChatHost'; interface ReviewAnalysisSessionViewProps { sessionId: string; onBack: () => void; } /** * 新的回顾分析详情页 - 完全复用错题分析的逻辑和模式 */ const ReviewAnalysisSessionView: React.FC<ReviewAnalysisSessionViewProps> = ({ sessionId, onBack, }) => { console.log('🔍 ReviewAnalysisSessionView 渲染, sessionId:', sessionId); // 使用数据库模式,复用错题分析的状态管理 const [reviewAnalysis, setReviewAnalysis] = useState<ReviewAnalysisItem | null>(null); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null); const { showNotification } = useNotification(); // 用于存储最新的聊天历史状态 const [latestChatHistory, setLatestChatHistory] = useState<any[]>([]); // 定时保存的引用 const autoSaveTimerRef = useRef<NodeJS.Timeout | null>(null); // 从数据库加载回顾分析(复用错题分析的加载模式) const loadReviewAnalysis = useCallback(async () => { try { setLoading(true); setError(null); console.log('🔍 从数据库加载回顾分析:', sessionId); const analysis = await TauriAPI.getReviewAnalysisById(sessionId); if (analysis) { console.log('✅ 成功加载回顾分析:', analysis); setReviewAnalysis(analysis); } else { console.error('❌ 未找到回顾分析:', sessionId); setError('未找到指定的回顾分析'); } } catch (error) { console.error('加载回顾分析失败:', error); setError(String(error)); showNotification('error', '加载回顾分析失败'); } finally { setLoading(false); } }, [sessionId, showNotification]); useEffect(() => { loadReviewAnalysis(); }, [loadReviewAnalysis]); // 🎯 保存聊天历史的辅助函数 const saveReviewAnalysisData = useCallback(async (chatHistory: any[], context: string) => { if (!reviewAnalysis || chatHistory.length === 0) return; try { console.log(`🔄 [${context}] 保存聊天历史,数量:`, chatHistory.length); const updatedAnalysis = { ...reviewAnalysis, chat_history: chatHistory, status: 'completed' as const, updated_at: new Date().toISOString() }; // 🎯 首选方案:使用新的更新API try { await TauriAPI.updateReviewAnalysis(updatedAnalysis); console.log(`✅ [${context}] 聊天历史保存成功 (直接更新)`); return; } catch (updateError) { console.log(`⚠️ [${context}] 直接更新失败,尝试变通方案:`, updateError); } // 🎯 变通方案:使用追问API(它会自动保存聊天历史) await TauriAPI.continueReviewChatStream({ reviewId: reviewAnalysis.id, chatHistory: chatHistory, enableChainOfThought: true, enableRag: false, ragTopK: 5 }); console.log(`✅ [${context}] 聊天历史保存成功 (变通方案)`); } catch (error) { console.error(`❌ [${context}] 保存聊天历史失败:`, error); } }, [reviewAnalysis]); // 🎯 新增:页面卸载时保存最新的聊天历史 useEffect(() => { const handleBeforeUnload = () => { if (latestChatHistory.length > 0) { // beforeunload 不能使用 async,所以只能发起请求 saveReviewAnalysisData(latestChatHistory, '页面卸载').catch(console.error); } }; // 监听页面卸载事件 window.addEventListener('beforeunload', handleBeforeUnload); // 组件卸载时的清理 return () => { window.removeEventListener('beforeunload', handleBeforeUnload); // 清理定时器 if (autoSaveTimerRef.current) { clearTimeout(autoSaveTimerRef.current); autoSaveTimerRef.current = null; } // 组件卸载时保存(非async) if (latestChatHistory.length > 0) { console.log('🔄 [组件卸载] 尝试保存最新聊天历史'); saveReviewAnalysisData(latestChatHistory, '组件卸载').catch(console.error); } }; }, [latestChatHistory, saveReviewAnalysisData]); // 保存回顾分析到数据库(复用错题分析的保存模式) const handleSaveReviewAnalysis = useCallback(async (updatedAnalysis: ReviewAnalysisItem) => { try { // 注意:后端API已经自动保存,这里主要是更新本地状态 setReviewAnalysis(updatedAnalysis); console.log('✅ 回顾分析状态已更新'); } catch (error) { console.error('更新回顾分析状态失败:', error); showNotification('error', '更新状态失败'); } }, [showNotification]); // 加载中状态 if (loading) { return ( <div className="flex justify-center items-center h-64"> <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div> <span className="ml-2 text-gray-600">加载中...</span> </div> ); } // 错误状态 if (error || !reviewAnalysis) { return ( <div className="text-center py-12"> <h3 className="text-lg font-medium text-red-700 mb-2">加载失败</h3> <p className="text-gray-600 mb-4"> {error || '未找到回顾分析'} </p> <button onClick={onBack} className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors" > 返回列表 </button> </div> ); } // 主界面 - 使用UniversalAppChatHost,完全复用错题分析的逻辑 return ( <UniversalAppChatHost mode="REVIEW_SESSION_DETAIL" businessSessionId={reviewAnalysis.id} preloadedData={{ subject: reviewAnalysis.subject, userQuestion: reviewAnalysis.user_question, ocrText: reviewAnalysis.consolidated_input, tags: reviewAnalysis.mistake_ids, // 使用mistake_ids作为标签 chatHistory: reviewAnalysis.chat_history || [], thinkingContent: new Map(), // 从聊天历史中恢复思维链 status: reviewAnalysis.status, }} serviceConfig={{ apiProvider: { initiateAndGetStreamId: async () => ({ streamIdForEvents: reviewAnalysis.id, ocrResultData: { ocr_text: reviewAnalysis.consolidated_input, tags: reviewAnalysis.mistake_ids, mistake_type: reviewAnalysis.analysis_type }, initialMessages: reviewAnalysis.chat_history || [] }), startMainStreaming: async (params) => { // 根据回顾分析状态决定是否启动流式处理 const needsInitialAnalysis = !reviewAnalysis.chat_history || reviewAnalysis.chat_history.length === 0 || reviewAnalysis.status === 'pending' || reviewAnalysis.status === 'analyzing'; if (needsInitialAnalysis) { console.log('🚀 启动回顾分析流式处理'); try { await TauriAPI.triggerConsolidatedReviewStream({ review_session_id: reviewAnalysis.id, enable_chain_of_thought: params.enableChainOfThought, enable_rag: params.enableRag, rag_options: params.enableRag ? { top_k: params.ragTopK } : undefined }); console.log('✅ 回顾分析流式处理已启动'); } catch (error) { console.error('❌ 启动回顾分析流式处理失败:', error); throw error; } } else { console.log('ℹ️ 回顾分析已完成,无需启动流式处理'); } }, continueUserChat: async (params) => { // 使用新的API进行追问(自动保存到数据库) await TauriAPI.continueReviewChatStream({ reviewId: params.businessId, chatHistory: params.fullChatHistory, enableChainOfThought: params.enableChainOfThought, enableRag: params.enableRag, ragTopK: params.ragTopK }); } }, streamEventNames: { initialStream: (id) => ({ data: `review_analysis_stream_${id}`, reasoning: `review_analysis_stream_${id}_reasoning`, ragSources: `review_analysis_stream_${id}_rag_sources` }), // 🎯 修复:追问使用不同的事件名称,参考错题分析的正确实现 continuationStream: (id) => ({ data: `review_chat_stream_${id}`, reasoning: `review_chat_stream_${id}_reasoning`, ragSources: `review_chat_stream_${id}_rag_sources` }), }, defaultEnableChainOfThought: true, defaultEnableRag: false, defaultRagTopK: 5, }} onCoreStateUpdate={(data) => { // 🎯 实现状态更新监听,主要用于调试和状态同步 console.log('🔄 [回顾分析] 核心状态更新:', { sessionId, chatHistoryLength: data.chatHistory?.length || 0, thinkingContentSize: data.thinkingContent?.size || 0, isAnalyzing: data.isAnalyzing, isChatting: data.isChatting }); // 🎯 关键修复:保存最新的聊天历史到状态中 if (data.chatHistory) { setLatestChatHistory(data.chatHistory); // 🎯 新增:设置定时自动保存(防抖) if (autoSaveTimerRef.current) { clearTimeout(autoSaveTimerRef.current); } // 30秒后自动保存 autoSaveTimerRef.current = setTimeout(() => { if (data.chatHistory.length > 0) { console.log('🕒 [定时保存] 触发自动保存'); saveReviewAnalysisData(data.chatHistory, '定时保存').catch(console.error); } }, 30000); // 30秒定时保存 } // 更新本地状态 if (data.chatHistory && data.chatHistory.length > 0) { setReviewAnalysis(prev => prev ? { ...prev, chat_history: data.chatHistory, status: 'completed', updated_at: new Date().toISOString() } : prev); } }} onSaveRequest={async (data) => { try { console.log('💾 回顾分析手动保存请求,数据:', data); // 🎯 使用新的保存函数 await saveReviewAnalysisData(data.chatHistory, '手动保存'); // 更新本地状态 setReviewAnalysis(prev => prev ? { ...prev, chat_history: data.chatHistory, status: 'completed', updated_at: new Date().toISOString() } : prev); showNotification('success', '回顾分析已保存'); } catch (error) { console.error('❌ 手动保存回顾分析失败:', error); showNotification('error', '保存失败: ' + error); } }} onExitRequest={onBack} /> ); }; export default ReviewAnalysisSessionView;
10,173
ReviewAnalysisSessionView
tsx
en
tsx
code
{"qsc_code_num_words": 786, "qsc_code_num_chars": 10173.0, "qsc_code_mean_word_length": 7.40839695, "qsc_code_frac_words_unique": 0.37659033, "qsc_code_frac_chars_top_2grams": 0.02575992, "qsc_code_frac_chars_top_3grams": 0.0094453, "qsc_code_frac_chars_top_4grams": 0.01889061, "qsc_code_frac_chars_dupe_5grams": 0.12639533, "qsc_code_frac_chars_dupe_6grams": 0.07556242, "qsc_code_frac_chars_dupe_7grams": 0.05495449, "qsc_code_frac_chars_dupe_8grams": 0.03469002, "qsc_code_frac_chars_dupe_9grams": 0.03469002, "qsc_code_frac_chars_dupe_10grams": 0.03469002, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.007174, "qsc_code_frac_chars_whitespace": 0.30118942, "qsc_code_size_file_byte": 10173.0, "qsc_code_num_lines": 312.0, "qsc_code_num_chars_line_max": 102.0, "qsc_code_num_chars_line_mean": 32.60576923, "qsc_code_frac_chars_alphabet": 0.80784921, "qsc_code_frac_chars_comments": 0.06124054, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.25506073, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00809717, "qsc_code_frac_chars_string_length": 0.07842111, "qsc_code_frac_chars_long_word_length": 0.0096325, "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}
0000cd/wolf-set
data/cards.yaml
# https://github.com/0000cd/wolf-set - title: 欢迎回来 hex: "#0000cd" tags: - 置顶 date: 24/04 description: 狼集 Wolf Set:宇宙总需要些航天器,“📀各位都好吧?” 让我们路过些互联网小行星。 links: - name: 关于 url: https://ws.0000cd.com/posts/about/ - name: GitHub url: https://github.com/0000cd/wolf-set - name: 网站统计 url: https://eu.umami.is/share/inDFetQGPNU7eUt4/ws.0000cd.com media: - url: https://player.bilibili.com/player.html?isOutside=true&aid=113680083655495&bvid=BV1oFkBY1EjF&cid=27425508078&p=1 - url: met/?id=137470856 - title: TGAGWCAGA hex: "#0583ab" tags: - 置顶 - 有趣 date: 24/12 description: 为付不起 TGA 的游戏设立的 TGA。The Game Awards for Games Who Can't Afford the Game Awards. links: - name: 官网 url: https://tgagwcaga.com/ - name: 获奖提名 url: https://tgagwcaga.com/nominees/ - name: Steam 特卖! url: https://store.steampowered.com/curator/45328769-The-Great-Awards-for-Games-With-Creative/sale/tgagwcaga - title: indienova hex: "#ef4c26" tags: - 置顶 date: 24/12 description: 独立游戏新闻、评测、开发、教学。提示,点击图片查看画廊。 links: - name: 官网 url: https://indienova.com - name: 折扣 url: https://indienova.com/steam/discount/4-0-0-0-0-0-0-0-0/p/1 - name: 游戏库 url: https://indienova.com/gamedb - name: 三相奇谈 url: https://store.steampowered.com/app/3084280/_/?l=schinese media: - url: https://player.bilibili.com/player.html?isOutside=true&aid=113309357447966&bvid=BV1ABmnYsEYu&autoplay=0 - title: 夸克 hex: "#0d53ff" tags: - 置顶 date: 24/04 description: 搜索有AI,扫描自动校正,网盘文件找得快,做你学习、工作、生活的高效拍档!手机电视电脑都能用。 links: - name: 夸克 url: https://www.quark.cn/ - name: 网盘 url: https://pan.quark.cn/ - name: 扫描 url: https://scan.quark.cn/ - title: 阿里云 hex: "#ff6a00" tags: - 置顶 - 开发 date: 24/04 description: 新老用户服务器一年99!3分钟部署 AI 或联机游戏,更有学生特惠。 links: - name: 服务器 99 url: https://www.aliyun.com/minisite/goods?userCode=chvg06mh - name: AI 软件游戏 url: https://computenest.aliyun.com/services/all?userCode=chvg06mh - name: 学生特惠 url: https://developer.aliyun.com/plan/student?userCode=chvg06mh media: - url: https://player.bilibili.com/player.html?isOutside=true&aid=113309357447966&bvid=BV1ABmnYsEYu&autoplay=0 # 正文 - title: DOOM CAPTCHA hex: "#4285f4" tags: - 网页 - 有趣 date: "2025/01" description: 打通 DOOM 证明你是人类。 links: https://doom-captcha.vercel.app/ - title: Button Stealer hex: "#ff5100" tags: - 网页 - 有趣 - 开源 date: "2024/12" description: 从路过的每个网页“窃取”按钮,欣赏你的按钮藏品。 links: - name: 官网 url: https://anatolyzenkov.com/stolen-buttons/button-stealer - name: GitHub url: https://github.com/anatolyzenkov/button-stealer - name: 藏品? url: https://anatolyzenkov.com/stolen-buttons - title: cobalt hex: "#000000" tags: - 网页 - 工具 - 开源 date: "2024/12" description: 一键下载网页上的媒体文件。 links: - name: 官网 url: https://cobalt.tools/ - name: GitHub url: https://github.com/imputnet/cobalt - name: 赞助 url: https://liberapay.com/imput - title: GOODY-2 hex: "#EBF38D" tags: - 网页 - AI - 有趣 date: "2024/12" description: 与世界上“最负责”的 AI 聊天。 links: https://www.goody2.ai/chat - title: SONOTELLER.AI hex: "#fcac45" tags: - 网页 - 声音 - AI date: "2024/12" description: 听懂歌的 AI,分析曲风情绪歌词等音乐的一切。 links: https://sonoteller.ai/ - title: Wappalyzer hex: "#4608AD" tags: - 网页 - 开发 date: "2024/12" description: 识别任意网页的技术栈。 links: https://www.wappalyzer.com/ - title: Neal.fun hex: "#ffc7c7" tags: - 网页 - 有趣 date: "2024/12" description: 希望你有美好的一天… 游戏互动可视化等其他奇怪的东西。 links: - name: 官网 url: https://neal.fun/ - name: 设置密码? url: https://neal.fun/password-game/ - name: 赞助 url: https://buymeacoffee.com/neal - title: Wild West hex: "#BBF7D0" tags: - 网页 - 有趣 - AI date: "2024/12" description: 由 AI 驱动的游戏,剪刀石头布。 links: - name: 官网 url: https://www.wildwest.gg/ - name: 击败石头? url: https://www.whatbeatsrock.com/ - title: UniGetUI hex: "#707070" tags: - 桌面 - 开源 - 开发 date: "2024/12" description: 图形化 Windows 全能包管理器。 links: - name: 官网 url: https://www.marticliment.com/unigetui/ - name: GitHub url: https://github.com/marticliment/UniGetUI - name: 赞助 url: https://ko-fi.com/s/290486d079 - title: PowerToys hex: "#666666" tags: - 桌面 - 开源 - 工具 date: "2024/12" description: 一组实用工具,可帮助高级用户调整和简化其 Windows 体验,从而提高工作效率。 links: - name: 官网 url: https://learn.microsoft.com/zh-cn/windows/powertoys/ - name: GitHub url: https://github.com/microsoft/PowerToys - name: 微软商店 url: https://apps.microsoft.com/detail/xp89dcgq3k6vld?hl=zh-cn&gl=CN - title: LocalSend hex: "#008080" tags: - 桌面 - 移动 - 开源 date: "2024/12" description: 全平台 WIFI 分享文件。 links: - name: 官网 url: https://localsend.org/zh-CN - name: GitHub url: https://github.com/localsend/localsend - name: 赞助 url: https://github.com/sponsors/Tienisto # Legacy - title: CSS Diner hex: "#2e2a23" tags: - 网页 - 开发 - 开源 date: "2024/04" description: 练习 CSS 选择器小游戏。 links: - name: 官网 url: https://flukeout.github.io/ - name: GitHub url: https://github.com/flukeout/css-diner - title: Humane by Design hex: "#14151d" tags: - 网页 - 设计 - 想法 date: "2024/04" description: 人性化的数字产品和服务指南。 links: https://humanebydesign.com/ - title: Laws of UX hex: "#0d1e26" tags: - 网页 - 设计 - 想法 date: "2024/04" description: 最佳用户体验 UX 法则合集。 links: https://lawsofux.com/ - title: Checklist Design hex: "#5e4dcd" tags: - 网页 - 设计 - 开发 date: "2024/04" description: 各类页面、组件、流程、设计、品牌等检查清单。 links: https://www.checklist.design/ - title: Method of Action hex: "#333647" tags: - 网页 - 设计 - 有趣 - 开源 date: "2024/04" description: 练习布尔运算、贝塞尔曲线、色轮、字体设计等小游戏。 links: - name: 官网 url: https://method.ac/ - name: GitHub url: https://github.com/methodofaction/Method-Draw - name: 赞助 url: https://method.ac/donate/ - title: Unsplash hex: "#000000" tags: - 推荐 - 网页 - 图片 date: "2024/04" description: 全球摄影师 300万 高清免费图片。 links: - name: 官网 url: https://unsplash.com - name: 背景 url: https://unsplash.com/backgrounds - name: 壁纸 url: https://unsplash.com/wallpapers - title: The Useless Web hex: "#ff1493" tags: - 推荐 - 网页 - 有趣 date: "2024/04" description: 随机打开网上有趣而无用的网站。 links: https://theuselessweb.com - title: i Hate Regex hex: "#e53e3e" tags: - 网页 - 开源 - 开发 date: "2024/04" description: 帮助讨厌复杂正则表达式的人理解和使用它们,现在你有两个问题了。 links: - name: 官网 url: https://ihateregex.io/ - name: GitHub url: https://github.com/geongeorge/i-hate-regex - name: 赞助 url: https://opencollective.com/ihateregex - title: Msgif hex: "#7880dd" tags: - 网页 - 动图 - 有趣 date: "2024/04" description: 打字过程转换成动图,见字如面。 links: https://msgif.net/ - title: Exploding Topics hex: "#2e5ce5" tags: - 网页 - 搜索 - 想法 date: "2024/04" description: 寻找快速增长与有潜力的科技话题。 links: https://explodingtopics.com/ - title: 100font.com hex: "#f7c601" tags: - 推荐 - 网页 - 字体 date: "2024/04" description: 一个专门收集整理“免费商用字体”的网站,有大量中文字体。 links: https://www.100font.com - title: Recompressor hex: "#3755dc" tags: - 推荐 - 网页 - 工具 - 图片 date: "2024/04" description: 智能压缩技术,优化图片质量与尺寸,多种图像工具。 links: - name: 压缩 url: https://zh.recompressor.com/ - name: 修复 url: https://zh.pixfix.com/ - name: 检查 url: https://zh.pixspy.com/ - title: No More Ransom hex: "#102a87" tags: - 网页 - 安全 date: "2024/04" description: 提供数十种免费的解密工具,从勒索病毒中恢复数据。 links: - name: 官网 url: https://www.nomoreransom.org/zh/index.html - name: 知识 url: https://www.nomoreransom.org/zh/ransomware-qa.html - name: 建议 url: https://www.nomoreransom.org/zh/prevention-advice-for-users.html - title: IconKitchen hex: "#6a3de8" tags: - 网页 - 图标 - 开发 date: "2024/04" description: 轻松生成标准的全平台应用图标。 links: https://icon.kitchen - title: Game-icons.net hex: "#000000" tags: - 网页 - 图标 date: "2024/04" description: 4千 CC 授权免费矢量游戏图标。 links: https://game-icons.net/
8,115
cards
yaml
en
yaml
data
{"qsc_code_num_words": 1101, "qsc_code_num_chars": 8115.0, "qsc_code_mean_word_length": 4.69663942, "qsc_code_frac_words_unique": 0.32788374, "qsc_code_frac_chars_top_2grams": 0.08663701, "qsc_code_frac_chars_top_3grams": 0.02900793, "qsc_code_frac_chars_top_4grams": 0.06091665, "qsc_code_frac_chars_dupe_5grams": 0.30206923, "qsc_code_frac_chars_dupe_6grams": 0.16785921, "qsc_code_frac_chars_dupe_7grams": 0.07271321, "qsc_code_frac_chars_dupe_8grams": 0.05994972, "qsc_code_frac_chars_dupe_9grams": 0.04795978, "qsc_code_frac_chars_dupe_10grams": 0.04795978, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.07058089, "qsc_code_frac_chars_whitespace": 0.21084412, "qsc_code_size_file_byte": 8115.0, "qsc_code_num_lines": 422.0, "qsc_code_num_chars_line_max": 122.0, "qsc_code_num_chars_line_mean": 19.22985782, "qsc_code_frac_chars_alphabet": 0.73625859, "qsc_code_frac_chars_comments": 0.00591497, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.50393701, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.04946077, "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/EnhancedKnowledgeBaseManagement.tsx
import React, { useState, useEffect, useCallback } from 'react'; import { TauriAPI } from '../utils/tauriApi'; import { useNotification } from '../hooks/useNotification'; import './EnhancedKnowledgeBaseManagement.css'; import type { RagDocument, KnowledgeBaseStatusPayload, RagProcessingEvent, RagDocumentStatusEvent } from '../types'; import { listen } from '@tauri-apps/api/event'; import './KnowledgeBaseManagement.css'; import { FileText, Edit, Trash2, BookOpen, Lightbulb, X, Upload, FolderOpen } from 'lucide-react'; // 添加CSS动画样式 const animationKeyframes = ` @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } @keyframes shimmer { 0% { transform: translateX(-100%); } 100% { transform: translateX(100%); } } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.7; } } `; // 将样式注入到页面中 if (typeof document !== 'undefined') { const styleElement = document.createElement('style'); styleElement.textContent = animationKeyframes; document.head.appendChild(styleElement); } // 进度条组件 interface ProgressBarProps { progress: number; status: string; fileName: string; stage?: string; totalChunks?: number; currentChunk?: number; chunksProcessed?: number; } const ProgressBar: React.FC<ProgressBarProps> = ({ progress, status, fileName, stage, totalChunks, currentChunk, chunksProcessed }) => { const getStatusColor = (status: string) => { switch (status) { case 'Reading': return '#3b82f6'; // 蓝色 case 'Preprocessing': return '#8b5cf6'; // 紫色 case 'Chunking': return '#f59e0b'; // 橙色 case 'Embedding': return '#10b981'; // 绿色 case 'Storing': return '#06b6d4'; // 青色 case 'Completed': return '#22c55e'; // 成功绿色 case 'Failed': return '#ef4444'; // 错误红色 default: return '#6b7280'; // 灰色 } }; const getStageText = (status: string) => { switch (status) { case 'Reading': return '📖 读取文件'; case 'Preprocessing': return '🔧 预处理'; case 'Chunking': return '✂️ 文本分块'; case 'Embedding': return '🧠 生成向量'; case 'Storing': return '💾 存储数据'; case 'Completed': return '✅ 处理完成'; case 'Failed': return '❌ 处理失败'; default: return '⏳ 处理中'; } }; return ( <div style={{ background: 'white', border: '1px solid #e5e7eb', borderRadius: '12px', padding: '16px', marginBottom: '12px', boxShadow: '0 2px 4px rgba(0, 0, 0, 0.05)' }}> <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}> <div style={{ fontSize: '14px', fontWeight: '600', color: '#374151', display: 'flex', alignItems: 'center', gap: '8px' }}> <FileText size={16} /> {fileName} </div> <div style={{ fontSize: '12px', color: '#6b7280', fontWeight: '500' }}> {Math.round(progress * 100)}% </div> </div> <div style={{ fontSize: '12px', color: getStatusColor(status), marginBottom: '8px', fontWeight: '500', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}> <span>{getStageText(status)}</span> {status === 'Chunking' && totalChunks && ( <span style={{ color: '#6b7280', fontSize: '11px' }}> 预计生成 {totalChunks} 个文本块 </span> )} {status === 'Embedding' && chunksProcessed !== undefined && totalChunks && ( <span style={{ color: '#6b7280', fontSize: '11px' }}> 🧠 生成向量: {chunksProcessed} / {totalChunks} </span> )} {status === 'Embedding' && !chunksProcessed && totalChunks && ( <span style={{ color: '#6b7280', fontSize: '11px' }}> 预计生成 {totalChunks} 个向量 </span> )} {status === 'Completed' && totalChunks && ( <span style={{ color: '#22c55e', fontSize: '11px' }}> ✅ 已生成 {totalChunks} 个文本块 </span> )} </div> <div style={{ width: '100%', height: '8px', backgroundColor: '#f3f4f6', borderRadius: '4px', overflow: 'hidden' }}> <div style={{ width: `${progress * 100}%`, height: '100%', backgroundColor: getStatusColor(status), borderRadius: '4px', transition: 'width 0.5s ease, background-color 0.3s ease', background: status === 'Embedding' ? `linear-gradient(90deg, ${getStatusColor(status)}, ${getStatusColor(status)}aa, ${getStatusColor(status)})` : status === 'Reading' || status === 'Preprocessing' || status === 'Chunking' || status === 'Storing' ? `linear-gradient(90deg, ${getStatusColor(status)}, ${getStatusColor(status)}cc)` : getStatusColor(status), position: 'relative', overflow: 'hidden' }}> {(status === 'Embedding' || status === 'Storing') && progress < 1 && ( <div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, background: `linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent)`, animation: 'shimmer 2s infinite', transform: 'translateX(-100%)' }} /> )} </div> </div> {status === 'Failed' && ( <div style={{ marginTop: '8px', fontSize: '12px', color: '#ef4444', background: '#fef2f2', padding: '8px', borderRadius: '6px', border: '1px solid #fecaca' }}> 处理失败,请检查文件格式或重试 </div> )} </div> ); }; // 定义分库接口类型 interface SubLibrary { id: string; name: string; description?: string; created_at: string; updated_at: string; document_count: number; chunk_count: number; } interface CreateSubLibraryRequest { name: string; description?: string; } interface UpdateSubLibraryRequest { name?: string; description?: string; } interface EnhancedKnowledgeBaseManagementProps { className?: string; } export const EnhancedKnowledgeBaseManagement: React.FC<EnhancedKnowledgeBaseManagementProps> = ({ className = '' }) => { // 分库相关状态 const [subLibraries, setSubLibraries] = useState<SubLibrary[]>([]); const [selectedLibrary, setSelectedLibrary] = useState<string>('default'); const [documents, setDocuments] = useState<RagDocument[]>([]); const [status, setStatus] = useState<KnowledgeBaseStatusPayload | null>(null); const [loading, setLoading] = useState(false); const [uploading, setUploading] = useState(false); const [processingDocuments, setProcessingDocuments] = useState<Map<string, RagDocumentStatusEvent>>(new Map()); const [selectedFiles, setSelectedFiles] = useState<File[]>([]); // 分库管理状态 const [showCreateLibraryModal, setShowCreateLibraryModal] = useState(false); const [showEditLibraryModal, setShowEditLibraryModal] = useState(false); const [editingLibrary, setEditingLibrary] = useState<SubLibrary | null>(null); const [newLibraryName, setNewLibraryName] = useState(''); const [newLibraryDescription, setNewLibraryDescription] = useState(''); const { showSuccess, showError, showWarning } = useNotification(); // 拖拽状态 const [isDragOver, setIsDragOver] = useState(false); // 格式化文件大小 const formatFileSize = (bytes?: number) => { if (!bytes) return '未知'; const sizes = ['B', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(1024)); return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]; }; // 格式化日期 const formatDate = (dateString: string) => { return new Date(dateString).toLocaleDateString('zh-CN'); }; // 加载分库列表 const loadSubLibraries = useCallback(async () => { try { const libraries = await TauriAPI.invoke('get_rag_sub_libraries') as SubLibrary[]; setSubLibraries(libraries); } catch (error) { console.error('加载分库列表失败:', error); showError(`加载分库列表失败: ${error}`); } }, [showError]); // 加载知识库状态 const loadKnowledgeBaseStatus = useCallback(async () => { try { setLoading(true); const statusData = await TauriAPI.ragGetKnowledgeBaseStatus(); setStatus(statusData); } catch (error) { console.error('加载知识库状态失败:', error); showError(`加载知识库状态失败: ${error}`); } finally { setLoading(false); } }, [showError]); // 加载指定分库的文档 const loadLibraryDocuments = useCallback(async (libraryId: string) => { try { setLoading(true); const documentsData = await TauriAPI.invoke('get_rag_documents_by_library', { request: { sub_library_id: libraryId === 'default' ? null : libraryId, page: 1, page_size: 100 } }) as RagDocument[]; setDocuments(documentsData); } catch (error) { console.error('加载文档列表失败:', error); showError(`加载文档列表失败: ${error}`); } finally { setLoading(false); } }, [showError]); // 创建新分库 const createSubLibrary = async () => { if (!newLibraryName.trim()) { showError('请输入分库名称'); return; } try { const request: CreateSubLibraryRequest = { name: newLibraryName.trim(), description: newLibraryDescription.trim() || undefined }; await TauriAPI.invoke('create_rag_sub_library', { request }); showSuccess(`分库 "${newLibraryName}" 创建成功`); // 重置表单 setNewLibraryName(''); setNewLibraryDescription(''); setShowCreateLibraryModal(false); // 重新加载分库列表 await loadSubLibraries(); } catch (error) { console.error('创建分库失败:', error); showError(`创建分库失败: ${error}`); } }; // 更新分库 const updateSubLibrary = async () => { if (!editingLibrary || !newLibraryName.trim()) { showError('请输入分库名称'); return; } try { const request: UpdateSubLibraryRequest = { name: newLibraryName.trim(), description: newLibraryDescription.trim() || undefined }; await TauriAPI.updateRagSubLibrary(editingLibrary.id, request); showSuccess(`分库更新成功`); // 重置表单 setNewLibraryName(''); setNewLibraryDescription(''); setShowEditLibraryModal(false); setEditingLibrary(null); // 重新加载分库列表 await loadSubLibraries(); } catch (error) { console.error('更新分库失败:', error); showError(`更新分库失败: ${error}`); } }; // 删除分库 const deleteSubLibrary = async (library: SubLibrary) => { if (library.id === 'default') { showError('不能删除默认分库'); return; } const confirmMessage = `确定要删除分库 "${library.name}" 吗? 分库信息: - 文档数量:${library.document_count} 个 - 文本块数量:${library.chunk_count} 个 ⚠️ 注意:分库删除后,其中的文档将自动移动到默认分库,文档内容不会丢失。 确定要继续吗?`; const confirmDelete = window.confirm(confirmMessage); if (!confirmDelete) return; try { console.log('开始删除分库:', library.id, library.name); await TauriAPI.deleteRagSubLibrary(library.id, false); // 将文档移动到默认分库而不是删除 console.log('分库删除成功,开始刷新数据'); showSuccess(`分库 "${library.name}" 已删除,文档已移动到默认分库`); // 立即从本地状态中移除该分库,提升界面响应速度 setSubLibraries(prev => prev.filter(lib => lib.id !== library.id)); if (selectedLibrary === library.id) { // 切换到默认分库并加载其文档 setSelectedLibrary('default'); await loadLibraryDocuments('default'); } else { // 重新加载当前分库文档 await loadLibraryDocuments(selectedLibrary); } // 同步更新知识库状态 await loadKnowledgeBaseStatus(); } catch (error) { console.error('删除分库失败:', error); showError(`删除分库失败: ${error}`); } }; // 上传文档到指定分库 const uploadDocuments = async () => { if (selectedFiles.length === 0) { showError('请选择要上传的文件'); return; } setUploading(true); try { // 读取文件内容,使用内容模式上传 const documents: Array<{ file_name: string; base64_content: string }> = []; for (const file of selectedFiles) { try { const content = await new Promise<string>((resolve, reject) => { const reader = new FileReader(); reader.onerror = (e) => reject(e); // 根据文件类型选择读取方式 if (file.type === 'text/plain' || file.name.endsWith('.txt') || file.name.endsWith('.md')) { reader.onload = (e) => { const result = e.target?.result as string; resolve(result); }; reader.readAsText(file); } else { // 对于PDF、DOCX等二进制文件,读取为ArrayBuffer然后转换为base64 reader.onload = (e) => { const arrayBuffer = e.target?.result as ArrayBuffer; const uint8Array = new Uint8Array(arrayBuffer); // 分块处理大文件,避免栈溢出 let binary = ''; const chunkSize = 8192; // 8KB chunks for (let i = 0; i < uint8Array.length; i += chunkSize) { const chunk = uint8Array.subarray(i, i + chunkSize); binary += String.fromCharCode.apply(null, Array.from(chunk)); } const base64 = btoa(binary); resolve(base64); }; reader.readAsArrayBuffer(file); } }); documents.push({ file_name: file.name, base64_content: content }); } catch (fileError) { console.error(`处理文件 ${file.name} 失败:`, fileError); showError(`处理文件 ${file.name} 失败`); return; } } if (documents.length === 0) { showError('没有文件被成功处理'); return; } // 使用内容模式上传到分库 await TauriAPI.invoke('rag_add_documents_from_content_to_library', { request: { documents: documents, sub_library_id: selectedLibrary === 'default' ? null : selectedLibrary } }); showSuccess(`成功上传 ${selectedFiles.length} 个文件到分库`); setSelectedFiles([]); // 重新加载当前分库的文档 await loadLibraryDocuments(selectedLibrary); await loadKnowledgeBaseStatus(); } catch (error) { console.error('上传文档失败:', error); let errorMessage = '上传文档失败'; if (typeof error === 'string') { errorMessage = `上传失败: ${error}`; } else if (error instanceof Error) { errorMessage = `上传失败: ${error.message}`; } else if (error && typeof error === 'object' && 'message' in error) { errorMessage = `上传失败: ${(error as any).message}`; } // 提供更有用的错误信息和建议 if (errorMessage.includes('系统找不到指定的文件') || errorMessage.includes('文件不存在')) { errorMessage += '\n\n建议:\n• 文件可能已被移动或删除\n• 请重新选择文件\n• 检查文件名是否包含特殊字符'; } showError(errorMessage); } finally { setUploading(false); } }; // 初始化加载 useEffect(() => { loadSubLibraries(); loadKnowledgeBaseStatus(); }, [loadSubLibraries, loadKnowledgeBaseStatus]); // 当选中的分库改变时,重新加载文档 useEffect(() => { if (selectedLibrary) { loadLibraryDocuments(selectedLibrary); } }, [selectedLibrary, loadLibraryDocuments]); // 监听文档处理事件 useEffect(() => { const setupListeners = async () => { // 监听处理状态更新 await listen<RagProcessingEvent>('rag-processing-status', (event) => { console.log('RAG处理状态:', event.payload); }); // 监听文档状态更新 await listen<RagDocumentStatusEvent>('rag_document_status', (event) => { const data = event.payload; setProcessingDocuments(prev => { const newMap = new Map(prev); newMap.set(data.document_id, data); return newMap; }); if (data.status === 'Completed') { showSuccess(`文档 "${data.file_name}" 处理完成,共生成 ${data.total_chunks} 个文本块`); setTimeout(() => { setProcessingDocuments(prev => { const newMap = new Map(prev); newMap.delete(data.document_id); return newMap; }); }, 3000); } else if (data.status === 'Failed') { const errorMsg = data.error_message || '未知错误'; showError(`文档 "${data.file_name}" 处理失败: ${errorMsg}`); setTimeout(() => { setProcessingDocuments(prev => { const newMap = new Map(prev); newMap.delete(data.document_id); return newMap; }); }, 8000); } }); }; setupListeners(); }, [selectedLibrary, loadLibraryDocuments, loadKnowledgeBaseStatus]); // 文件拖拽处理 const handleDragOver = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = 'copy'; setIsDragOver(true); }; const handleDragEnter = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); setIsDragOver(true); }; const handleDragLeave = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); if (!e.currentTarget.contains(e.relatedTarget as Node)) { setIsDragOver(false); } }; const handleDrop = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); setIsDragOver(false); const files = Array.from(e.dataTransfer.files); const supportedFiles = files.filter(file => { const lowerName = file.name.toLowerCase(); return ( lowerName.endsWith('.pdf') || lowerName.endsWith('.docx') || lowerName.endsWith('.txt') || lowerName.endsWith('.md') ); }); if (supportedFiles.length > 0) { setSelectedFiles(prev => [...prev, ...supportedFiles]); } else { showWarning('请选择支持的文件格式(PDF、DOCX、TXT、MD)'); } }; return ( <div style={{ width: '100%', height: '100%', overflow: 'auto', background: '#f8fafc' }}> {/* 头部区域 - 统一白色样式 */} <div style={{ background: 'white', borderBottom: '1px solid #e5e7eb', padding: '24px 32px', position: 'relative' }}> <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: '4px', background: 'linear-gradient(90deg, #667eea, #764ba2)' }}></div> <div style={{ position: 'relative', zIndex: 1 }}> <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}> <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#667eea" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: '12px' }}> <path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/> <path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/> <path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"/> <path d="M17.599 6.5a3 3 0 0 0 .399-1.375"/> <path d="M6.003 5.125A3 3 0 0 0 6.401 6.5"/> <path d="M3.477 10.896a4 4 0 0 1 .585-.396"/> <path d="M19.938 10.5a4 4 0 0 1 .585.396"/> <path d="M6 18a4 4 0 0 1-1.967-.516"/> <path d="M19.967 17.484A4 4 0 0 1 18 18"/> </svg> <h1 style={{ fontSize: '28px', fontWeight: '700', margin: 0, color: '#1f2937' }}>增强知识库管理</h1> </div> <p style={{ fontSize: '16px', color: '#6b7280', margin: 0, lineHeight: '1.5' }}> 智能管理文档资源,构建强大的RAG知识检索系统 </p> <div style={{ marginTop: '24px', display: 'flex', gap: '12px' }}> <button onClick={() => setShowCreateLibraryModal(true)} style={{ background: '#667eea', border: '1px solid #667eea', color: 'white', padding: '12px 24px', borderRadius: '12px', fontSize: '16px', fontWeight: '600', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: '8px', transition: 'all 0.3s ease', backdropFilter: 'blur(10px)' }} onMouseOver={(e) => { e.currentTarget.style.background = '#5a67d8'; e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 8px 25px rgba(102, 126, 234, 0.4)'; }} onMouseOut={(e) => { e.currentTarget.style.background = '#667eea'; e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = 'none'; }} > <svg style={{ width: '20px', height: '20px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" /> </svg> 创建分库 </button> <button onClick={() => { loadSubLibraries(); loadKnowledgeBaseStatus(); loadLibraryDocuments(selectedLibrary); }} disabled={loading} style={{ background: 'white', border: '1px solid #d1d5db', color: '#374151', padding: '12px 24px', borderRadius: '12px', fontSize: '16px', fontWeight: '600', cursor: loading ? 'not-allowed' : 'pointer', display: 'inline-flex', alignItems: 'center', gap: '8px', transition: 'all 0.3s ease', opacity: loading ? 0.6 : 1 }} onMouseOver={(e) => { if (!loading) { e.currentTarget.style.background = '#f9fafb'; e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 8px 25px rgba(0, 0, 0, 0.1)'; } }} onMouseOut={(e) => { if (!loading) { e.currentTarget.style.background = 'white'; e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = 'none'; } }} > <svg style={{ width: '20px', height: '20px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /> </svg> 刷新 </button> </div> </div> </div> <div className={`knowledge-base-management ${className}`} style={{ padding: '24px', background: 'transparent' }}> {/* 知识库状态概览 */} {status && ( <div className="status-overview"> <div className="status-item"> <span className="label">总文档数:</span> <span className="value">{status.total_documents}</span> </div> <div className="status-item"> <span className="label">总文本块:</span> <span className="value">{status.total_chunks}</span> </div> <div className="status-item"> <span className="label">向量存储:</span> <span className="value">{status.vector_store_type}</span> </div> {status.embedding_model_name && ( <div className="status-item"> <span className="label">嵌入模型:</span> <span className="value">{status.embedding_model_name}</span> </div> )} </div> )} <div className="main-content"> {/* 分库管理侧栏 */} <div className="library-sidebar"> <h3>分库列表</h3> <div className="library-list"> {subLibraries.map(library => ( <div key={library.id} className={`library-item ${selectedLibrary === library.id ? 'selected' : ''}`} onClick={() => setSelectedLibrary(library.id)} > <div className="library-info"> <div className="library-name">{library.name}</div> <div className="library-stats" style={{ display: 'flex', alignItems: 'center', gap: '12px' }}> <span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}> <FileText size={14} /> {library.document_count} </span> <span>|</span> <span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}> <BookOpen size={14} /> {library.chunk_count} </span> </div> {library.description && ( <div className="library-description">{library.description}</div> )} </div> <div className="library-actions"> {library.id !== 'default' && ( <> <button onClick={(e) => { e.stopPropagation(); setEditingLibrary(library); setNewLibraryName(library.name); setNewLibraryDescription(library.description || ''); setShowEditLibraryModal(true); }} className="library-action-btn edit" style={{ display: 'flex', alignItems: 'center', gap: '4px' }} > <Edit size={14} /> </button> <button onClick={(e) => { e.stopPropagation(); deleteSubLibrary(library); }} className="library-action-btn delete" disabled={library.id === 'default'} style={{ display: 'flex', alignItems: 'center', gap: '4px' }} > <Trash2 size={14} /> </button> </> )} </div> </div> ))} </div> </div> {/* 文档管理主区域 */} <div className="documents-main"> <div className="section-header"> <h3 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}> <FileText size={20} /> {subLibraries.find(lib => lib.id === selectedLibrary)?.name || '默认分库'} - 文档管理 </h3> </div> {/* 文件上传区域 */} <div className={`upload-zone ${isDragOver ? 'drag-over' : ''} ${uploading ? 'uploading' : ''}`} onDragEnter={handleDragEnter} onDragOver={handleDragOver} onDragLeave={handleDragLeave} onDrop={handleDrop} > <div className="upload-content" onDragEnter={handleDragEnter} onDragOver={handleDragOver} onDragLeave={handleDragLeave} onDrop={handleDrop} > <div className="upload-icon">📁</div> <div className="upload-text"> {uploading ? '上传中...' : '拖拽文件到此处或点击选择文件'} </div> <div className="upload-hint"> 支持格式: PDF, DOCX, TXT, MD </div> <input type="file" multiple accept=".pdf,.PDF,.docx,.DOCX,.txt,.TXT,.md,.MD" onChange={(e) => { const files = Array.from(e.target.files || []); setSelectedFiles(prev => [...prev, ...files]); }} style={{ display: 'none' }} id="file-input" /> <label htmlFor="file-input" className="btn btn-primary"> 选择文件 </label> </div> {selectedFiles.length > 0 && ( <div className="selected-files"> <h4>待上传文件 ({selectedFiles.length})</h4> <div className="file-list"> {selectedFiles.map((file, index) => ( <div key={index} className="file-item"> <span className="file-name">{file.name}</span> <span className="file-size"> {(file.size / 1024 / 1024).toFixed(2)} MB </span> <button onClick={() => setSelectedFiles(prev => prev.filter((_, i) => i !== index) )} className="btn-remove" > ✕ </button> </div> ))} </div> <div className="upload-actions"> <button onClick={uploadDocuments} disabled={uploading} className="btn btn-success" > {uploading ? '上传中...' : `上传到 ${subLibraries.find(lib => lib.id === selectedLibrary)?.name}`} </button> <button onClick={() => setSelectedFiles([])} disabled={uploading} className="btn btn-secondary" > 清空 </button> </div> </div> )} </div> {/* 文档处理进度区域 */} {processingDocuments.size > 0 && ( <div style={{ background: 'white', border: '1px solid #e5e7eb', borderRadius: '12px', padding: '20px', marginBottom: '24px', boxShadow: '0 2px 4px rgba(0, 0, 0, 0.05)' }}> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px' }}> <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '16px', fontWeight: '600', color: '#374151' }}> <div style={{ width: '20px', height: '20px', border: '2px solid #3b82f6', borderTop: '2px solid transparent', borderRadius: '50%', animation: 'spin 1s linear infinite' }} /> 正在处理文档 ({processingDocuments.size} 个) </div> {/* 总体进度 */} <div style={{ fontSize: '14px', color: '#6b7280', display: 'flex', alignItems: 'center', gap: '8px' }}> <span>总体进度:</span> <div style={{ width: '100px', height: '6px', backgroundColor: '#f3f4f6', borderRadius: '3px', overflow: 'hidden' }}> <div style={{ width: `${(Array.from(processingDocuments.values()).reduce((sum, doc) => sum + doc.progress, 0) / processingDocuments.size) * 100}%`, height: '100%', backgroundColor: '#3b82f6', borderRadius: '3px', transition: 'width 0.3s ease' }} /> </div> <span style={{ fontWeight: '500', minWidth: '35px' }}> {Math.round((Array.from(processingDocuments.values()).reduce((sum, doc) => sum + doc.progress, 0) / processingDocuments.size) * 100)}% </span> </div> </div> <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}> {Array.from(processingDocuments.values()).map((doc) => ( <ProgressBar key={doc.document_id} progress={doc.progress} status={doc.status} fileName={doc.file_name} totalChunks={doc.total_chunks} chunksProcessed={doc.chunks_processed} /> ))} </div> </div> )} {/* 文档列表 */} <div className="documents-section"> <div className="documents-header"> <h4 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}> <FileText size={20} /> {subLibraries.find(lib => lib.id === selectedLibrary)?.name || '默认分库'} - 文档管理 </h4> </div> {loading ? ( <div className="loading-state">加载中...</div> ) : documents.length === 0 ? ( <div className="empty-state"> <div className="empty-icon" style={{ display: 'flex', justifyContent: 'center', marginBottom: '16px' }}> <FolderOpen size={48} color="#ccc" /> </div> <div className="empty-text">该分库中暂无文档</div> <div className="empty-hint">上传一些文档开始使用吧!</div> </div> ) : ( <div className="documents-grid"> {documents.map((doc: any) => ( <div key={doc.id} className="document-card"> <div className="doc-header"> <div className="doc-name" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}> <FileText size={16} /> {doc.file_name} </div> <div className="doc-actions"> <button onClick={async () => { const confirmDelete = window.confirm(`确定要删除文档 "${doc.file_name}" 吗?此操作不可撤销。`); if (!confirmDelete) return; try { console.log('开始删除文档:', doc.id, doc.file_name); await TauriAPI.ragDeleteDocument(doc.id); console.log('文档删除成功,开始刷新数据'); showSuccess(`文档 "${doc.file_name}" 删除成功`); // 前端即时移除该文档以提升体验 setDocuments(prev => prev.filter(d => d.id !== doc.id)); // 更新知识库状态和分库统计 await loadKnowledgeBaseStatus(); await loadSubLibraries(); } catch (error) { console.error('删除文档失败:', error); showError(`删除文档失败: ${error}`); } }} className="btn-icon" title="删除文档" style={{ display: 'flex', alignItems: 'center', gap: '4px' }} > <Trash2 size={14} /> </button> </div> </div> <div className="doc-info"> <div className="doc-meta"> <span>大小: {formatFileSize(doc.file_size)}</span> <span>文本块: {doc.total_chunks}</span> <span>上传时间: {formatDate(doc.created_at)}</span> </div> </div> </div> ))} </div> )} </div> </div> </div> {/* 创建分库模态框 */} {showCreateLibraryModal && ( <div className="modal-overlay"> <div className="modal"> <div className="modal-header"> <h3>创建新分库</h3> <button onClick={() => setShowCreateLibraryModal(false)} className="btn-close" style={{ display: 'flex', alignItems: 'center' }} > <X size={16} /> </button> </div> <div className="modal-body"> <div className="form-group"> <label>分库名称 *</label> <input type="text" value={newLibraryName} onChange={(e) => setNewLibraryName(e.target.value)} placeholder="请输入分库名称" className="form-input" /> </div> <div className="form-group"> <label>分库描述</label> <textarea value={newLibraryDescription} onChange={(e) => setNewLibraryDescription(e.target.value)} placeholder="请输入分库描述(可选)" className="form-textarea" rows={3} /> </div> </div> <div className="modal-footer"> <button onClick={() => setShowCreateLibraryModal(false)} className="btn btn-secondary" > 取消 </button> <button onClick={createSubLibrary} className="btn btn-primary" disabled={!newLibraryName.trim()} > 创建 </button> </div> </div> </div> )} {/* 编辑分库模态框 */} {showEditLibraryModal && editingLibrary && ( <div className="modal-overlay"> <div className="modal"> <div className="modal-header"> <h3>编辑分库</h3> <button onClick={() => { setShowEditLibraryModal(false); setEditingLibrary(null); }} className="btn-close" style={{ display: 'flex', alignItems: 'center' }} > <X size={16} /> </button> </div> <div className="modal-body"> <div className="form-group"> <label>分库名称 *</label> <input type="text" value={newLibraryName} onChange={(e) => setNewLibraryName(e.target.value)} placeholder="请输入分库名称" className="form-input" /> </div> <div className="form-group"> <label>分库描述</label> <textarea value={newLibraryDescription} onChange={(e) => setNewLibraryDescription(e.target.value)} placeholder="请输入分库描述(可选)" className="form-textarea" rows={3} /> </div> </div> <div className="modal-footer"> <button onClick={() => { setShowEditLibraryModal(false); setEditingLibrary(null); }} className="btn btn-secondary" > 取消 </button> <button onClick={updateSubLibrary} className="btn btn-primary" disabled={!newLibraryName.trim()} > 保存 </button> </div> </div> </div> )} </div> </div> ); }; export default EnhancedKnowledgeBaseManagement;
40,607
EnhancedKnowledgeBaseManagement
tsx
en
tsx
code
{"qsc_code_num_words": 3203, "qsc_code_num_chars": 40607.0, "qsc_code_mean_word_length": 6.06868561, "qsc_code_frac_words_unique": 0.2266625, "qsc_code_frac_chars_top_2grams": 0.01728573, "qsc_code_frac_chars_top_3grams": 0.01064924, "qsc_code_frac_chars_top_4grams": 0.02222451, "qsc_code_frac_chars_dupe_5grams": 0.32786295, "qsc_code_frac_chars_dupe_6grams": 0.29226258, "qsc_code_frac_chars_dupe_7grams": 0.26103509, "qsc_code_frac_chars_dupe_8grams": 0.21190452, "qsc_code_frac_chars_dupe_9grams": 0.17928799, "qsc_code_frac_chars_dupe_10grams": 0.15516, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03497836, "qsc_code_frac_chars_whitespace": 0.37973748, "qsc_code_size_file_byte": 40607.0, "qsc_code_num_lines": 1196.0, "qsc_code_num_chars_line_max": 218.0, "qsc_code_num_chars_line_mean": 33.95234114, "qsc_code_frac_chars_alphabet": 0.73605431, "qsc_code_frac_chars_comments": 0.0171399, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.4934334, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00375235, "qsc_code_frac_chars_string_length": 0.10638404, "qsc_code_frac_chars_long_word_length": 0.0083183, "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}
002and001/FHHFPSIndicator
Demo/FHHFPSIndicatorDemo/Utility/UIViewController+CustomNavigationBar.m
// // ************************************************************************ // // UIViewController+CustomNavigationBar.m // LoveTourGuide // // Created by 002 on 2017/7/26. // Copyright © 2017年 hqyxedu. All rights reserved. // // Main function:自定义导航栏控制器分类 // // Other specifications: // // ************************************************************************ #import "UIViewController+CustomNavigationBar.h" #import "UIView+FHH.h" #import <objc/runtime.h> #define RGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0] #define KColorBlue RGBColor(0, 160, 233) #define ScreenWidth ([[UIScreen mainScreen] bounds].size.width) const char *NavigationBarKey = "navigationBar"; const char *NavMiddleButtonKey = "navMiddleButton"; const char *NavLeftButtonKey = "navLeftButton"; const char *NavRightButtonKey = "navRightButton"; const char *IsPushedKey = "IsPushed"; @implementation UIViewController (CustomNavigationBar) #pragma mark - 导航栏 - (void)setNavigationBarTitle:(NSString *)title { [self setNavigationBarTitle:title navLeftButtonIcon:nil navRightButtonIcon:nil navRightButtonTitle:nil]; self.navLeftButton.hidden = YES; } - (void)setNavigationBarTitle:(NSString *)title navLeftButtonIcon:(NSString *)navLeftButtonIcon { [self setNavigationBarTitle:title navLeftButtonIcon:navLeftButtonIcon navRightButtonIcon:nil navRightButtonTitle:nil]; } - (void)setNavigationBarTitle:(NSString *)title navLeftButtonIcon:(NSString *)navLeftButtonIcon navRightButtonTitle:(NSString *)navRightButtonTitle { [self setNavigationBarTitle:title navLeftButtonIcon:navLeftButtonIcon navRightButtonIcon:nil navRightButtonTitle:navRightButtonTitle]; } - (void)setNavigationBarTitle:(NSString *)title navLeftButtonIcon:(NSString *)navLeftButtonIcon navRightButtonIcon:(NSString *)navRightButtonIcon { [self setNavigationBarTitle:title navLeftButtonIcon:navLeftButtonIcon navRightButtonIcon:navRightButtonIcon navRightButtonTitle:nil]; } - (void)setNavigationBarTitle:(NSString *)title navLeftButtonIcon:(NSString *)navLeftButtonIcon navRightButtonIcon:(NSString *)navRightButtonIcon navRightButtonTitle:(NSString *)navRightButtonTitle { [self pc_configCustomNavigationBar]; [self pc_configCustomNavLeftButtonWithNavLeftButtonIcon:navLeftButtonIcon]; [self pc_configCustomNavRightButtonWithNavRightButtonIcon:navRightButtonIcon navRightButtonTitle:navRightButtonTitle]; [self pc_configCustomNavMiddleButtonWithTitle:title]; [self pc_configBottomSepImageView]; } - (void)pc_configCustomNavigationBar { if (self.navigationController.navigationBar != nil) { [self.navigationController.navigationBar removeFromSuperview]; } if (self.navigationBar != nil) { [self.navigationBar removeFromSuperview]; } self.isPushed = YES; // 1.自定义UIView代替导航栏 // 1.1) 创建并定义属性 self.navigationBar = [[UIView alloc] init]; self.navigationBar.frame = CGRectMake(0, 0, ScreenWidth, 64.0); self.navigationBar.backgroundColor = RGBColor(0, 160, 233); [self.view addSubview:self.navigationBar]; } - (void)pc_configCustomNavLeftButtonWithNavLeftButtonIcon:(NSString *)NavLeftButtonIcon { // 2.‘左边’ 按钮 self.navLeftButton = [[UIButton alloc] init]; self.navLeftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; if (!NavLeftButtonIcon || [@"" isEqualToString:NavLeftButtonIcon]) { NavLeftButtonIcon = @"nav_return"; self.navLeftButton.hidden = YES; } [self.navLeftButton addTarget:self action:@selector(clickLeftNavButton) forControlEvents:UIControlEventTouchUpInside]; [self.navLeftButton setImage:[UIImage imageNamed:NavLeftButtonIcon] forState:UIControlStateNormal]; [self configLeftButton]; [self p_configLeftButtonEdgeInsets]; } - (void)pc_configCustomNavRightButtonWithNavRightButtonIcon:(NSString *)NavRightButtonIcon navRightButtonTitle:(NSString *)navRightButtonTitle { if (NavRightButtonIcon || navRightButtonTitle) { self.navRightButton = [UIButton buttonWithType:UIButtonTypeCustom]; self.navRightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; if (navRightButtonTitle && ![@"" isEqualToString:navRightButtonTitle]) { [self.navRightButton setTitle:navRightButtonTitle forState:UIControlStateNormal]; } if (NavRightButtonIcon && ![@"" isEqualToString:NavRightButtonIcon]) { [self.navRightButton setImage:[UIImage imageNamed:NavRightButtonIcon] forState:UIControlStateNormal]; } self.navRightButton.titleLabel.font = [UIFont systemFontOfSize:T5_30PX]; [self.navRightButton setTitleColor:kColorC4_1 forState:UIControlStateNormal]; [self.navigationBar addSubview:self.navRightButton]; [self reConfigNavRightButton]; [self p_configRightButtonEdgeInsets]; } } - (void)pc_configCustomNavMiddleButtonWithTitle:(NSString *)title { if (title && ![@"" isEqualToString:title]) { [self addBarMiddleButtonWithTitle:title]; } } - (void)addBarMiddleButtonWithTitle:(NSString *)title { self.navMiddleButton = [[UIButton alloc] init]; self.navMiddleButton.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail; [self.navMiddleButton setTitle:title forState:UIControlStateNormal]; [self.navMiddleButton setTitleColor:kColorC4_1 forState:UIControlStateNormal]; self.navMiddleButton.titleLabel.font = [UIFont systemFontOfSize:T3_34PX]; [self reConfigNavMiddleButton]; // 添加到当前view [self.navigationBar addSubview:self.navMiddleButton]; } - (void)pc_configBottomSepImageView { CGRect frame = CGRectMake(0, self.navigationBar.height - 0.5, self.navigationBar.width, 0.5); UIImageView *bottomSepImageView = [[UIImageView alloc] initWithFrame:frame]; [self.navigationBar addSubview:bottomSepImageView]; bottomSepImageView.backgroundColor = kColorC3_1; } - (void)configLeftButton { [self.navLeftButton sizeToFit]; self.navLeftButton.frame = CGRectMake(0, 28 , 50, 64); self.navLeftButton.bottom = self.navigationBar.height; [self.navigationBar addSubview:self.navLeftButton]; } - (void)p_configLeftButtonEdgeInsets { self.navLeftButton.imageEdgeInsets = UIEdgeInsetsMake((50 - 30), S3_PAGE_PADDING_30PX, 0, 0); } - (void)p_configRightButtonEdgeInsets { CGSize imageSize = self.navRightButton.imageView.size; CGSize titleSize = self.navRightButton.titleLabel.size; CGFloat imageLeftInset = (self.navRightButton.width - imageSize.width - MARGIN_COMMON); CGFloat titleLeftInset = (self.navRightButton.width - titleSize.width - MARGIN_COMMON + 2); self.navRightButton.imageEdgeInsets = UIEdgeInsetsMake(0, imageLeftInset, 0, -imageLeftInset); self.navRightButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, titleLeftInset); } - (void)clickLeftNavButton { if (self.isPushed) { [self.navigationController popViewControllerAnimated:YES]; } else { if (self.navigationController != nil) { [self.navigationController dismissViewControllerAnimated:YES completion:nil]; } else { [self dismissViewControllerAnimated:YES completion:nil]; } } } - (void)removeNavLeftButtonDefaultEvent { [self.navLeftButton removeTarget:self action:@selector(clickLeftNavButton) forControlEvents:UIControlEventTouchUpInside]; } - (void)reConfigNavMiddleButton { [self.navMiddleButton sizeToFit]; CGFloat maxWidth = self.navigationBar.width - 2 * PADDING_30PX; if (self.navLeftButton != nil && self.navRightButton != nil) { maxWidth = self.navRightButton.x - self.navLeftButton.right; } else if (self.navLeftButton != nil) { maxWidth = self.navigationBar.width - 2 * self.navLeftButton.right; } if (self.navMiddleButton.width > maxWidth) { self.navMiddleButton.width = maxWidth; } self.navMiddleButton.center = CGPointMake(self.navigationBar.centerX , self.navLeftButton.centerY + 20 * 0.5); } - (void)reConfigNavRightButton { if (self.navRightButton.currentBackgroundImage == nil) { [self.navRightButton sizeToFit]; self.navRightButton.width = self.navRightButton.width + MARGIN_COMMON; self.navRightButton.height = 44; if (self.navRightButton.width < 40) { self.navRightButton.width = 40; } self.navRightButton.centerY = self.navLeftButton.centerY + (20 * 0.5); self.navRightButton.right = self.navigationBar.right; } else { self.navRightButton.centerY = self.navLeftButton.centerY + (20 * 0.5); self.navRightButton.right = self.navigationBar.right - MARGIN_COMMON; } } #pragma mark - 运行时添加实例变量 - (void)setNavigationBar:(UIView *)navigationBar { objc_setAssociatedObject(self, NavigationBarKey, navigationBar, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (UIView *)navigationBar { return objc_getAssociatedObject(self, NavigationBarKey); } - (void)setNavMiddleButton:(UIButton *)navMiddleButton { objc_setAssociatedObject(self, NavMiddleButtonKey, navMiddleButton, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (UIButton *)navMiddleButton { return objc_getAssociatedObject(self, NavMiddleButtonKey); } - (void)setNavLeftButton:(UIButton *)navLeftButton { objc_setAssociatedObject(self, NavLeftButtonKey, navLeftButton, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (UIButton *)navLeftButton { return objc_getAssociatedObject(self, NavLeftButtonKey); } - (void)setNavRightButton:(UIButton *)navRightButton { objc_setAssociatedObject(self, NavRightButtonKey, navRightButton, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (UIButton *)navRightButton { return objc_getAssociatedObject(self, NavRightButtonKey); } - (void)setIsPushed:(BOOL)isPushed { NSNumber *isPushedNumber = [NSNumber numberWithBool:isPushed]; objc_setAssociatedObject(self, IsPushedKey, isPushedNumber, OBJC_ASSOCIATION_ASSIGN); } - (BOOL)isPushed { NSNumber *isPushedInNumber = objc_getAssociatedObject(self, IsPushedKey); bool isPushed = [isPushedInNumber boolValue]; return isPushed; } @end
11,010
UIViewController+CustomNavigationBar
m
en
limbo
code
{"qsc_code_num_words": 822, "qsc_code_num_chars": 11010.0, "qsc_code_mean_word_length": 9.1216545, "qsc_code_frac_words_unique": 0.24695864, "qsc_code_frac_chars_top_2grams": 0.06241664, "qsc_code_frac_chars_top_3grams": 0.01840491, "qsc_code_frac_chars_top_4grams": 0.02534009, "qsc_code_frac_chars_dupe_5grams": 0.21872499, "qsc_code_frac_chars_dupe_6grams": 0.17951454, "qsc_code_frac_chars_dupe_7grams": 0.11162977, "qsc_code_frac_chars_dupe_8grams": 0.10096026, "qsc_code_frac_chars_dupe_9grams": 0.07575353, "qsc_code_frac_chars_dupe_10grams": 0.05921579, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01282345, "qsc_code_frac_chars_whitespace": 0.20672116, "qsc_code_size_file_byte": 11010.0, "qsc_code_num_lines": 285.0, "qsc_code_num_chars_line_max": 123.0, "qsc_code_num_chars_line_mean": 38.63157895, "qsc_code_frac_chars_alphabet": 0.84554614, "qsc_code_frac_chars_comments": 0.03142598, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.19665272, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00684546, "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}
002and001/FHHFPSIndicator
Demo/FHHFPSIndicatorDemo/Utility/UIView+FHH.m
// // UIView+FHH.m // // // Created by 002 on 15/10/1. // Copyright (c) 2015年 002. All rights reserved. // #import "UIView+FHH.h" @implementation UIView (FHH) #pragma mark - Setter - (void)setX:(CGFloat)x { CGRect frame = self.frame; frame.origin.x = x; self.frame = frame; } - (void)setY:(CGFloat)y { CGRect frame = self.frame; frame.origin.y = y; self.frame = frame; } - (void)setRight:(CGFloat)right { self.frame = CGRectMake(right - self.width, self.y, self.width, self.height); } - (void)setBottom:(CGFloat)bottom { self.frame = CGRectMake(self.x, bottom - self.height, self.width, self.height); } - (void)setCenterX:(CGFloat)centerX{ CGPoint center = self.center; center.x = centerX; self.center = center; } - (void)setCenterY:(CGFloat)centerY { CGPoint center = self.center; center.y = centerY; self.center = center; } - (void)setWidth:(CGFloat)width { CGRect frame = self.frame; frame.size.width = width; self.frame = frame; } - (void)setHeight:(CGFloat)height { CGRect frame = self.frame; frame.size.height = height; self.frame = frame; } - (void)setOrigin:(CGPoint)origin { CGRect frame = self.frame; frame.origin = origin; self.frame = frame; } - (void)setSize:(CGSize)size { CGRect tempFrame = self.frame; tempFrame.size = size; self.frame = tempFrame; } #pragma mark - Getter - (CGFloat)x { return self.frame.origin.x; } - (CGFloat)y { return self.frame.origin.y; } - (CGFloat)width { return self.frame.size.width; } - (CGFloat)height { return self.frame.size.height; } - (CGSize)size { return self.frame.size; } - (CGPoint)origin { return self.frame.origin; } - (CGFloat)centerX { return self.center.x; } - (CGFloat)centerY { return self.center.y; } - (CGFloat)bottom { return self.y + self.height; } - (CGFloat)right { return self.x + self.width; } #pragma mark - Functions - (CGRect)convertRectToView:(UIView *)view { CGRect newFrame = [self convertRect:self.bounds toView:view]; return newFrame; } - (CGFloat)xInView:(UIView *)view { CGRect newFrame = [self convertRect:self.bounds toView:view]; return newFrame.origin.x; } - (CGFloat)yInView:(UIView *)view { CGRect newFrame = [self convertRect:self.bounds toView:view]; return newFrame.origin.y; } - (CGFloat)rightInView:(UIView *)view { CGRect newFrame = [self convertRect:self.bounds toView:view]; return newFrame.origin.x + newFrame.size.width; } - (CGFloat)bottomInView:(UIView *)view { CGRect newFrame = [self convertRect:self.bounds toView:view]; return newFrame.origin.y + newFrame.size.height; } - (CGFloat)centerXInView:(UIView *)view { CGRect newFrame = [self convertRect:self.bounds toView:view]; return newFrame.origin.x + newFrame.size.width * 0.5; } - (CGFloat)centerYInView:(UIView *)view { CGRect newFrame = [self convertRect:self.bounds toView:view]; return newFrame.origin.y + newFrame.size.height * 0.5; } @end
3,034
UIView+FHH
m
en
limbo
code
{"qsc_code_num_words": 374, "qsc_code_num_chars": 3034.0, "qsc_code_mean_word_length": 5.36363636, "qsc_code_frac_words_unique": 0.18716578, "qsc_code_frac_chars_top_2grams": 0.08973081, "qsc_code_frac_chars_top_3grams": 0.06979063, "qsc_code_frac_chars_top_4grams": 0.08374875, "qsc_code_frac_chars_dupe_5grams": 0.43768694, "qsc_code_frac_chars_dupe_6grams": 0.38584247, "qsc_code_frac_chars_dupe_7grams": 0.3105683, "qsc_code_frac_chars_dupe_8grams": 0.3105683, "qsc_code_frac_chars_dupe_9grams": 0.3105683, "qsc_code_frac_chars_dupe_10grams": 0.3105683, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00772672, "qsc_code_frac_chars_whitespace": 0.18951879, "qsc_code_size_file_byte": 3034.0, "qsc_code_num_lines": 147.0, "qsc_code_num_chars_line_max": 84.0, "qsc_code_num_chars_line_mean": 20.63945578, "qsc_code_frac_chars_alphabet": 0.80805205, "qsc_code_frac_chars_comments": 0.03032301, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.22123894, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "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}
002and001/FHHFPSIndicator
Demo/FHHFPSIndicatorDemo/Classes/LastHomeViewController.m
// // LastHomeViewController.m // FHHFPSIndicator // // Created by 002 on 16/6/27. // Copyright © 2016年 002. All rights reserved. // #import "LastHomeViewController.h" #import "UIViewController+CustomNavigationBar.h" #import "WildernessViewController.h" #import "FHHFPSIndicator.h" @implementation LastHomeViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = kColorC4_1; [self setNavigationBarTitle:@"LastHome" navLeftButtonIcon:@"backupIcon" navRightButtonTitle:@"next"]; [self.navRightButton addTarget:self action:@selector(p_rightButtonDidClick:) forControlEvents:UIControlEventTouchUpInside]; [FHHFPSIndicator sharedFPSIndicator].fpsLabelPosition = FPSIndicatorPositionTopRight; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:YES]; [FHHFPSIndicator sharedFPSIndicator].fpsLabelPosition = FPSIndicatorPositionBottomCenter; } - (void)p_rightButtonDidClick:(UIButton *)btn { [self.navigationController pushViewController:[[WildernessViewController alloc] init] animated:YES]; } @end
1,097
LastHomeViewController
m
en
limbo
code
{"qsc_code_num_words": 87, "qsc_code_num_chars": 1097.0, "qsc_code_mean_word_length": 9.72413793, "qsc_code_frac_words_unique": 0.67816092, "qsc_code_frac_chars_top_2grams": 0.0248227, "qsc_code_frac_chars_top_3grams": 0.11583924, "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.01758014, "qsc_code_frac_chars_whitespace": 0.11850501, "qsc_code_size_file_byte": 1097.0, "qsc_code_num_lines": 36.0, "qsc_code_num_chars_line_max": 128.0, "qsc_code_num_chars_line_mean": 30.47222222, "qsc_code_frac_chars_alphabet": 0.85625646, "qsc_code_frac_chars_comments": 0.13582498, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.13043478, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.02320675, "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}
002and001/FHHFPSIndicator
Demo/FHHFPSIndicatorDemo/Classes/AppDelegate.m
// // AppDelegate.m // FHHFPSIndicatorDemo // // Created by 002 on 16/6/27. // Copyright © 2016年 002. All rights reserved. // #import "AppDelegate.h" #import "HomeViewController.h" #if defined(DEBUG) || defined(_DEBUG) #import "FHHFPSIndicator.h" #endif @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; [self.window makeKeyAndVisible]; // Add the follwing code after the window become keywindow #if defined(DEBUG) || defined(_DEBUG) [[FHHFPSIndicator sharedFPSIndicator] show]; // [FHHFPSIndicator sharedFPSIndicator].fpsLabelPosition = FPSIndicatorPositionTopRight; #endif self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[HomeViewController alloc] init]]; return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } - (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } @end
2,669
AppDelegate
m
en
limbo
code
{"qsc_code_num_words": 306, "qsc_code_num_chars": 2669.0, "qsc_code_mean_word_length": 6.66666667, "qsc_code_frac_words_unique": 0.54248366, "qsc_code_frac_chars_top_2grams": 0.07058824, "qsc_code_frac_chars_top_3grams": 0.01911765, "qsc_code_frac_chars_top_4grams": 0.02205882, "qsc_code_frac_chars_dupe_5grams": 0.07156863, "qsc_code_frac_chars_dupe_6grams": 0.02647059, "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.00669643, "qsc_code_frac_chars_whitespace": 0.16073436, "qsc_code_size_file_byte": 2669.0, "qsc_code_num_lines": 63.0, "qsc_code_num_chars_line_max": 282.0, "qsc_code_num_chars_line_mean": 42.36507937, "qsc_code_frac_chars_alphabet": 0.90357143, "qsc_code_frac_chars_comments": 0.06481828, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.13157895, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "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}
002and001/FHHFPSIndicator
Demo/FHHFPSIndicatorDemo/Classes/WildernessViewController.m
// // WildernessViewController.m // FHHFPSIndicator // // Created by 002 on 16/6/27. // Copyright © 2016年 002. All rights reserved. // #import "WildernessViewController.h" #import "UIViewController+CustomNavigationBar.h" #import "UIView+FHH.h" @interface WildernessViewController () @property (nonatomic, strong) UITextView *textView; @end @implementation WildernessViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = RGBColor(246, 246, 246); [self setNavigationBarTitle:@"Wilderness" navLeftButtonIcon:@"deleteButton"]; [self removeNavLeftButtonDefaultEvent]; [self.navLeftButton addTarget:self action:@selector(p_leftButtonClick) forControlEvents:UIControlEventTouchUpInside]; [self p_setupUI]; } - (void)p_setupUI { [self.view addSubview:self.textView]; self.textView.width = [UIScreen mainScreen].bounds.size.width; self.textView.height = [UIScreen mainScreen].bounds.size.height - 64 - 20; self.textView.x = 0; self.textView.y = 64 + 20; } - (void)p_leftButtonClick { [self.navigationController popToRootViewControllerAnimated:YES]; } - (UITextView *)textView { if(!_textView) { _textView = [[UITextView alloc] init]; NSMutableString *strM = [NSMutableString string]; for (int i = 0; i < 500; i++) { [strM appendString:@"O(∩_∩)!%>_<% 😙😙😐😣😡😚😱(‧_‧?)😱🌮🍩🏝💖🍫🍦🏦🍦(*^__^*)(ˉ▽ ̄~) 😚😚😚😣😡😱(→_→)😱😚🌮😚🗽🍻🍯🗽🚋🎊🎂💗💛🍫🎂🍜🍜🍜(¯^¯ )"]; } _textView.text = strM; } return _textView; } @end
1,551
WildernessViewController
m
en
limbo
code
{"qsc_code_num_words": 154, "qsc_code_num_chars": 1551.0, "qsc_code_mean_word_length": 6.81168831, "qsc_code_frac_words_unique": 0.59090909, "qsc_code_frac_chars_top_2grams": 0.05719733, "qsc_code_frac_chars_top_3grams": 0.04575786, "qsc_code_frac_chars_top_4grams": 0.05338418, "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.02915682, "qsc_code_frac_chars_whitespace": 0.18181818, "qsc_code_size_file_byte": 1551.0, "qsc_code_num_lines": 58.0, "qsc_code_num_chars_line_max": 122.0, "qsc_code_num_chars_line_mean": 26.74137931, "qsc_code_frac_chars_alphabet": 0.7572892, "qsc_code_frac_chars_comments": 0.07027724, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.12195122, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0742025, "qsc_code_frac_chars_long_word_length": 0.04785021, "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}
003random/getJS
main.go
package main import ( "bufio" "flag" "fmt" "io" "log" "net/http" "os" "strings" "time" "github.com/003random/getJS/v2/runner" ) func main() { options, err := setup() if err != nil { log.Fatal(fmt.Errorf("parsing flags: %w", err)) } if err := runner.New(options).Run(); err != nil { log.Fatal(err) } } func setup() (options *runner.Options, err error) { options = &runner.Options{} flag.StringVar(&options.Request.Method, "method", "GET", "The request method that should be used to make fetch the remote contents.") flag.DurationVar(&options.Request.Timeout, "timeout", 5*time.Second, "The request timeout used while fetching the remote contents.") flag.BoolVar(&options.Request.InsecureSkipVerify, "insecure", true, "Skip certification verification.") flag.BoolVar(&options.Complete, "complete", false, "Complete/Autofil relative URLs by adding the current origin.") flag.BoolVar(&options.Resolve, "resolve", false, "Resolve the JavaScript files. Can only be used in combination with '--resolve'. Unresolvable hosts are not included in the results.") flag.IntVar(&options.Threads, "threads", 2, "The amount of processing threads to spawn.") flag.BoolVar(&options.Verbose, "verbose", false, "Print verbose runtime information and errors.") var ( url string input arrayFlags output arrayFlags header arrayFlags ) flag.Var(&header, "header", "The optional request headers to add to the requests. This flag can be used multiple times with a new header each time.") flag.StringVar(&url, "url", "", "The URL where the JavaScript sources should be extracted from.") flag.Var(&input, "input", "The optional URLs input files. Each URL should be on a new line in plain text format. This flag can be used multiple times with different files.") flag.Var(&output, "output", "The optional output file where the results are written to.") flag.Parse() options.Request.Headers = headers(header) options.Inputs = inputs(input) options.Outputs = outputs(output) // Add an input for the single URL option, if set. if len(url) > 0 { options.Inputs = append(options.Inputs, runner.Input{ Type: runner.InputURL, Data: strings.NewReader(url), }) } stat, err := os.Stdin.Stat() if err != nil { log.Fatal(fmt.Errorf("error reading stdin: %v", err)) } if (stat.Mode() & os.ModeCharDevice) == 0 { // Read the first line of stdin to detect its format reader := bufio.NewReader(os.Stdin) firstLine, err := reader.ReadString('\n') if err != nil && err != io.EOF { log.Fatal(fmt.Errorf("error reading first line of stdin: %v", err)) } if isURL(strings.TrimSpace(firstLine)) { // Treat as URL input. options.Inputs = append(options.Inputs, runner.Input{ Type: runner.InputURL, Data: io.MultiReader(strings.NewReader(firstLine), reader), }) } else { // Treat as HTTP response body. options.Inputs = append(options.Inputs, runner.Input{ Type: runner.InputResponse, Data: io.MultiReader(strings.NewReader(firstLine), reader), }) } } return } func isURL(str string) bool { return strings.HasPrefix(str, "http://") || strings.HasPrefix(str, "https://") } func outputs(names []string) []io.Writer { outputs := append([]io.Writer{}, os.Stdout) for _, n := range names { file, err := os.OpenFile(n, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) if err != nil { log.Fatal(fmt.Errorf("error parsing output file flag: %v", err)) } outputs = append(outputs, file) } return outputs } func inputs(names []string) []runner.Input { inputs := []runner.Input{} for _, n := range names { file, err := os.Open(n) if err != nil { log.Fatal(fmt.Errorf("error reading from file %s: %v", n, err)) } inputs = append(inputs, runner.Input{Type: runner.InputURL, Data: file}) } return inputs } func headers(args []string) http.Header { headers := make(http.Header) for _, s := range args { parts := strings.Split(s, ":") if len(parts) <= 1 { log.Fatal(fmt.Errorf("invalid header %s", s)) } headers[strings.TrimSpace(parts[0])] = []string{strings.TrimSpace(strings.Join(parts[1:], ":"))} } return headers } type arrayFlags []string func (a *arrayFlags) Set(value string) error { *a = append(*a, value) return nil } func (a *arrayFlags) String() string { return strings.Join(*a, ",") }
4,324
main
go
en
go
code
{"qsc_code_num_words": 597, "qsc_code_num_chars": 4324.0, "qsc_code_mean_word_length": 4.93634841, "qsc_code_frac_words_unique": 0.31155779, "qsc_code_frac_chars_top_2grams": 0.01900238, "qsc_code_frac_chars_top_3grams": 0.02239566, "qsc_code_frac_chars_top_4grams": 0.03461147, "qsc_code_frac_chars_dupe_5grams": 0.19884628, "qsc_code_frac_chars_dupe_6grams": 0.19884628, "qsc_code_frac_chars_dupe_7grams": 0.18900577, "qsc_code_frac_chars_dupe_8grams": 0.12046149, "qsc_code_frac_chars_dupe_9grams": 0.08720733, "qsc_code_frac_chars_dupe_10grams": 0.04411266, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00417362, "qsc_code_frac_chars_whitespace": 0.16882516, "qsc_code_size_file_byte": 4324.0, "qsc_code_num_lines": 154.0, "qsc_code_num_chars_line_max": 185.0, "qsc_code_num_chars_line_mean": 28.07792208, "qsc_code_frac_chars_alphabet": 0.81580412, "qsc_code_frac_chars_comments": 0.03584644, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.13445378, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.02521008, "qsc_code_frac_chars_string_length": 0.27584553, "qsc_code_frac_chars_long_word_length": 0.00863516, "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.06722689, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.13445378, "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}
003random/getJS
README.md
<h1 align="center">JavaScript Extraction CLI & Package</h1> <p align="center"> <a href="https://pkg.go.dev/github.com/003random/getJS"> <img src="https://pkg.go.dev/badge/github.com/003random/getJS"> </a> <a href="https://github.com/003random/getJS/releases"> <img src="https://img.shields.io/github/release/003random/getJS.svg"> </a> <a href="https://github.com/003random/getJS/blob/master/LICENSE"> <img src="https://img.shields.io/badge/license-MIT-blue.svg"> </a> </p> This is a powerful tool for extracting JavaScript sources from URLs and web pages / HTTP responses. It offers a command-line interface (CLI) for straightforward URL processing and a package interface for custom integrations, making it ideal for pentesters, bug bounty hunters, and developers needing to extract JS sources efficiently. ## Table of Contents - [Installation](#installation) - [CLI Usage](#cli-usage) - [Options](#options) - [Examples](#examples) - [Package Usage](#package-usage) - [Importing the Extractor](#importing-the-extractor) - [Example](#example) - [Version Information](#version-information) - [Contributing](#contributing) - [License](#license) ## Installation To install `getJS`, use the following command: `go install github.com/003random/getJS/v2@latest` ## CLI Usage ### Options `getJS` provides several command-line options to customize its behavior: - `-url string`: The URL from which JavaScript sources should be extracted. - `-input string`: Optional URLs input files. Each URL should be on a new line in plain text format. Can be used multiple times. - `-output string`: Optional output file where results are written to. Can be used multiple times. - `-complete`: Complete/Autofill relative URLs by adding the current origin. - `-resolve`: Resolve the JavaScript files. Can only be used in combination with `--complete`. - `-threads int`: The number of processing threads to spawn (default: 2). - `-verbose`: Print verbose runtime information and errors. - `-method string`: The request method used to fetch remote contents (default: "GET"). - `-header string`: Optional request headers to add to the requests. Can be used multiple times. - `-timeout duration`: The request timeout while fetching remote contents (default: 5s). ### Examples #### Extracting JavaScript from a Single URL `getJS -url https://destroy.ai` or `curl https://destroy.ai | getJS` #### Using Custom Request Options `getJS -url "http://example.com" -header "User-Agent: foo bar" -method POST --timeout=15s` #### Processing Multiple URLs from a File `getJS -input foo.txt -input bar.txt` #### Saving Results to an Output File `getJS -url "http://example.com" -output results.txt` ## Package Usage ### Importing the Extractor To use `getJS` as a package, you need to import the `extractor` package and utilize its functions directly. ### Example ```Go package main import ( "fmt" "log" "net/http" "net/url" "github.com/003random/getJS/extractor" ) func main() { baseURL, err := url.Parse("https://google.com") if (err != nil) { log.Fatalf("Error parsing base URL: %v", err) } resp, err := extractor.FetchResponse(baseURL.String(), "GET", http.Header{}) if (err != nil) { log.Fatalf("Error fetching response: %v", err) } defer resp.Body.Close() // Custom extraction points (optional). extractionPoints := map[string][]string{ "script": {"src", "data-src"}, "a": {"href"}, } sources, err := extractor.ExtractSources(resp.Body, extractionPoints) if (err != nil) { log.Fatalf("Error extracting sources: %v", err) } // Filtering and extending extracted sources. filtered, err := extractor.Filter(sources, extractor.WithComplete(baseURL), extractor.WithResolve()) if (err != nil) { log.Fatalf("Error filtering sources: %v", err) } for source := range filtered { fmt.Println(source.String()) } } ``` ## Version Information This is the v2 version of `getJS`. The original version can be found under the tag [v1](https://github.com/003random/getJS/tree/v1). ## Contributing Contributions are welcome! Please open an issue or submit a pull request for any bugs, feature requests, or improvements. ## License This project is licensed under the MIT License. See the [LICENSE](https://github.com/003random/getJS/blob/master/LICENSE) file for details.
4,446
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.00449843, "qsc_doc_frac_words_redpajama_stop": 0.13116371, "qsc_doc_num_sentences": 73.0, "qsc_doc_num_words": 594, "qsc_doc_num_chars": 4446.0, "qsc_doc_num_lines": 140.0, "qsc_doc_mean_word_length": 5.22390572, "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.38888889, "qsc_doc_entropy_unigram": 5.06949571, "qsc_doc_frac_words_all_caps": 0.01873767, "qsc_doc_frac_lines_dupe_lines": 0.14141414, "qsc_doc_frac_chars_dupe_lines": 0.02112163, "qsc_doc_frac_chars_top_2grams": 0.04060587, "qsc_doc_frac_chars_top_3grams": 0.0464067, "qsc_doc_frac_chars_top_4grams": 0.05929745, "qsc_doc_frac_chars_dupe_5grams": 0.15082179, "qsc_doc_frac_chars_dupe_6grams": 0.08507896, "qsc_doc_frac_chars_dupe_7grams": 0.04189494, "qsc_doc_frac_chars_dupe_8grams": 0.04189494, "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": 19.78037383, "qsc_doc_frac_chars_hyperlink_html_tag": 0.11830859, "qsc_doc_frac_chars_alphabet": 0.82864865, "qsc_doc_frac_chars_digital": 0.01, "qsc_doc_frac_chars_whitespace": 0.16779127, "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}
003random/getJS
extractor/extractor.go
package extractor import ( "fmt" "io" "log" "net/http" "net/url" "github.com/PuerkitoBio/goquery" ) // ExtractionPoints defines the default HTML tags and their attributes from which JavaScript sources are extracted. var ExtractionPoints = map[string][]string{ "script": {"src", "data-src"}, } // FetchResponse fetches the HTTP response for the given URL. func FetchResponse(u string, method string, headers http.Header) (*http.Response, error) { req, err := http.NewRequest(method, u, nil) if err != nil { return nil, err } req.Header = headers return http.DefaultClient.Do(req) } // ExtractSources extracts all JavaScript sources found in the provided HTTP response reader. // The optional extractionPoints can be used to overwrite the default extraction points map // with a set of HTML tag names, together with a list of what attributes to extract from. func ExtractSources(input io.Reader, extractionPoints ...map[string][]string) (<-chan url.URL, error) { doc, err := goquery.NewDocumentFromReader(input) if err != nil { return nil, err } var ( urls = make(chan url.URL) points = ExtractionPoints ) if len(extractionPoints) > 0 { points = extractionPoints[0] } go func() { defer close(urls) for tag, attributes := range points { doc.Find(tag).Each(func(i int, s *goquery.Selection) { for _, a := range attributes { if value, exists := s.Attr(a); exists { u, err := url.Parse(value) if err != nil { log.Println(fmt.Errorf("invalid attribute value %s cannot be parsed to a URL: %w", value, err)) continue } urls <- *u } } }) } }() return urls, nil } // Filter applies options to filter URLs from the input channel. func Filter(input <-chan url.URL, options ...func([]url.URL) []url.URL) (<-chan url.URL, error) { output := make(chan url.URL) go func() { defer close(output) var urls []url.URL for u := range input { urls = append(urls, u) } for _, option := range options { urls = option(urls) } for _, u := range urls { output <- u } }() return output, nil } // WithComplete is an option to complete relative URLs. func WithComplete(base *url.URL) func([]url.URL) []url.URL { return func(urls []url.URL) []url.URL { var result []url.URL for _, u := range urls { result = append(result, complete(u, base)) } return result } } // WithResolve is an option to filter URLs that resolve successfully. func WithResolve() func([]url.URL) []url.URL { return func(urls []url.URL) []url.URL { var result []url.URL for _, u := range urls { if resolve(u) { result = append(result, u) } } return result } } // complete completes relative URLs by adding the base URL. func complete(source url.URL, base *url.URL) url.URL { if source.IsAbs() { return source } return *base.ResolveReference(&source) } // resolve checks if the provided URL resolves successfully. func resolve(source url.URL) bool { resp, err := http.Get(source.String()) if err != nil { return false } defer resp.Body.Close() _, err = io.Copy(io.Discard, resp.Body) return err == nil && (resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices) }
3,223
extractor
go
en
go
code
{"qsc_code_num_words": 444, "qsc_code_num_chars": 3223.0, "qsc_code_mean_word_length": 4.83333333, "qsc_code_frac_words_unique": 0.32432432, "qsc_code_frac_chars_top_2grams": 0.08108108, "qsc_code_frac_chars_top_3grams": 0.05032619, "qsc_code_frac_chars_top_4grams": 0.03355079, "qsc_code_frac_chars_dupe_5grams": 0.09832246, "qsc_code_frac_chars_dupe_6grams": 0.08387698, "qsc_code_frac_chars_dupe_7grams": 0.06523765, "qsc_code_frac_chars_dupe_8grams": 0.06523765, "qsc_code_frac_chars_dupe_9grams": 0.06523765, "qsc_code_frac_chars_dupe_10grams": 0.06523765, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00077851, "qsc_code_frac_chars_whitespace": 0.20291654, "qsc_code_size_file_byte": 3223.0, "qsc_code_num_lines": 133.0, "qsc_code_num_chars_line_max": 116.0, "qsc_code_num_chars_line_mean": 24.23308271, "qsc_code_frac_chars_alphabet": 0.83456598, "qsc_code_frac_chars_comments": 0.23456407, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.18446602, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.05107418, "qsc_code_frac_chars_long_word_length": 0.01216052, "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.06796117, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.2038835, "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}
000haoji/deep-student
src-tauri/src/debug_logger.rs
/** * 后端调试日志记录模块 * 用于记录数据库操作、API调用、流式处理等关键信息 */ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use tauri::Manager; use tracing::{error, info, warn}; #[derive(Debug, Serialize, Deserialize, Clone)] pub enum LogLevel { DEBUG, INFO, WARN, ERROR, TRACE, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct LogContext { pub user_id: Option<String>, pub session_id: Option<String>, pub mistake_id: Option<String>, pub stream_id: Option<String>, pub business_id: Option<String>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct LogEntry { pub timestamp: String, pub level: LogLevel, pub module: String, pub operation: String, pub data: serde_json::Value, pub context: Option<LogContext>, pub stack_trace: Option<String>, } #[derive(Debug, Clone)] pub struct DebugLogger { log_dir: PathBuf, log_queue: Arc<Mutex<Vec<LogEntry>>>, } impl DebugLogger { pub fn new(app_data_dir: PathBuf) -> Self { let log_dir = app_data_dir.join("logs"); // 确保日志目录存在 if let Err(e) = std::fs::create_dir_all(&log_dir.join("frontend")) { error!("Failed to create frontend log directory: {}", e); } if let Err(e) = std::fs::create_dir_all(&log_dir.join("backend")) { error!("Failed to create backend log directory: {}", e); } if let Err(e) = std::fs::create_dir_all(&log_dir.join("debug")) { error!("Failed to create debug log directory: {}", e); } Self { log_dir, log_queue: Arc::new(Mutex::new(Vec::new())), } } /// 记录数据库操作相关日志 pub async fn log_database_operation( &self, operation: &str, table: &str, query: &str, params: Option<&serde_json::Value>, result: Option<&serde_json::Value>, error: Option<&str>, duration_ms: Option<u64>, ) { let level = if error.is_some() { LogLevel::ERROR } else { LogLevel::DEBUG }; let data = serde_json::json!({ "table": table, "query": query, "params": params, "result": self.sanitize_database_result(result), "error": error, "duration_ms": duration_ms }); self.log(level, "DATABASE", operation, data, None).await; } /// 记录聊天记录相关操作 pub async fn log_chat_record_operation( &self, operation: &str, mistake_id: &str, chat_history: Option<&serde_json::Value>, expected_vs_actual: Option<(usize, usize)>, error: Option<&str>, ) { let level = if error.is_some() { LogLevel::ERROR } else { LogLevel::INFO }; let data = serde_json::json!({ "mistake_id": mistake_id, "chat_history_length": chat_history.and_then(|ch| ch.as_array().map(|arr| arr.len())), "chat_history": self.sanitize_chat_history(chat_history), "expected_vs_actual": expected_vs_actual, "error": error, "timestamp": Utc::now().to_rfc3339() }); let context = LogContext { user_id: None, session_id: None, mistake_id: Some(mistake_id.to_string()), stream_id: None, business_id: Some(mistake_id.to_string()), }; self.log(level, "CHAT_RECORD", operation, data, Some(context)).await; } /// 记录RAG操作 pub async fn log_rag_operation( &self, operation: &str, query: Option<&str>, top_k: Option<usize>, sources_found: Option<usize>, sources_returned: Option<usize>, error: Option<&str>, duration_ms: Option<u64>, ) { let level = if error.is_some() { LogLevel::ERROR } else { LogLevel::INFO }; let data = serde_json::json!({ "query_length": query.map(|q| q.len()), "query_preview": query.map(|q| if q.len() > 100 { &q[..100] } else { q }), "top_k": top_k, "sources_found": sources_found, "sources_returned": sources_returned, "error": error, "duration_ms": duration_ms, "sources_missing": sources_found.and_then(|found| sources_returned.map(|returned| found.saturating_sub(returned)) ) }); self.log(level, "RAG", operation, data, None).await; } /// 记录流式处理操作 pub async fn log_streaming_operation( &self, operation: &str, stream_id: &str, event_type: &str, payload_size: Option<usize>, error: Option<&str>, ) { let level = if error.is_some() { LogLevel::ERROR } else { LogLevel::DEBUG }; let data = serde_json::json!({ "stream_id": stream_id, "event_type": event_type, "payload_size": payload_size, "error": error, "timestamp": Utc::now().to_rfc3339() }); let context = LogContext { user_id: None, session_id: None, mistake_id: None, stream_id: Some(stream_id.to_string()), business_id: None, }; self.log(level, "STREAMING", operation, data, Some(context)).await; } /// 记录API调用 pub async fn log_api_call( &self, operation: &str, method: &str, url: &str, request_body: Option<&serde_json::Value>, response_body: Option<&serde_json::Value>, status_code: Option<u16>, error: Option<&str>, duration_ms: Option<u64>, ) { let level = if error.is_some() || status_code.map_or(false, |code| code >= 400) { LogLevel::ERROR } else { LogLevel::INFO }; let data = serde_json::json!({ "method": method, "url": url, "request_body": self.sanitize_api_body(request_body), "response_body": self.sanitize_api_body(response_body), "status_code": status_code, "error": error, "duration_ms": duration_ms }); self.log(level, "API", operation, data, None).await; } /// 记录状态变化 pub async fn log_state_change( &self, component: &str, operation: &str, old_state: Option<&serde_json::Value>, new_state: Option<&serde_json::Value>, trigger: Option<&str>, ) { let data = serde_json::json!({ "component": component, "old_state": self.sanitize_state(old_state), "new_state": self.sanitize_state(new_state), "state_diff": self.calculate_state_diff(old_state, new_state), "trigger": trigger }); self.log(LogLevel::TRACE, "STATE_CHANGE", operation, data, None).await; } /// 通用日志记录方法 pub async fn log( &self, level: LogLevel, module: &str, operation: &str, data: serde_json::Value, context: Option<LogContext>, ) { let log_entry = LogEntry { timestamp: Utc::now().to_rfc3339(), level: level.clone(), module: module.to_string(), operation: operation.to_string(), data, context, stack_trace: if matches!(level, LogLevel::ERROR) { Some(format!("{:?}", std::backtrace::Backtrace::capture())) } else { None }, }; // 添加到队列 if let Ok(mut queue) = self.log_queue.lock() { queue.push(log_entry.clone()); // 如果是错误级别,立即写入 if matches!(level, LogLevel::ERROR) { drop(queue); self.flush_logs().await; } } // 同时输出到控制台 match level { LogLevel::ERROR => error!("[{}] [{}] {}: {:?}", module, operation, log_entry.timestamp, log_entry.data), LogLevel::WARN => warn!("[{}] [{}] {}: {:?}", module, operation, log_entry.timestamp, log_entry.data), LogLevel::INFO => info!("[{}] [{}] {}: {:?}", module, operation, log_entry.timestamp, log_entry.data), _ => tracing::debug!("[{}] [{}] {}: {:?}", module, operation, log_entry.timestamp, log_entry.data), } } /// 刷新日志到文件 pub async fn flush_logs(&self) { let logs = { let mut queue = match self.log_queue.lock() { Ok(queue) => queue, Err(_) => return, }; if queue.is_empty() { return; } let logs = queue.clone(); queue.clear(); logs }; // 按日期和模块分组写入不同文件 let mut grouped_logs: HashMap<String, Vec<LogEntry>> = HashMap::new(); for log in logs { let date = log.timestamp.split('T').next().unwrap_or("unknown").to_string(); let key = format!("{}_{}", date, log.module.to_lowercase()); grouped_logs.entry(key).or_insert_with(Vec::new).push(log); } for (key, group_logs) in grouped_logs { let file_path = self.log_dir.join("backend").join(format!("{}.log", key)); if let Err(e) = self.write_logs_to_file(&file_path, &group_logs) { error!("Failed to write logs to {}: {}", file_path.display(), e); } } } fn write_logs_to_file(&self, file_path: &PathBuf, logs: &[LogEntry]) -> Result<(), Box<dyn std::error::Error>> { let mut file = OpenOptions::new() .create(true) .append(true) .open(file_path)?; for log in logs { let log_line = serde_json::to_string(log)?; writeln!(file, "{}", log_line)?; } file.flush()?; Ok(()) } fn sanitize_database_result(&self, result: Option<&serde_json::Value>) -> Option<serde_json::Value> { result.map(|r| { if let Some(arr) = r.as_array() { if arr.len() > 10 { serde_json::json!({ "_truncated": true, "_count": arr.len(), "_preview": &arr[..5] }) } else { r.clone() } } else { r.clone() } }) } fn sanitize_chat_history(&self, chat_history: Option<&serde_json::Value>) -> Option<serde_json::Value> { chat_history.and_then(|ch| { ch.as_array().map(|arr| { if arr.len() > 10 { serde_json::json!({ "_truncated": true, "_count": arr.len(), "_preview": &arr[..3], "_latest": &arr[arr.len().saturating_sub(2)..] }) } else { serde_json::Value::Array(arr.clone()) } }) }) } fn sanitize_api_body(&self, body: Option<&serde_json::Value>) -> Option<serde_json::Value> { body.map(|b| { let body_str = b.to_string(); if body_str.len() > 1000 { serde_json::json!({ "_truncated": true, "_size": body_str.len(), "_preview": &body_str[..500] }) } else { b.clone() } }) } fn sanitize_state(&self, state: Option<&serde_json::Value>) -> Option<serde_json::Value> { state.map(|s| { // 移除大型数组和对象,只保留关键信息 if let Some(obj) = s.as_object() { let mut sanitized = serde_json::Map::new(); for (key, value) in obj { match key.as_str() { "chatHistory" | "thinkingContent" => { if let Some(arr) = value.as_array() { sanitized.insert(key.clone(), serde_json::json!({ "_type": "array", "_length": arr.len() })); } else { sanitized.insert(key.clone(), serde_json::json!({ "_type": "object", "_size": value.to_string().len() })); } }, _ => { sanitized.insert(key.clone(), value.clone()); } } } serde_json::Value::Object(sanitized) } else { s.clone() } }) } fn calculate_state_diff(&self, old_state: Option<&serde_json::Value>, new_state: Option<&serde_json::Value>) -> serde_json::Value { match (old_state, new_state) { (Some(old), Some(new)) => { if let (Some(old_obj), Some(new_obj)) = (old.as_object(), new.as_object()) { let mut diff = serde_json::Map::new(); // 检查所有键 let mut all_keys = std::collections::HashSet::new(); all_keys.extend(old_obj.keys()); all_keys.extend(new_obj.keys()); for key in all_keys { let old_val = old_obj.get(key); let new_val = new_obj.get(key); if old_val != new_val { diff.insert(key.clone(), serde_json::json!({ "from": old_val, "to": new_val })); } } serde_json::Value::Object(diff) } else { serde_json::json!({ "changed": old != new, "from": old, "to": new }) } }, _ => serde_json::json!({ "from": old_state, "to": new_state }) } } } // Tauri命令,用于从前端写入日志 #[tauri::command] pub async fn write_debug_logs( app: tauri::AppHandle, logs: Vec<LogEntry>, ) -> Result<(), String> { let app_data_dir = app.path_resolver() .app_data_dir() .ok_or("Failed to get app data directory")?; let logger = DebugLogger::new(app_data_dir); // 写入前端日志到frontend目录 let frontend_dir = logger.log_dir.join("frontend"); std::fs::create_dir_all(&frontend_dir).map_err(|e| e.to_string())?; // 按日期分组 let mut grouped_logs: HashMap<String, Vec<LogEntry>> = HashMap::new(); for log in logs { let date = log.timestamp.split('T').next().unwrap_or("unknown").to_string(); let key = format!("{}_{}", date, log.module.to_lowercase()); grouped_logs.entry(key).or_insert_with(Vec::new).push(log); } for (key, group_logs) in grouped_logs { let file_path = frontend_dir.join(format!("{}.log", key)); logger.write_logs_to_file(&file_path, &group_logs) .map_err(|e| e.to_string())?; } Ok(()) } // 全局日志记录器实例 lazy_static::lazy_static! { static ref GLOBAL_LOGGER: Arc<Mutex<Option<DebugLogger>>> = Arc::new(Mutex::new(None)); } /// 初始化全局日志记录器 pub fn init_global_logger(app_data_dir: PathBuf) { if let Ok(mut logger) = GLOBAL_LOGGER.lock() { *logger = Some(DebugLogger::new(app_data_dir)); } } /// 获取全局日志记录器 pub fn get_global_logger() -> Option<DebugLogger> { GLOBAL_LOGGER.lock().ok()?.clone() } /// 便捷宏用于记录日志 #[macro_export] macro_rules! debug_log { ($level:expr, $module:expr, $operation:expr, $data:expr) => { if let Some(logger) = crate::debug_logger::get_global_logger() { tokio::spawn(async move { logger.log($level, $module, $operation, $data, None).await; }); } }; ($level:expr, $module:expr, $operation:expr, $data:expr, $context:expr) => { if let Some(logger) = crate::debug_logger::get_global_logger() { tokio::spawn(async move { logger.log($level, $module, $operation, $data, Some($context)).await; }); } }; }
16,777
debug_logger
rs
en
rust
code
{"qsc_code_num_words": 1727, "qsc_code_num_chars": 16777.0, "qsc_code_mean_word_length": 4.58772438, "qsc_code_frac_words_unique": 0.14707585, "qsc_code_frac_chars_top_2grams": 0.04543733, "qsc_code_frac_chars_top_3grams": 0.04064117, "qsc_code_frac_chars_top_4grams": 0.04291304, "qsc_code_frac_chars_dupe_5grams": 0.40464471, "qsc_code_frac_chars_dupe_6grams": 0.34368295, "qsc_code_frac_chars_dupe_7grams": 0.31667298, "qsc_code_frac_chars_dupe_8grams": 0.30531364, "qsc_code_frac_chars_dupe_9grams": 0.24624511, "qsc_code_frac_chars_dupe_10grams": 0.22251672, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00403566, "qsc_code_frac_chars_whitespace": 0.36490433, "qsc_code_size_file_byte": 16777.0, "qsc_code_num_lines": 521.0, "qsc_code_num_chars_line_max": 136.0, "qsc_code_num_chars_line_mean": 32.20153551, "qsc_code_frac_chars_alphabet": 0.73955889, "qsc_code_frac_chars_comments": 0.02133874, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.29723502, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.05487211, "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}
000ylop/galgame_cn
readme.md
# galgame_cn 如标题所叙,本项目主要收集galgame汉化资源站点/频道 附带一个 `generate_list` 工具来生成markdown文档。 ## 免责声明 本项目只是出于个人兴趣,收集一些入门门槛较低的资源站点/频道。 本项目不保证您通过这些站点/频道下载的资源是安全的,请您自行斟酌。 ## 生成 ```bash cd generate_list && touch ../readme.md && mkdir res && cargo run -- -o ../readme.md -s ../sites.txt && mv res .. ``` ## 频道 [莱茵图书馆](https://t.me/RhineLibrary) [galgame搬运工](https://t.me/gal_porter) [Galgame Patch Collection](https://t.me/galpatch) [Galgame Cloud](https://t.me/galgame_in_telegram) [Galgame频道](https://t.me/Galgamer_channel) [Visual Novel Channel](https://t.me/erogamecloud) [秘密基地之游戏仓储中心](https://t.me/heiheinon) [『雨夜凉亭』ACG频道](https://t.me/yuyeweimian) [夏风小分队](https://t.me/XiafengButter) [黄油仓库](https://t.me/quzimingyue) [Farr的黄油(游)仓库SLG.RPG.ADV.3D](https://t.me/farrslgrpg) [山の黄油阁](https://t.me/HY_QingYan) [里番 黄油聚集地](https://t.me/lifanhuang) [一起钓大鱼](https://t.me/dayuyud) ## 网站 <figure class="image"> <a href="https://galgamer.eu.org"> <img src="res/d0444cdec08d12f61d70b8c31044e08b.webp" alt="Galgamer"></img> </a> <figcaption>主要是介绍博客</figcaption> </figure> <figure class="image"> <a href="https://www.xygalgame.com"> <img src="res/a368d461aa60cede7affa9ada86bdabb.webp" alt="初音的青葱发布页"></img> </a> <figcaption>需要长期签到才可以无限制下载</figcaption> </figure> <figure class="image"> <a href="https://bbs.kfmax.com/"> <img src="res/64f0454e9029767adb5ae68caa84921a.webp" alt="绯月ScarletMoon"></img> </a> <figcaption>绯月</figcaption> </figure> <figure class="image"> <a href="https://sstm.moe/"> <img src="res/012d766c880eacc8cd6cb4f698862a61.webp" alt="SS同盟首页"></img> </a> <figcaption>SS同盟</figcaption> </figure> <figure class="image"> <a href="https://lzacg.org/"> <img src="res/52def5c0828203b948c4e2b7318db193.webp" alt="量子ACG"></img> </a> <figcaption>量子ACG</figcaption> </figure> <figure class="image"> <a href="https://hacg.meme/wp/category/all/game/"> <img src="res/b69be616c4f83786efc3faf36acab2ac.webp" alt="游戏 | 琉璃神社 ★ HACG.LA"></img> </a> <figcaption>琉璃神社</figcaption> </figure> <figure class="image"> <a href="https://blog.reimu.net/"> <img src="res/da51cdf90485ee7c90ffb613cb911bfe.webp" alt="灵梦御所 – 绅士的幻想乡"></img> </a> <figcaption>灵梦御所</figcaption> </figure> <figure class="image"> <a href="https://www.galzy.eu.org/"> <img src="res/3ef4974827e7894f71ea9bc9bf20c2a9.webp" alt="主页 | 紫缘社- Galgame资源站"></img> </a> <figcaption>紫缘社</figcaption> </figure> <figure class="image"> <a href="https://www.banbaog.com/"> <img src="res/ec5b7089407143629af1f4e633d941b0.webp" alt="梦幻星空电脑单机游戏下载-最新PC单机游戏下载,破解单机游戏下载 - 梦幻星空"></img> </a> <figcaption>梦幻星空</figcaption> </figure> <figure class="image"> <a href="https://spare.qingju.org/"> <img src="res/b3a10995eab4897215ab48370df82a95.webp" alt="青桔网-galgame免费分享平台"></img> </a> <figcaption>青桔网,百度云盘</figcaption> </figure> <figure class="image"> <a href="https://www.ymgal.games/"> <img src="res/92465a3a8ecd124c0170edac6ad0443a.webp" alt="月幕Galgame-最戳你XP的美少女游戏综合交流平台 | 来感受这绝妙的文艺体裁"></img> </a> <figcaption>月幕</figcaption> </figure> <figure class="image"> <a href="https://hmoe.top/"> <img src="res/f0e5e8251d4b7678ad4bd82cdb02511f.webp" alt="萌幻之乡"></img> </a> <figcaption>萌幻之乡</figcaption> </figure> <figure class="image"> <a href="https://www.touchgal.com"> <img src="res/5404300909bbfdc9cbf9c0ac9e9726f1.webp" alt="TouchGAL-一站式Galgame文化社区!"></img> </a> <figcaption>TouchGal</figcaption> </figure> <figure class="image"> <a href="https://www.acgnsq.com/"> <img src="res/414d3d342a1f381445df6d966036381b.webp" alt="ACGN社区"></img> </a> <figcaption>ACGN社区</figcaption> </figure> <figure class="image"> <a href="https://www.tianshie.com"> <img src="res/a46207b605878b31788c83e4cacb57ca.webp" alt="天使二次元 — 本站专注ACG,主攻Galgame,兼攻Comic,Anime。以汉化版Galgame为主,为未来Gal中文界培养生力军。"></img> </a> <figcaption>天使二次元</figcaption> </figure> <figure class="image"> <a href="https://moe.best/"> <img src="res/731d3781a6f594a6caea853df1012531.webp" alt="神代綺凛の随波逐流 - 平时都在不务正业些什么?有没有空?可以写多点文章吗?"></img> </a> <figcaption>神代綺凛の随波逐流</figcaption> </figure> <figure class="image"> <a href="https://galgamer.eu.org"> <img src="res/d0444cdec08d12f61d70b8c31044e08b.webp" alt="Galgamer"></img> </a> <figcaption>主要是介绍博客</figcaption> </figure> <figure class="image"> <a href="https://www.ryuugames.com/"> <img src="res/98b63ccf7ce07a629a3ff654a0626a05.webp" alt="Free Download Visual Novel Hentai Games Japanese (RAW) and English Translation - Ryuugames"></img> </a> <figcaption>RyuuGames,有官中和英翻</figcaption> </figure> <figure class="image"> <a href="https://www.mkwgame.com/"> <img src="res/afac9e68d200d2a878f0758dbce9b4d4.webp" alt="梦灵神社 – 梦之神灵 零梦初醒"></img> </a> <figcaption>梦灵神社</figcaption> </figure> <figure class="image"> <a href="https://www.vikacg.com/post"> <img src="res/51699cef745408b068c3329611365456.webp" alt="维咔VikACG[V站] - 肥宅们的欢乐家园"></img> </a> <figcaption>维咔VikACG</figcaption> </figure> <figure class="image"> <a href="https://shinnku.com/"> <img src="res/8eaaddd2f65b786478075c8dbeac6ede.webp" alt="失落小站 - galgame资源站"></img> </a> <figcaption>失落的小站</figcaption> </figure> <figure class="image"> <a href="https://bbs.sumisora.net/"> <img src="res/4fadefab4e3d7b121ab38f8a6f890600.webp" alt="『澄空学园』 GalGame专题网"></img> </a> <figcaption>澄空学园,BBS</figcaption> </figure> [![次元狗 – 动漫资源分享下载,二次元世界](res/58c0a765b2373cce0460a2bbfdecc933.webp)](https://www.acgndog.com/) [![南+ South Plus - powered by Pu!mdHd](res/654ff792a09b35c5a828cdcbd4b61f5f.webp)](https://south-plus.org/ )
5,667
readme
md
zh
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 104.0, "qsc_doc_num_words": 881, "qsc_doc_num_chars": 5667.0, "qsc_doc_num_lines": 229.0, "qsc_doc_mean_word_length": 4.42905789, "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.36662883, "qsc_doc_entropy_unigram": 4.84374526, "qsc_doc_frac_words_all_caps": 0.00997009, "qsc_doc_frac_lines_dupe_lines": 0.43902439, "qsc_doc_frac_chars_dupe_lines": 0.20180665, "qsc_doc_frac_chars_top_2grams": 0.06201948, "qsc_doc_frac_chars_top_3grams": 0.09021015, "qsc_doc_frac_chars_top_4grams": 0.09584828, "qsc_doc_frac_chars_dupe_5grams": 0.30958483, "qsc_doc_frac_chars_dupe_6grams": 0.30138391, "qsc_doc_frac_chars_dupe_7grams": 0.28908252, "qsc_doc_frac_chars_dupe_8grams": 0.28908252, "qsc_doc_frac_chars_dupe_9grams": 0.20963608, "qsc_doc_frac_chars_dupe_10grams": 0.08252178, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 16.2804878, "qsc_doc_frac_chars_hyperlink_html_tag": 0.78065996, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.09283872, "qsc_doc_frac_chars_whitespace": 0.11046409, "qsc_doc_frac_chars_hex_words": 0.0}
0
{"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": 1, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
0015/map_tiles
map_tiles.cpp
#include "map_tiles.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "esp_log.h" #include "esp_heap_caps.h" static const char* TAG = "map_tiles"; // Internal structure for map tiles instance struct map_tiles_t { // Configuration char* base_path; char* tile_folders[MAP_TILES_MAX_TYPES]; int tile_type_count; int current_tile_type; int grid_cols; int grid_rows; int tile_count; int zoom; bool use_spiram; bool initialized; // Tile management int tile_x; int tile_y; int marker_offset_x; int marker_offset_y; bool tile_loading_error; // Tile data - arrays will be allocated dynamically based on actual grid size uint8_t** tile_bufs; lv_image_dsc_t* tile_imgs; }; map_tiles_handle_t map_tiles_init(const map_tiles_config_t* config) { if (!config || !config->base_path || config->tile_type_count <= 0 || config->tile_type_count > MAP_TILES_MAX_TYPES || config->default_tile_type < 0 || config->default_tile_type >= config->tile_type_count) { ESP_LOGE(TAG, "Invalid configuration"); return NULL; } // Validate grid size - use defaults if not specified or invalid int grid_cols = config->grid_cols; int grid_rows = config->grid_rows; if (grid_cols <= 0 || grid_cols > MAP_TILES_MAX_GRID_COLS) { ESP_LOGW(TAG, "Invalid grid_cols %d, using default %d", grid_cols, MAP_TILES_DEFAULT_GRID_COLS); grid_cols = MAP_TILES_DEFAULT_GRID_COLS; } if (grid_rows <= 0 || grid_rows > MAP_TILES_MAX_GRID_ROWS) { ESP_LOGW(TAG, "Invalid grid_rows %d, using default %d", grid_rows, MAP_TILES_DEFAULT_GRID_ROWS); grid_rows = MAP_TILES_DEFAULT_GRID_ROWS; } int tile_count = grid_cols * grid_rows; // Validate that all tile folders are provided for (int i = 0; i < config->tile_type_count; i++) { if (!config->tile_folders[i]) { ESP_LOGE(TAG, "Tile folder %d is NULL", i); return NULL; } } map_tiles_handle_t handle = (map_tiles_handle_t)calloc(1, sizeof(struct map_tiles_t)); if (!handle) { ESP_LOGE(TAG, "Failed to allocate handle"); return NULL; } // Copy base path handle->base_path = strdup(config->base_path); if (!handle->base_path) { ESP_LOGE(TAG, "Failed to allocate base path"); free(handle); return NULL; } // Copy tile folder names handle->tile_type_count = config->tile_type_count; for (int i = 0; i < config->tile_type_count; i++) { handle->tile_folders[i] = strdup(config->tile_folders[i]); if (!handle->tile_folders[i]) { ESP_LOGE(TAG, "Failed to allocate tile folder %d", i); // Clean up previously allocated folders for (int j = 0; j < i; j++) { free(handle->tile_folders[j]); } free(handle->base_path); free(handle); return NULL; } } handle->zoom = config->default_zoom; handle->use_spiram = config->use_spiram; handle->current_tile_type = config->default_tile_type; handle->grid_cols = grid_cols; handle->grid_rows = grid_rows; handle->tile_count = tile_count; handle->initialized = true; handle->tile_loading_error = false; // Initialize tile data - allocate arrays based on actual tile count handle->tile_bufs = (uint8_t**)calloc(tile_count, sizeof(uint8_t*)); handle->tile_imgs = (lv_image_dsc_t*)calloc(tile_count, sizeof(lv_image_dsc_t)); if (!handle->tile_bufs || !handle->tile_imgs) { ESP_LOGE(TAG, "Failed to allocate tile arrays"); // Clean up if (handle->tile_bufs) free(handle->tile_bufs); if (handle->tile_imgs) free(handle->tile_imgs); for (int i = 0; i < handle->tile_type_count; i++) { free(handle->tile_folders[i]); } free(handle->base_path); free(handle); return NULL; } ESP_LOGI(TAG, "Map tiles initialized with base path: %s, %d tile types, current type: %s, zoom: %d, grid: %dx%d", handle->base_path, handle->tile_type_count, handle->tile_folders[handle->current_tile_type], handle->zoom, handle->grid_cols, handle->grid_rows); return handle; } void map_tiles_set_zoom(map_tiles_handle_t handle, int zoom_level) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return; } handle->zoom = zoom_level; ESP_LOGI(TAG, "Zoom level set to %d", zoom_level); } int map_tiles_get_zoom(map_tiles_handle_t handle) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return 0; } return handle->zoom; } bool map_tiles_set_tile_type(map_tiles_handle_t handle, int tile_type) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return false; } if (tile_type < 0 || tile_type >= handle->tile_type_count) { ESP_LOGE(TAG, "Invalid tile type: %d (valid range: 0-%d)", tile_type, handle->tile_type_count - 1); return false; } handle->current_tile_type = tile_type; ESP_LOGI(TAG, "Tile type set to %d (%s)", tile_type, handle->tile_folders[tile_type]); return true; } int map_tiles_get_tile_type(map_tiles_handle_t handle) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return -1; } return handle->current_tile_type; } int map_tiles_get_tile_type_count(map_tiles_handle_t handle) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return 0; } return handle->tile_type_count; } const char* map_tiles_get_tile_type_folder(map_tiles_handle_t handle, int tile_type) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return NULL; } if (tile_type < 0 || tile_type >= handle->tile_type_count) { ESP_LOGE(TAG, "Invalid tile type: %d", tile_type); return NULL; } return handle->tile_folders[tile_type]; } bool map_tiles_load_tile(map_tiles_handle_t handle, int index, int tile_x, int tile_y) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return false; } if (index < 0 || index >= handle->tile_count) { ESP_LOGE(TAG, "Invalid tile index: %d", index); return false; } char path[256]; const char* folder = handle->tile_folders[handle->current_tile_type]; snprintf(path, sizeof(path), "%s/%s/%d/%d/%d.bin", handle->base_path, folder, handle->zoom, tile_x, tile_y); FILE *f = fopen(path, "rb"); if (!f) { ESP_LOGW(TAG, "Tile not found: %s", path); return false; } // Skip 12-byte header fseek(f, 12, SEEK_SET); // Allocate buffer if needed if (!handle->tile_bufs[index]) { uint32_t caps = handle->use_spiram ? (MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) : MALLOC_CAP_DMA; handle->tile_bufs[index] = (uint8_t*)heap_caps_malloc( MAP_TILES_TILE_SIZE * MAP_TILES_TILE_SIZE * MAP_TILES_BYTES_PER_PIXEL, caps); if (!handle->tile_bufs[index]) { ESP_LOGE(TAG, "Tile %d: allocation failed", index); fclose(f); return false; } } // Clear buffer memset(handle->tile_bufs[index], 0, MAP_TILES_TILE_SIZE * MAP_TILES_TILE_SIZE * MAP_TILES_BYTES_PER_PIXEL); // Read tile data size_t bytes_read = fread(handle->tile_bufs[index], 1, MAP_TILES_TILE_SIZE * MAP_TILES_TILE_SIZE * MAP_TILES_BYTES_PER_PIXEL, f); fclose(f); if (bytes_read != MAP_TILES_TILE_SIZE * MAP_TILES_TILE_SIZE * MAP_TILES_BYTES_PER_PIXEL) { ESP_LOGW(TAG, "Incomplete tile read: %zu bytes", bytes_read); } // Setup image descriptor handle->tile_imgs[index].header.w = MAP_TILES_TILE_SIZE; handle->tile_imgs[index].header.h = MAP_TILES_TILE_SIZE; handle->tile_imgs[index].header.cf = MAP_TILES_COLOR_FORMAT; handle->tile_imgs[index].header.stride = MAP_TILES_TILE_SIZE * MAP_TILES_BYTES_PER_PIXEL; handle->tile_imgs[index].data = (const uint8_t*)handle->tile_bufs[index]; handle->tile_imgs[index].data_size = MAP_TILES_TILE_SIZE * MAP_TILES_TILE_SIZE * MAP_TILES_BYTES_PER_PIXEL; handle->tile_imgs[index].reserved = NULL; handle->tile_imgs[index].reserved_2 = NULL; ESP_LOGD(TAG, "Loaded tile %d from %s", index, path); return true; } void map_tiles_gps_to_tile_xy(map_tiles_handle_t handle, double lat, double lon, double* x, double* y) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return; } if (!x || !y) { ESP_LOGE(TAG, "Invalid output parameters"); return; } double lat_rad = lat * M_PI / 180.0; int n = 1 << handle->zoom; *x = (lon + 180.0) / 360.0 * n; *y = (1.0 - log(tan(lat_rad) + 1.0 / cos(lat_rad)) / M_PI) / 2.0 * n; } void map_tiles_tile_xy_to_gps(map_tiles_handle_t handle, double x, double y, double* lat, double* lon) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return; } if (!lat || !lon) { ESP_LOGE(TAG, "Invalid output parameters"); return; } int n = 1 << handle->zoom; *lon = x / n * 360.0 - 180.0; double lat_rad = atan(sinh(M_PI * (1 - 2 * y / n))); *lat = lat_rad * 180.0 / M_PI; } void map_tiles_get_center_gps(map_tiles_handle_t handle, double* lat, double* lon) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return; } if (!lat || !lon) { ESP_LOGE(TAG, "Invalid output parameters"); return; } // Calculate center tile coordinates (center of the grid) double center_x = handle->tile_x + handle->grid_cols / 2.0; double center_y = handle->tile_y + handle->grid_rows / 2.0; // Convert to GPS coordinates map_tiles_tile_xy_to_gps(handle, center_x, center_y, lat, lon); } void map_tiles_set_center_from_gps(map_tiles_handle_t handle, double lat, double lon) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return; } double x, y; map_tiles_gps_to_tile_xy(handle, lat, lon, &x, &y); handle->tile_x = (int)x - handle->grid_cols / 2; handle->tile_y = (int)y - handle->grid_rows / 2; // Calculate pixel offset within the tile handle->marker_offset_x = (int)((x - (int)x) * MAP_TILES_TILE_SIZE); handle->marker_offset_y = (int)((y - (int)y) * MAP_TILES_TILE_SIZE); ESP_LOGI(TAG, "GPS to tile: tile_x=%d, tile_y=%d, offset_x=%d, offset_y=%d", handle->tile_x, handle->tile_y, handle->marker_offset_x, handle->marker_offset_y); } bool map_tiles_is_gps_within_tiles(map_tiles_handle_t handle, double lat, double lon) { if (!handle || !handle->initialized) { return false; } double x, y; map_tiles_gps_to_tile_xy(handle, lat, lon, &x, &y); int gps_tile_x = (int)x; int gps_tile_y = (int)y; bool within_x = (gps_tile_x >= handle->tile_x && gps_tile_x < handle->tile_x + handle->grid_cols); bool within_y = (gps_tile_y >= handle->tile_y && gps_tile_y < handle->tile_y + handle->grid_rows); return within_x && within_y; } void map_tiles_get_position(map_tiles_handle_t handle, int* tile_x, int* tile_y) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return; } if (tile_x) *tile_x = handle->tile_x; if (tile_y) *tile_y = handle->tile_y; } void map_tiles_set_position(map_tiles_handle_t handle, int tile_x, int tile_y) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return; } handle->tile_x = tile_x; handle->tile_y = tile_y; } void map_tiles_get_marker_offset(map_tiles_handle_t handle, int* offset_x, int* offset_y) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return; } if (offset_x) *offset_x = handle->marker_offset_x; if (offset_y) *offset_y = handle->marker_offset_y; } void map_tiles_set_marker_offset(map_tiles_handle_t handle, int offset_x, int offset_y) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return; } handle->marker_offset_x = offset_x; handle->marker_offset_y = offset_y; } lv_image_dsc_t* map_tiles_get_image(map_tiles_handle_t handle, int index) { if (!handle || !handle->initialized || index < 0 || index >= handle->tile_count) { return NULL; } return &handle->tile_imgs[index]; } uint8_t* map_tiles_get_buffer(map_tiles_handle_t handle, int index) { if (!handle || !handle->initialized || index < 0 || index >= handle->tile_count) { return NULL; } return handle->tile_bufs[index]; } void map_tiles_set_loading_error(map_tiles_handle_t handle, bool error) { if (!handle || !handle->initialized) { ESP_LOGE(TAG, "Handle not initialized"); return; } handle->tile_loading_error = error; } bool map_tiles_has_loading_error(map_tiles_handle_t handle) { if (!handle || !handle->initialized) { return true; } return handle->tile_loading_error; } void map_tiles_cleanup(map_tiles_handle_t handle) { if (!handle) { return; } if (handle->initialized) { // Free tile buffers if (handle->tile_bufs) { for (int i = 0; i < handle->tile_count; i++) { if (handle->tile_bufs[i]) { heap_caps_free(handle->tile_bufs[i]); handle->tile_bufs[i] = NULL; } } free(handle->tile_bufs); handle->tile_bufs = NULL; } // Free tile image descriptors array if (handle->tile_imgs) { free(handle->tile_imgs); handle->tile_imgs = NULL; } handle->initialized = false; ESP_LOGI(TAG, "Map tiles cleaned up"); } // Free base path and folder names, then handle if (handle->base_path) { free(handle->base_path); } for (int i = 0; i < handle->tile_type_count; i++) { if (handle->tile_folders[i]) { free(handle->tile_folders[i]); } } free(handle); } void map_tiles_get_grid_size(map_tiles_handle_t handle, int* cols, int* rows) { if (!handle || !handle->initialized || !cols || !rows) { if (cols) *cols = 0; if (rows) *rows = 0; return; } *cols = handle->grid_cols; *rows = handle->grid_rows; } int map_tiles_get_tile_count(map_tiles_handle_t handle) { if (!handle || !handle->initialized) { return 0; } return handle->tile_count; }
15,307
map_tiles
cpp
en
cpp
code
{"qsc_code_num_words": 2110, "qsc_code_num_chars": 15307.0, "qsc_code_mean_word_length": 4.19383886, "qsc_code_frac_words_unique": 0.09241706, "qsc_code_frac_chars_top_2grams": 0.08226918, "qsc_code_frac_chars_top_3grams": 0.03277206, "qsc_code_frac_chars_top_4grams": 0.04407278, "qsc_code_frac_chars_dupe_5grams": 0.5683128, "qsc_code_frac_chars_dupe_6grams": 0.46886654, "qsc_code_frac_chars_dupe_7grams": 0.41665725, "qsc_code_frac_chars_dupe_8grams": 0.3349531, "qsc_code_frac_chars_dupe_9grams": 0.31246469, "qsc_code_frac_chars_dupe_10grams": 0.29879082, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00728645, "qsc_code_frac_chars_whitespace": 0.25583067, "qsc_code_size_file_byte": 15307.0, "qsc_code_num_lines": 509.0, "qsc_code_num_chars_line_max": 119.0, "qsc_code_num_chars_line_mean": 30.07269155, "qsc_code_frac_chars_alphabet": 0.76955491, "qsc_code_frac_chars_comments": 0.05128373, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.26884422, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00251256, "qsc_code_frac_chars_string_length": 0.07753753, "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.02763819, "qsc_codecpp_frac_lines_func_ratio": 0.06030151, "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.20854271, "qsc_codecpp_frac_lines_print": 0.00251256}
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
script/lvgl_map_tile_converter.py
import os import struct import argparse import threading from concurrent.futures import ThreadPoolExecutor, as_completed from PIL import Image # pip install pillow # No implicit defaults; these are set from CLI in main() INPUT_ROOT = None OUTPUT_ROOT = None # Convert RGB to 16-bit RGB565 def to_rgb565(r, g, b): return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3) # Strip .png or .bin extensions def clean_tile_name(filename): name = filename while True: name, ext = os.path.splitext(name) if ext.lower() not in [".png", ".bin", ".jpg", ".jpeg"]: break filename = name return filename # Create LVGL v9-compatible .bin image def make_lvgl_bin(png_path, bin_path): im = Image.open(png_path).convert("RGB") w, h = im.size pixels = im.load() stride = (w * 16 + 7) // 8 # bytes per row (RGB565 = 16 bpp) flags = 0x00 # no compression, no premult color_format = 0x12 # RGB565 magic = 0x19 header = bytearray() header += struct.pack("<B", magic) header += struct.pack("<B", color_format) header += struct.pack("<H", flags) header += struct.pack("<H", w) header += struct.pack("<H", h) header += struct.pack("<H", stride) header += struct.pack("<H", 0) # reserved body = bytearray() for y in range(h): for x in range(w): r, g, b = pixels[x, y] rgb565 = to_rgb565(r, g, b) body += struct.pack("<H", rgb565) os.makedirs(os.path.dirname(bin_path), exist_ok=True) if os.path.isdir(bin_path): # In case a folder mistakenly exists where a file should print(f"[Fix] Removing incorrect folder: {bin_path}") os.rmdir(bin_path) with open(bin_path, "wb") as f: f.write(header) f.write(body) print(f"[OK] {png_path} → {bin_path}") # Yield (input_path, output_path) pairs for all PNG tiles under INPUT_ROOT def _iter_tile_paths(): for zoom in sorted(os.listdir(INPUT_ROOT)): zoom_path = os.path.join(INPUT_ROOT, zoom) if not os.path.isdir(zoom_path) or not zoom.isdigit(): continue for x_tile in sorted(os.listdir(zoom_path)): x_path = os.path.join(zoom_path, x_tile) if not os.path.isdir(x_path) or not x_tile.isdigit(): continue for y_file in sorted(os.listdir(x_path)): if not y_file.lower().endswith(".png"): continue tile_base = clean_tile_name(y_file) input_path = os.path.join(INPUT_ROOT, zoom, x_tile, y_file) output_path = os.path.join(OUTPUT_ROOT, zoom, x_tile, f"{tile_base}.bin") yield input_path, output_path def convert_all_tiles(jobs=1, force=False): """ Convert tiles with optional threading. - jobs: number of worker threads (>=1) - force: if True, re-generate even if output exists """ if not os.path.isdir(INPUT_ROOT): print(f"[ERROR] '{INPUT_ROOT}' not found.") return # Build task list (skip existing unless --force) tasks = [] for input_path, output_path in _iter_tile_paths(): if not force and os.path.isfile(output_path): print(f"[Skip] {output_path}") continue tasks.append((input_path, output_path)) if not tasks: print("[INFO] Nothing to do.") return print(f"[INFO] Converting {len(tasks)} tiles with {jobs} thread(s)...") if jobs <= 1: # Serial path for inp, outp in tasks: try: make_lvgl_bin(inp, outp) except Exception as e: print(f"[Error] Failed to convert {inp} → {e}") return # Threaded path print_lock = threading.Lock() with ThreadPoolExecutor(max_workers=jobs) as ex: future_map = {ex.submit(make_lvgl_bin, inp, outp): (inp, outp) for inp, outp in tasks} for fut in as_completed(future_map): inp, outp = future_map[fut] try: fut.result() except Exception as e: with print_lock: print(f"[Error] Failed to convert {inp} → {e}") if __name__ == "__main__": parser = argparse.ArgumentParser( description="Convert OSM PNG tiles into LVGL-friendly .bin files (RGB565).", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument( "-i", "--input", required=True, default=argparse.SUPPRESS, # hide '(default: None)' help="Input root folder containing tiles in zoom/x/y.png structure", ) parser.add_argument( "-o", "--output", required=True, default=argparse.SUPPRESS, # hide '(default: None)' help="Output root folder where .bin tiles will be written", ) parser.add_argument( "-j", "--jobs", type=int, default=os.cpu_count(), help="Number of worker threads", ) parser.add_argument( "-f", "--force", action="store_true", help="Rebuild even if output file already exists", ) args = parser.parse_args() # Basic checks if not os.path.isdir(args.input): parser.error(f"Input folder not found or not a directory: {args.input}") os.makedirs(args.output, exist_ok=True) # Apply CLI values INPUT_ROOT = args.input OUTPUT_ROOT = args.output convert_all_tiles(jobs=max(1, args.jobs), force=args.force)
5,525
lvgl_map_tile_converter
py
en
python
code
{"qsc_code_num_words": 749, "qsc_code_num_chars": 5525.0, "qsc_code_mean_word_length": 4.2576769, "qsc_code_frac_words_unique": 0.30440587, "qsc_code_frac_chars_top_2grams": 0.02257761, "qsc_code_frac_chars_top_3grams": 0.03512073, "qsc_code_frac_chars_top_4grams": 0.02665412, "qsc_code_frac_chars_dupe_5grams": 0.13421135, "qsc_code_frac_chars_dupe_6grams": 0.07024146, "qsc_code_frac_chars_dupe_7grams": 0.07024146, "qsc_code_frac_chars_dupe_8grams": 0.05330825, "qsc_code_frac_chars_dupe_9grams": 0.05330825, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01338722, "qsc_code_frac_chars_whitespace": 0.28343891, "qsc_code_size_file_byte": 5525.0, "qsc_code_num_lines": 178.0, "qsc_code_num_chars_line_max": 95.0, "qsc_code_num_chars_line_mean": 31.03932584, "qsc_code_frac_chars_alphabet": 0.79136145, "qsc_code_frac_chars_comments": 0.11800905, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.16153846, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.14155629, "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.00413907, "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.03846154, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.04615385, "qsc_codepython_frac_lines_simplefunc": 0.007692307692307693, "qsc_codepython_score_lines_no_logic": 0.12307692, "qsc_codepython_frac_lines_print": 0.07692308}
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}
0015/map_tiles
script/README.md
# **LVGL Map Tile Converter** This Python script is designed to convert a directory of PNG map tiles into a format compatible with LVGL (Light and Versatile Graphics Library) version 9\. The output is a series of binary files (.bin) with a header and pixel data in the RGB565 format, optimized for direct use with LVGL's image APIs. The script is multithreaded and can significantly speed up the conversion process for large tile sets. ## **Features** * **PNG to RGB565 Conversion**: Converts standard 24-bit PNG images into 16-bit RGB565. * **LVGL v9 Compatibility**: Generates a .bin file with the correct LVGL v9 header format. * **Multithreaded Conversion**: Utilizes a ThreadPoolExecutor to process tiles in parallel, configurable with the \--jobs flag. * **Directory Traversal**: Automatically finds and converts all .png files within a specified input directory structure. * **Skip Existing Files**: Skips conversion for tiles that already exist in the output directory unless the \--force flag is used. ## **Requirements** The script requires the Pillow library to handle image processing. You can install it using pip: ```bash pip install Pillow ``` ## **Usage** The script is a command-line tool. You can run it from your terminal with the following arguments: ```bash python lvgl_map_tile_converter.py --input <input_folder> --output <output_folder> [options] ``` ### **Arguments** * \-i, \--input: **Required**. The root folder containing your map tiles. The script expects a tile structure like zoom/x/y.png. * \-o, \--output: **Required**. The root folder where the converted .bin tiles will be saved. The output structure will mirror the input: zoom/x/y.bin. * \-j, \--jobs: **Optional**. The number of worker threads to use for the conversion. Defaults to the number of CPU cores on your system. Using more jobs can speed up the process. * \-f, \--force: **Optional**. If this flag is set, the script will re-convert all tiles, even if the output .bin files already exist. ### **Examples** **1\. Basic conversion with default settings:** ```bash python lvgl_map_tile_converter.py --input ./map_tiles --output ./tiles1 ``` **2\. Conversion using a specific number of threads (e.g., 8):** ```bash python lvgl_map_tile_converter.py --input ./map_tiles --output ./tiles1 --jobs 8 ``` **3\. Forcing a full re-conversion:** ```bash python lvgl_map_tile_converter.py --input ./map_tiles --output ./tiles1 --force ```
2,451
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.22352941, "qsc_doc_num_sentences": 45.0, "qsc_doc_num_words": 371, "qsc_doc_num_chars": 2451.0, "qsc_doc_num_lines": 49.0, "qsc_doc_mean_word_length": 4.8032345, "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.68285063, "qsc_doc_frac_words_all_caps": 0.02352941, "qsc_doc_frac_lines_dupe_lines": 0.27027027, "qsc_doc_frac_chars_dupe_lines": 0.02092926, "qsc_doc_frac_chars_top_2grams": 0.01964085, "qsc_doc_frac_chars_top_3grams": 0.0308642, "qsc_doc_frac_chars_top_4grams": 0.05611672, "qsc_doc_frac_chars_dupe_5grams": 0.11672278, "qsc_doc_frac_chars_dupe_6grams": 0.11672278, "qsc_doc_frac_chars_dupe_7grams": 0.11672278, "qsc_doc_frac_chars_dupe_8grams": 0.11672278, "qsc_doc_frac_chars_dupe_9grams": 0.0959596, "qsc_doc_frac_chars_dupe_10grams": 0.0959596, "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.3655914, "qsc_doc_frac_chars_hyperlink_html_tag": 0.01183191, "qsc_doc_frac_chars_alphabet": 0.84968584, "qsc_doc_frac_chars_digital": 0.01159981, "qsc_doc_frac_chars_whitespace": 0.15585475, "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/map_tiles
examples/basic_map_display.c
#include "map_tiles.h" #include "lvgl.h" #include "esp_log.h" static const char* TAG = "map_example"; // Map tiles handle static map_tiles_handle_t map_handle = NULL; // LVGL objects for displaying tiles static lv_obj_t* map_container = NULL; static lv_obj_t** tile_images = NULL; // Dynamic array for configurable grid static int grid_cols = 0, grid_rows = 0, tile_count = 0; /** * @brief Initialize the map display */ void map_display_init(void) { // Configure 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", .tile_folders = {tile_folders[0], tile_folders[1], tile_folders[2], tile_folders[3]}, .tile_type_count = 4, .default_zoom = 10, .use_spiram = true, .default_tile_type = 0, // Start with street map .grid_cols = 5, // 5x5 grid (configurable) .grid_rows = 5 }; // Initialize map tiles map_handle = map_tiles_init(&config); if (!map_handle) { ESP_LOGE(TAG, "Failed to initialize map tiles"); return; } // Get grid dimensions map_tiles_get_grid_size(map_handle, &grid_cols, &grid_rows); tile_count = map_tiles_get_tile_count(map_handle); // Allocate tile images array tile_images = malloc(tile_count * sizeof(lv_obj_t*)); if (!tile_images) { ESP_LOGE(TAG, "Failed to allocate tile images array"); map_tiles_cleanup(map_handle); return; } // Create map container map_container = lv_obj_create(lv_screen_active()); lv_obj_set_size(map_container, grid_cols * MAP_TILES_TILE_SIZE, grid_rows * MAP_TILES_TILE_SIZE); lv_obj_center(map_container); lv_obj_set_style_pad_all(map_container, 0, 0); lv_obj_set_style_border_width(map_container, 0, 0); // Create image widgets for each tile for (int i = 0; i < tile_count; i++) { tile_images[i] = lv_image_create(map_container); // Position tile in 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); lv_obj_set_size(tile_images[i], MAP_TILES_TILE_SIZE, MAP_TILES_TILE_SIZE); } ESP_LOGI(TAG, "Map display initialized"); } /** * @brief Load and display map tiles for a GPS location * * @param lat Latitude in degrees * @param lon Longitude in degrees */ void map_display_load_location(double lat, double lon) { if (!map_handle) { ESP_LOGE(TAG, "Map not initialized"); return; } ESP_LOGI(TAG, "Loading map for GPS: %.6f, %.6f", lat, lon); // Set center from GPS coordinates map_tiles_set_center_from_gps(map_handle, lat, lon); // Get current tile position int base_tile_x, base_tile_y; map_tiles_get_position(map_handle, &base_tile_x, &base_tile_y); // Load tiles in a configurable grid 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 = base_tile_x + col; int tile_y = base_tile_y + row; // Load the tile bool loaded = map_tiles_load_tile(map_handle, index, tile_x, tile_y); if (loaded) { // Update the image widget lv_image_dsc_t* img_dsc = map_tiles_get_image(map_handle, index); if (img_dsc) { lv_image_set_src(tile_images[index], img_dsc); ESP_LOGD(TAG, "Loaded tile %d (%d, %d)", index, tile_x, tile_y); } } else { ESP_LOGW(TAG, "Failed to load tile %d (%d, %d)", index, tile_x, tile_y); // Set a placeholder or clear the image lv_image_set_src(tile_images[index], NULL); } } } ESP_LOGI(TAG, "Map tiles loaded for location"); } /** * @brief Set the map tile type and reload tiles * * @param tile_type Tile type index (0=street, 1=satellite, 2=terrain, 3=hybrid) * @param lat Current latitude * @param lon Current longitude */ void map_display_set_tile_type(int tile_type, double lat, double lon) { if (!map_handle) { ESP_LOGE(TAG, "Map not initialized"); return; } // Validate tile type int max_types = map_tiles_get_tile_type_count(map_handle); if (tile_type < 0 || tile_type >= max_types) { ESP_LOGW(TAG, "Invalid tile type %d (valid range: 0-%d)", tile_type, max_types - 1); return; } ESP_LOGI(TAG, "Setting tile type to %d (%s)", tile_type, map_tiles_get_tile_type_folder(map_handle, tile_type)); // Set tile type if (map_tiles_set_tile_type(map_handle, tile_type)) { // Reload tiles for the new type map_display_load_location(lat, lon); } } /** * @brief Set the zoom level and reload tiles * * @param zoom New zoom level * @param lat Current latitude * @param lon Current longitude */ void map_display_set_zoom(int zoom, double lat, double lon) { if (!map_handle) { ESP_LOGE(TAG, "Map not initialized"); return; } ESP_LOGI(TAG, "Setting zoom to %d", zoom); // Update zoom level map_tiles_set_zoom(map_handle, zoom); // Reload tiles for the new zoom level map_display_load_location(lat, lon); } /** * @brief Add a GPS marker to the map * * @param lat Latitude in degrees * @param lon Longitude in degrees */ void map_display_add_marker(double lat, double lon) { if (!map_handle) { ESP_LOGE(TAG, "Map not initialized"); return; } // Check if GPS position is within current tiles if (!map_tiles_is_gps_within_tiles(map_handle, lat, lon)) { ESP_LOGW(TAG, "GPS position outside current tiles, reloading map"); map_display_load_location(lat, lon); return; } // Get marker offset within the current tile grid int offset_x, offset_y; map_tiles_get_marker_offset(map_handle, &offset_x, &offset_y); // Create or update marker object static lv_obj_t* marker = NULL; if (!marker) { marker = lv_obj_create(map_container); lv_obj_set_size(marker, 10, 10); lv_obj_set_style_bg_color(marker, lv_color_hex(0xFF0000), 0); lv_obj_set_style_radius(marker, 5, 0); lv_obj_set_style_border_width(marker, 1, 0); lv_obj_set_style_border_color(marker, lv_color_hex(0xFFFFFF), 0); } // Position marker based on GPS offset int center_tile_col = grid_cols / 2; int center_tile_row = grid_rows / 2; int marker_x = center_tile_col * MAP_TILES_TILE_SIZE + offset_x - 5; int marker_y = center_tile_row * MAP_TILES_TILE_SIZE + offset_y - 5; lv_obj_set_pos(marker, marker_x, marker_y); ESP_LOGI(TAG, "GPS marker positioned at (%d, %d)", marker_x, marker_y); } /** * @brief Clean up map display resources */ void map_display_cleanup(void) { if (tile_images) { free(tile_images); tile_images = NULL; } if (map_handle) { map_tiles_cleanup(map_handle); map_handle = NULL; } if (map_container) { lv_obj_delete(map_container); map_container = NULL; } grid_cols = grid_rows = tile_count = 0; ESP_LOGI(TAG, "Map display cleaned up"); } /** * @brief Example usage in main application */ void app_main(void) { // Initialize LVGL and display driver first... // Initialize map display map_display_init(); // Load map for San Francisco double lat = 37.7749; double lon = -122.4194; map_display_load_location(lat, lon); // Add GPS marker map_display_add_marker(lat, lon); // Example: Change to satellite view (tile type 1) // map_display_set_tile_type(1, lat, lon); // Example: Change to terrain view (tile type 2) // map_display_set_tile_type(2, lat, lon); // Example: Change zoom level // map_display_set_zoom(12, lat, lon); // Example: Update GPS position // map_display_add_marker(37.7849, -122.4094); // NOTE: To use different grid sizes, modify the grid_cols and grid_rows // in the config structure above. Examples: // - 3x3 grid: .grid_cols = 3, .grid_rows = 3 (9 tiles, ~1.1MB RAM) // - 5x5 grid: .grid_cols = 5, .grid_rows = 5 (25 tiles, ~3.1MB RAM) // - 7x7 grid: .grid_cols = 7, .grid_rows = 7 (49 tiles, ~6.1MB RAM) }
8,744
basic_map_display
c
en
c
code
{"qsc_code_num_words": 1237, "qsc_code_num_chars": 8744.0, "qsc_code_mean_word_length": 4.11560226, "qsc_code_frac_words_unique": 0.16410671, "qsc_code_frac_chars_top_2grams": 0.05028482, "qsc_code_frac_chars_top_3grams": 0.01728541, "qsc_code_frac_chars_top_4grams": 0.02514241, "qsc_code_frac_chars_dupe_5grams": 0.28756629, "qsc_code_frac_chars_dupe_6grams": 0.18994304, "qsc_code_frac_chars_dupe_7grams": 0.1457474, "qsc_code_frac_chars_dupe_8grams": 0.11196229, "qsc_code_frac_chars_dupe_9grams": 0.11196229, "qsc_code_frac_chars_dupe_10grams": 0.10331958, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01681068, "qsc_code_frac_chars_whitespace": 0.27207228, "qsc_code_size_file_byte": 8744.0, "qsc_code_num_lines": 286.0, "qsc_code_num_chars_line_max": 94.0, "qsc_code_num_chars_line_mean": 30.57342657, "qsc_code_frac_chars_alphabet": 0.78303221, "qsc_code_frac_chars_comments": 0.27470265, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.14375, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.08593504, "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.00252286, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.05, "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.11875, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": 0.01875}
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
include/map_tiles.h
#pragma once #include <stdint.h> #include <stdbool.h> #include "lvgl.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Map tiles component for LVGL 9.x * * This component provides functionality to load and display map tiles with GPS coordinate conversion. * Tiles are assumed to be 256x256 pixels in RGB565 format, stored in binary files. */ // Constants #define MAP_TILES_TILE_SIZE 256 #define MAP_TILES_DEFAULT_GRID_COLS 5 #define MAP_TILES_DEFAULT_GRID_ROWS 5 #define MAP_TILES_MAX_GRID_COLS 9 #define MAP_TILES_MAX_GRID_ROWS 9 #define MAP_TILES_MAX_TILES (MAP_TILES_MAX_GRID_COLS * MAP_TILES_MAX_GRID_ROWS) #define MAP_TILES_BYTES_PER_PIXEL 2 #define MAP_TILES_COLOR_FORMAT LV_COLOR_FORMAT_RGB565 #define MAP_TILES_MAX_TYPES 8 #define MAP_TILES_MAX_FOLDER_NAME 32 /** * @brief Configuration structure for map tiles */ typedef struct { const char* base_path; /**< Base path where tiles are stored (e.g., "/sdcard") */ const char* tile_folders[MAP_TILES_MAX_TYPES]; /**< Array of folder names for different tile types */ int tile_type_count; /**< Number of tile types configured */ int grid_cols; /**< Number of tile columns (default: 5, max: 9) */ int grid_rows; /**< Number of tile rows (default: 5, max: 9) */ int default_zoom; /**< Default zoom level */ bool use_spiram; /**< Whether to use SPIRAM for tile buffers */ int default_tile_type; /**< Default tile type index (0 to tile_type_count-1) */ } map_tiles_config_t; /** * @brief Map tiles handle */ typedef struct map_tiles_t* map_tiles_handle_t; /** * @brief Initialize the map tiles system * * @param config Configuration structure * @return map_tiles_handle_t Handle to the map tiles instance, NULL on failure */ map_tiles_handle_t map_tiles_init(const map_tiles_config_t* config); /** * @brief Set the zoom level * * @param handle Map tiles handle * @param zoom_level Zoom level (typically 0-18) */ void map_tiles_set_zoom(map_tiles_handle_t handle, int zoom_level); /** * @brief Get the current zoom level * * @param handle Map tiles handle * @return Current zoom level */ int map_tiles_get_zoom(map_tiles_handle_t handle); /** * @brief Set tile type * * @param handle Map tiles handle * @param tile_type Tile type index (0 to configured tile_type_count-1) * @return true if tile type was set successfully, false otherwise */ bool map_tiles_set_tile_type(map_tiles_handle_t handle, int tile_type); /** * @brief Get current tile type * * @param handle Map tiles handle * @return Current tile type index, -1 if error */ int map_tiles_get_tile_type(map_tiles_handle_t handle); /** * @brief Get grid dimensions * * @param handle Map tiles handle * @param cols Output grid columns (can be NULL) * @param rows Output grid rows (can be NULL) */ void map_tiles_get_grid_size(map_tiles_handle_t handle, int* cols, int* rows); /** * @brief Get total tile count for current grid * * @param handle Map tiles handle * @return Total number of tiles in the grid, 0 if error */ int map_tiles_get_tile_count(map_tiles_handle_t handle); /** * @brief Get tile type count * * @param handle Map tiles handle * @return Number of configured tile types, 0 if error */ int map_tiles_get_tile_type_count(map_tiles_handle_t handle); /** * @brief Get tile type folder name * * @param handle Map tiles handle * @param tile_type Tile type index * @return Folder name for the tile type, NULL if invalid */ const char* map_tiles_get_tile_type_folder(map_tiles_handle_t handle, int tile_type); /** * @brief Load a specific tile dynamically * * @param handle Map tiles handle * @param index Tile index (0 to total_tile_count-1) * @param tile_x Tile X coordinate * @param tile_y Tile Y coordinate * @return true if tile loaded successfully, false otherwise */ bool map_tiles_load_tile(map_tiles_handle_t handle, int index, int tile_x, int tile_y); /** * @brief Convert GPS coordinates to tile coordinates * * @param handle Map tiles handle * @param lat Latitude in degrees * @param lon Longitude in degrees * @param x Output tile X coordinate * @param y Output tile Y coordinate */ void map_tiles_gps_to_tile_xy(map_tiles_handle_t handle, double lat, double lon, double* x, double* y); /** * @brief Convert tile coordinates to GPS coordinates * * @param handle Map tiles handle * @param x Tile X coordinate * @param y Tile Y coordinate * @param lat Output latitude in degrees * @param lon Output longitude in degrees */ void map_tiles_tile_xy_to_gps(map_tiles_handle_t handle, double x, double y, double* lat, double* lon); /** * @brief Get center GPS coordinates of current map view * * @param handle Map tiles handle * @param lat Output latitude in degrees * @param lon Output longitude in degrees */ void map_tiles_get_center_gps(map_tiles_handle_t handle, double* lat, double* lon); /** * @brief Set the tile center from GPS coordinates * * @param handle Map tiles handle * @param lat Latitude in degrees * @param lon Longitude in degrees */ void map_tiles_set_center_from_gps(map_tiles_handle_t handle, double lat, double lon); /** * @brief Check if GPS coordinates are within current tile grid * * @param handle Map tiles handle * @param lat Latitude in degrees * @param lon Longitude in degrees * @return true if GPS position is within current tiles, false otherwise */ bool map_tiles_is_gps_within_tiles(map_tiles_handle_t handle, double lat, double lon); /** * @brief Get current tile position * * @param handle Map tiles handle * @param tile_x Output tile X coordinate (can be NULL) * @param tile_y Output tile Y coordinate (can be NULL) */ void map_tiles_get_position(map_tiles_handle_t handle, int* tile_x, int* tile_y); /** * @brief Set tile position * * @param handle Map tiles handle * @param tile_x Tile X coordinate * @param tile_y Tile Y coordinate */ void map_tiles_set_position(map_tiles_handle_t handle, int tile_x, int tile_y); /** * @brief Get marker offset within the current tile * * @param handle Map tiles handle * @param offset_x Output X offset in pixels (can be NULL) * @param offset_y Output Y offset in pixels (can be NULL) */ void map_tiles_get_marker_offset(map_tiles_handle_t handle, int* offset_x, int* offset_y); /** * @brief Set marker offset within the current tile * * @param handle Map tiles handle * @param offset_x X offset in pixels * @param offset_y Y offset in pixels */ void map_tiles_set_marker_offset(map_tiles_handle_t handle, int offset_x, int offset_y); /** * @brief Get tile image descriptor * * @param handle Map tiles handle * @param index Tile index (0 to total_tile_count-1) * @return Pointer to LVGL image descriptor, NULL if invalid */ lv_image_dsc_t* map_tiles_get_image(map_tiles_handle_t handle, int index); /** * @brief Get tile buffer * * @param handle Map tiles handle * @param index Tile index (0 to total_tile_count-1) * @return Pointer to tile buffer, NULL if invalid */ uint8_t* map_tiles_get_buffer(map_tiles_handle_t handle, int index); /** * @brief Set tile loading error state * * @param handle Map tiles handle * @param error Error state */ void map_tiles_set_loading_error(map_tiles_handle_t handle, bool error); /** * @brief Check if there's a tile loading error * * @param handle Map tiles handle * @return true if there's an error, false otherwise */ bool map_tiles_has_loading_error(map_tiles_handle_t handle); /** * @brief Clean up and free map tiles resources * * @param handle Map tiles handle */ void map_tiles_cleanup(map_tiles_handle_t handle); #ifdef __cplusplus } #endif
7,960
map_tiles
h
en
c
code
{"qsc_code_num_words": 1212, "qsc_code_num_chars": 7960.0, "qsc_code_mean_word_length": 4.4339934, "qsc_code_frac_words_unique": 0.13778878, "qsc_code_frac_chars_top_2grams": 0.14291031, "qsc_code_frac_chars_top_3grams": 0.13025679, "qsc_code_frac_chars_top_4grams": 0.07257164, "qsc_code_frac_chars_dupe_5grams": 0.5759211, "qsc_code_frac_chars_dupe_6grams": 0.49348716, "qsc_code_frac_chars_dupe_7grams": 0.41049498, "qsc_code_frac_chars_dupe_8grams": 0.33327131, "qsc_code_frac_chars_dupe_9grams": 0.29605508, "qsc_code_frac_chars_dupe_10grams": 0.27502791, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00714626, "qsc_code_frac_chars_whitespace": 0.2089196, "qsc_code_size_file_byte": 7960.0, "qsc_code_num_lines": 264.0, "qsc_code_num_chars_line_max": 127.0, "qsc_code_num_chars_line_mean": 30.15151515, "qsc_code_frac_chars_alphabet": 0.846276, "qsc_code_frac_chars_comments": 0.61432161, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.07272727, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00228013, "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.43636364, "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.6, "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}
000haoji/deep-student
src-tauri/src/models.rs
use serde::{Deserialize, Serialize}; use chrono::{DateTime, Utc}; use std::fmt; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ChatMessage { pub role: String, // "user" 或 "assistant" pub content: String, pub timestamp: DateTime<Utc>, #[serde(default, skip_serializing_if = "Option::is_none")] pub thinking_content: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub rag_sources: Option<Vec<RagSourceInfo>>, // 🎯 修复BUG-05:新增图片字段支持多模态对话 #[serde(default, skip_serializing_if = "Option::is_none")] pub image_paths: Option<Vec<String>>, // 用户消息中包含的图片路径 #[serde(default, skip_serializing_if = "Option::is_none")] pub image_base64: Option<Vec<String>>, // 备用:base64编码的图片数据 } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RagSourceInfo { pub document_id: String, pub file_name: String, pub chunk_text: String, pub score: f32, pub chunk_index: usize, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MistakeItem { pub id: String, pub subject: String, pub created_at: DateTime<Utc>, 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 status: String, // "analyzing", "completed", "error", "summary_required" pub updated_at: DateTime<Utc>, pub chat_history: Vec<ChatMessage>, // 新增字段:用于回顾分析的结构化总结 pub mistake_summary: Option<String>, // 错题简要解析:题目要点、正确解法、关键知识点 pub user_error_analysis: Option<String>, // 用户错误分析:错误原因、思维误区、薄弱点总结 } #[derive(Debug, Deserialize)] pub struct AnalysisRequest { pub subject: String, pub question_image_files: Vec<String>, // base64编码的图片 pub analysis_image_files: Vec<String>, // base64编码的图片 pub user_question: String, #[serde(default)] pub enable_chain_of_thought: bool, // 是否启用思维链 } // 回顾分析数据库表 - 复用错题分析结构但保留特殊性 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ReviewAnalysisItem { pub id: String, // 回顾分析ID pub name: String, // 分析会话名称 pub subject: String, // 科目(继承自关联错题) pub created_at: DateTime<Utc>, // 创建时间 pub updated_at: DateTime<Utc>, // 更新时间 pub mistake_ids: Vec<String>, // 关联的错题ID列表(特殊性) pub consolidated_input: String, // 合并后的输入内容(特殊性) pub user_question: String, // 用户问题描述 pub status: String, // "analyzing", "completed", "error" pub chat_history: Vec<ChatMessage>, // 聊天历史(复用通用结构) // 扩展字段 pub tags: Vec<String>, // 分析标签 pub analysis_type: String, // 分析类型:"consolidated_review" } #[derive(Debug, Serialize)] pub struct AnalysisResponse { pub temp_id: String, pub initial_data: InitialAnalysisData, } #[derive(Debug, Serialize)] pub struct InitialAnalysisData { pub ocr_text: String, pub tags: Vec<String>, pub mistake_type: String, pub first_answer: String, } #[derive(Debug, Deserialize)] pub struct ContinueChatRequest { pub temp_id: String, pub chat_history: Vec<ChatMessage>, pub enable_chain_of_thought: Option<bool>, } #[derive(Debug, Serialize)] pub struct ContinueChatResponse { pub new_assistant_message: String, } #[derive(Debug, Deserialize)] pub struct SaveMistakeRequest { pub temp_id: String, pub final_chat_history: Vec<ChatMessage>, } #[derive(Debug, Serialize)] pub struct SaveMistakeResponse { pub success: bool, pub final_mistake_item: Option<MistakeItem>, } // 回顾分析相关结构 #[derive(Debug, Serialize)] pub struct ReviewSessionResponse { pub review_id: String, pub analysis_summary: String, pub chat_history: Option<Vec<ChatMessage>>, } #[derive(Debug, Deserialize)] pub struct ReviewChatRequest { pub review_id: String, pub new_message: ChatMessage, pub chat_history: Vec<ChatMessage>, } #[derive(Debug, Serialize)] pub struct ReviewChatResponse { pub new_assistant_message: String, pub chain_of_thought_details: Option<serde_json::Value>, } // 回顾分析会话数据结构 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ReviewSession { pub id: String, pub subject: String, pub mistake_ids: Vec<String>, pub analysis_summary: String, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, pub chat_history: Vec<ReviewChatMessage>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ReviewChatMessage { pub id: String, pub session_id: String, pub role: String, // "user" 或 "assistant" pub content: String, pub timestamp: DateTime<Utc>, } // 结构化错误处理 #[derive(Debug, Clone, Serialize, Deserialize)] pub enum AppErrorType { Validation, Database, LLM, FileSystem, NotFound, Configuration, Network, Unknown, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AppError { pub error_type: AppErrorType, pub message: String, pub details: Option<serde_json::Value>, } impl AppError { pub fn new(error_type: AppErrorType, message: impl Into<String>) -> Self { Self { error_type, message: message.into(), details: None, } } pub fn with_details(error_type: AppErrorType, message: impl Into<String>, details: serde_json::Value) -> Self { Self { error_type, message: message.into(), details: Some(details), } } pub fn validation(message: impl Into<String>) -> Self { Self::new(AppErrorType::Validation, message) } pub fn database(message: impl Into<String>) -> Self { Self::new(AppErrorType::Database, message) } pub fn llm(message: impl Into<String>) -> Self { Self::new(AppErrorType::LLM, message) } pub fn file_system(message: impl Into<String>) -> Self { Self::new(AppErrorType::FileSystem, message) } pub fn not_found(message: impl Into<String>) -> Self { Self::new(AppErrorType::NotFound, message) } pub fn configuration(message: impl Into<String>) -> Self { Self::new(AppErrorType::Configuration, message) } pub fn network(message: impl Into<String>) -> Self { Self::new(AppErrorType::Network, message) } pub fn unknown(message: impl Into<String>) -> Self { Self::new(AppErrorType::Unknown, message) } } // 为AppError实现From trait以支持自动转换 impl From<String> for AppError { fn from(message: String) -> Self { AppError::validation(message) } } impl From<&str> for AppError { fn from(message: &str) -> Self { AppError::validation(message.to_string()) } } // 实现Display trait impl fmt::Display for AppError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.message) } } // 实现Error trait impl std::error::Error for AppError {} // 实现从其他错误类型的转换 impl From<zip::result::ZipError> for AppError { fn from(err: zip::result::ZipError) -> Self { AppError::file_system(format!("ZIP操作错误: {}", err)) } } impl From<anyhow::Error> for AppError { fn from(err: anyhow::Error) -> Self { AppError::unknown(err.to_string()) } } impl From<serde_json::Error> for AppError { fn from(err: serde_json::Error) -> Self { AppError::validation(format!("JSON序列化错误: {}", err)) } } impl From<std::io::Error> for AppError { fn from(err: std::io::Error) -> Self { AppError::file_system(format!("文件系统错误: {}", err)) } } // 新增:错题总结生成相关结构 #[derive(Debug, Deserialize)] pub struct GenerateMistakeSummaryRequest { pub mistake_id: String, pub force_regenerate: Option<bool>, // 是否强制重新生成总结 } #[derive(Debug, Serialize)] pub struct GenerateMistakeSummaryResponse { pub success: bool, pub mistake_summary: Option<String>, pub user_error_analysis: Option<String>, pub error_message: Option<String>, } // anyhow 会自动为实现了 std::error::Error 的类型提供转换 // 统一AI接口的输出结构 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct StandardModel1Output { pub ocr_text: String, pub tags: Vec<String>, pub mistake_type: String, pub raw_response: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct StandardModel2Output { pub assistant_message: String, pub raw_response: Option<String>, pub chain_of_thought_details: Option<serde_json::Value>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct StreamChunk { pub content: String, pub is_complete: bool, pub chunk_id: String, } // 模型分配结构 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ModelAssignments { pub model1_config_id: Option<String>, pub model2_config_id: Option<String>, pub review_analysis_model_config_id: Option<String>, // 回顾分析模型配置ID pub anki_card_model_config_id: Option<String>, // 新增: ANKI制卡模型配置ID pub embedding_model_config_id: Option<String>, // 新增: 第五模型(嵌入模型)配置ID pub reranker_model_config_id: Option<String>, // 新增: 第六模型(重排序模型)配置ID pub summary_model_config_id: Option<String>, // 新增: 总结模型配置ID } #[derive(Debug, Deserialize)] pub struct ReviewAnalysisRequest { pub subject: String, pub mistake_ids: Vec<String>, } #[derive(Debug, Serialize)] pub struct Statistics { pub total_mistakes: i32, pub total_reviews: i32, pub subject_stats: std::collections::HashMap<String, i32>, pub type_stats: std::collections::HashMap<String, i32>, pub tag_stats: std::collections::HashMap<String, i32>, pub recent_mistakes: Vec<serde_json::Value>, } #[derive(Debug, Deserialize)] pub struct StartStreamingAnswerRequest { pub temp_id: String, pub enable_chain_of_thought: bool, } // 科目配置系统相关结构 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SubjectConfig { pub id: String, pub subject_name: String, pub display_name: String, pub description: String, pub is_enabled: bool, pub prompts: SubjectPrompts, pub mistake_types: Vec<String>, pub default_tags: Vec<String>, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SubjectPrompts { pub analysis_prompt: String, // 错题分析提示词 pub review_prompt: String, // 回顾分析提示词 pub chat_prompt: String, // 对话追问提示词 pub ocr_prompt: String, // OCR识别提示词 pub classification_prompt: String, // 分类标记提示词 pub consolidated_review_prompt: String, // 统一回顾分析提示词 pub anki_generation_prompt: String, // 新增: ANKI制卡提示词 } // 默认的科目配置模板 impl Default for SubjectPrompts { fn default() -> Self { Self { analysis_prompt: "请仔细分析这道{subject}错题,提供详细的解题思路和知识点讲解。".to_string(), review_prompt: "请分析这些{subject}错题的共同问题和改进建议。".to_string(), chat_prompt: "基于这道{subject}题目,请回答学生的问题。".to_string(), ocr_prompt: "请识别这张{subject}题目图片中的文字内容。".to_string(), classification_prompt: "请分析这道{subject}题目的类型和相关知识点标签。".to_string(), consolidated_review_prompt: "你是一个资深{subject}老师,请仔细阅读以下学生提交的多道错题的详细信息(包括题目原文、原始提问和历史交流)。请基于所有这些信息,对学生提出的总体回顾问题进行全面、深入的分析和解答。请注意识别错题间的关联,总结共性问题,并给出针对性的学习建议。".to_string(), anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。请创建多样化的卡片类型,包括概念定义、要点列举、关系分析等。每张卡片应包含:\n- front(正面):简洁明确的问题或概念名\n- back(背面):详细准确的答案或解释\n- tags(标签):相关的知识点标签\n\n请以JSON数组格式返回结果,每个对象包含 front、back、tags 三个字段。示例格式:[{\"front\": \"什么是...?\", \"back\": \"...的定义是...\", \"tags\": [\"概念\", \"定义\"]}]".to_string(), } } } #[derive(Debug, Deserialize)] pub struct CreateSubjectConfigRequest { pub subject_name: String, pub display_name: String, pub description: Option<String>, pub prompts: Option<SubjectPrompts>, pub mistake_types: Option<Vec<String>>, pub default_tags: Option<Vec<String>>, } #[derive(Debug, Deserialize)] pub struct UpdateSubjectConfigRequest { pub id: String, pub display_name: Option<String>, pub description: Option<String>, pub is_enabled: Option<bool>, pub prompts: Option<SubjectPrompts>, pub mistake_types: Option<Vec<String>>, pub default_tags: Option<Vec<String>>, } // 回顾分析相关的新结构 #[derive(Debug, Deserialize)] pub struct StartConsolidatedReviewAnalysisRequest { pub subject: String, pub consolidated_input: String, pub overall_prompt: String, pub enable_chain_of_thought: bool, pub mistake_ids: Vec<String>, // 参与回顾分析的错题ID列表 } #[derive(Debug, Serialize)] pub struct StartConsolidatedReviewAnalysisResponse { pub review_session_id: String, } #[derive(Debug, Deserialize)] pub struct TriggerConsolidatedReviewStreamRequest { pub review_session_id: String, pub enable_chain_of_thought: bool, } #[derive(Debug, Deserialize)] pub struct ContinueConsolidatedReviewStreamRequest { pub review_session_id: String, pub chat_history: Vec<ChatMessage>, pub enable_chain_of_thought: bool, } // 临时会话数据结构,用于存储回顾分析过程中的状态 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ConsolidatedReviewSession { pub review_session_id: String, pub subject: String, pub consolidated_input: String, pub overall_prompt: String, pub enable_chain_of_thought: bool, pub created_at: DateTime<Utc>, pub chat_history: Vec<ChatMessage>, pub mistake_ids: Vec<String>, // 🎯 新增:关联的错题ID列表,用于获取图片信息 } // ANKI相关结构体 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AnkiGenerationOptions { pub deck_name: String, pub note_type: String, pub enable_images: bool, pub max_cards_per_mistake: i32, #[serde(default)] pub max_tokens: Option<u32>, #[serde(default)] pub temperature: Option<f32>, // 新增:AI行为参数覆盖值 #[serde(default)] pub max_output_tokens_override: Option<u32>, #[serde(default)] pub temperature_override: Option<f32>, // 新增:模板系统参数 #[serde(default)] pub template_id: Option<String>, #[serde(default)] pub custom_anki_prompt: Option<String>, #[serde(default)] pub template_fields: Option<Vec<String>>, // 新增:字段提取规则用于动态解析 #[serde(default)] pub field_extraction_rules: Option<std::collections::HashMap<String, FieldExtractionRule>>, // 新增:用户自定义制卡要求 #[serde(default)] pub custom_requirements: Option<String>, // 新增:任务间重叠区域大小控制 #[serde(default = "default_overlap_size")] pub segment_overlap_size: u32, // 新增:用户自定义系统 prompt #[serde(default)] pub system_prompt: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AnkiCardGenerationResponse { pub success: bool, pub cards: Vec<AnkiCard>, pub error_message: Option<String>, } // 增强的AnkiCard结构体,支持数据库存储和任务关联 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AnkiCard { pub front: String, pub back: String, #[serde(default)] pub text: Option<String>, // 新增:用于Cloze填空题模板 pub tags: Vec<String>, pub images: Vec<String>, // 新增字段用于数据库存储和内部管理 #[serde(default = "default_uuid_id")] pub id: String, #[serde(default)] pub task_id: String, #[serde(default)] pub is_error_card: bool, #[serde(default)] pub error_content: Option<String>, #[serde(default = "default_timestamp")] pub created_at: String, #[serde(default = "default_timestamp")] pub updated_at: String, // 新增:扩展字段支持,用于自定义模板 #[serde(default)] pub extra_fields: std::collections::HashMap<String, String>, #[serde(default)] pub template_id: Option<String>, } // 自定义模板系统相关结构体 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CustomAnkiTemplate { pub id: String, pub name: String, pub description: String, pub author: Option<String>, pub version: String, pub preview_front: String, pub preview_back: String, pub note_type: String, pub fields: Vec<String>, pub generation_prompt: String, pub front_template: String, pub back_template: String, pub css_style: String, // 字段解析规则:指定如何从AI输出中提取和验证字段 pub field_extraction_rules: std::collections::HashMap<String, FieldExtractionRule>, // 模板元数据 pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, pub is_active: bool, pub is_built_in: bool, } // 字段解析规则 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FieldExtractionRule { pub field_type: FieldType, pub is_required: bool, pub default_value: Option<String>, pub validation_pattern: Option<String>, // 正则表达式 pub description: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum FieldType { Text, Array, Number, Boolean, } // 模板创建/更新请求 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CreateTemplateRequest { pub name: String, pub description: String, pub author: Option<String>, pub preview_front: String, pub preview_back: String, pub note_type: String, pub fields: Vec<String>, pub generation_prompt: String, pub front_template: String, pub back_template: String, pub css_style: String, pub field_extraction_rules: std::collections::HashMap<String, FieldExtractionRule>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct UpdateTemplateRequest { pub name: Option<String>, pub description: Option<String>, pub author: Option<String>, pub preview_front: Option<String>, pub preview_back: Option<String>, pub note_type: Option<String>, pub fields: Option<Vec<String>>, pub generation_prompt: Option<String>, pub front_template: Option<String>, pub back_template: Option<String>, pub css_style: Option<String>, pub field_extraction_rules: Option<std::collections::HashMap<String, FieldExtractionRule>>, pub is_active: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TemplateImportRequest { pub template_data: String, // JSON格式的模板数据 pub overwrite_existing: bool, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TemplateExportResponse { pub template_data: String, // JSON格式的模板数据 pub filename: String, } // DocumentTask 结构体 - 支持文档分段任务管理 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DocumentTask { pub id: String, // UUID pub document_id: String, // 关联的原始文档ID pub original_document_name: String, // 原始文档名,用于UI显示 pub segment_index: u32, // 在原始文档中的分段序号 (从0开始) pub content_segment: String, // 该任务对应的文档内容片段 pub status: TaskStatus, // 任务状态 pub created_at: String, // ISO8601 格式时间戳 pub updated_at: String, // ISO8601 格式时间戳 pub error_message: Option<String>, // 存储任务级别的错误信息 pub subject_name: String, // 处理该任务时使用的科目 pub anki_generation_options_json: String, // 存储处理该任务时使用的选项 } // 任务状态枚举 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum TaskStatus { Pending, // 待处理 Processing, // 处理中 (AI正在生成卡片) Streaming, // 正在流式返回卡片 (细化Processing状态) Completed, // 处理完成,所有卡片已生成 Failed, // 任务处理失败 (例如,AI调用失败,无法分段等) Truncated, // AI输出因达到最大长度等原因被截断 Cancelled, // 用户取消 } impl TaskStatus { pub fn to_db_string(&self) -> String { match self { TaskStatus::Pending => "Pending".to_string(), TaskStatus::Processing => "Processing".to_string(), TaskStatus::Streaming => "Streaming".to_string(), TaskStatus::Completed => "Completed".to_string(), TaskStatus::Failed => "Failed".to_string(), TaskStatus::Truncated => "Truncated".to_string(), TaskStatus::Cancelled => "Cancelled".to_string(), } } } // 流式卡片数据结构 #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type", content = "data")] pub enum StreamedCardPayload { NewCard(AnkiCard), // 一个新生成的、完整的卡片 NewErrorCard(AnkiCard), // 一个新生成的、标识错误的卡片 TaskStatusUpdate { task_id: String, status: TaskStatus, message: Option<String>, segment_index: Option<u32>, // 新增: 用于前端关联临时任务 }, // 任务状态更新 TaskProcessingError { task_id: String, error_message: String }, // 任务处理过程中的严重错误 TaskCompleted { task_id: String, final_status: TaskStatus, total_cards_generated: u32 }, // 单个任务完成信号 DocumentProcessingStarted { document_id: String, total_segments: u32 }, //整个文档开始处理,告知总任务数 DocumentProcessingCompleted { document_id: String }, // 整个文档所有任务处理完毕 RateLimitWarning { message: String, retry_after_seconds: Option<u32> }, // API频率限制警告 } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct StreamEvent { pub payload: StreamedCardPayload, } // 默认值辅助函数 fn default_uuid_id() -> String { uuid::Uuid::new_v4().to_string() } fn default_timestamp() -> String { chrono::Utc::now().to_rfc3339() } fn default_overlap_size() -> u32 { 200 // 默认重叠200个字符 } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AnkiExportResponse { pub success: bool, pub file_path: Option<String>, pub card_count: i32, pub error_message: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AnkiConnectResult { pub success: bool, pub result: Option<serde_json::Value>, pub error: Option<String>, } // 新增:ANKI文档制卡请求结构 #[derive(Debug, Deserialize)] pub struct AnkiDocumentGenerationRequest { pub document_content: String, pub subject_name: String, pub options: Option<AnkiGenerationOptions>, } // 新增:ANKI文档制卡响应结构 #[derive(Debug, Serialize)] pub struct AnkiDocumentGenerationResponse { pub success: bool, pub cards: Vec<AnkiCard>, pub error_message: Option<String>, } // ==================== 图片遮罩卡相关数据结构 ==================== // 图片文字识别区域 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TextRegion { pub text: String, // 识别到的文字内容 pub bbox: [f32; 4], // 边界框坐标 [x1, y1, x2, y2] pub confidence: f32, // 识别置信度 pub region_id: String, // 区域唯一标识 } // 图片OCR识别请求 #[derive(Debug, Deserialize)] pub struct ImageOcrRequest { pub image_base64: String, // base64编码的图片数据 pub extract_coordinates: bool, // 是否提取坐标信息 pub target_text: Option<String>, // 可选:指定要识别的目标文字 #[serde(default)] pub vl_high_resolution_images: bool, // 是否启用高分辨率模式(Qwen2.5-VL模型) } // 图片OCR识别响应 #[derive(Debug, Serialize)] pub struct ImageOcrResponse { pub success: bool, pub text_regions: Vec<TextRegion>, // 识别到的文字区域列表 pub full_text: String, // 完整的OCR文字 pub image_width: u32, // 图片宽度 pub image_height: u32, // 图片高度 pub error_message: Option<String>, } // 遮罩区域定义 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct OcclusionMask { pub mask_id: String, // 遮罩唯一标识 pub bbox: [f32; 4], // 遮罩区域坐标 pub original_text: String, // 被遮罩的原始文字 pub hint: Option<String>, // 可选提示信息 pub mask_style: MaskStyle, // 遮罩样式 } // 遮罩样式枚举 #[derive(Debug, Clone, Serialize, Deserialize)] pub enum MaskStyle { SolidColor { color: String }, // 纯色遮罩 BlurEffect { intensity: u8 }, // 模糊效果 Rectangle { color: String, opacity: f32 }, // 半透明矩形 } // 图片遮罩卡片数据结构 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ImageOcclusionCard { pub id: String, // 卡片ID pub task_id: String, // 关联任务ID pub image_path: String, // 原始图片路径 pub image_base64: Option<String>, // 图片base64数据(用于导出) pub image_width: u32, // 图片尺寸 pub image_height: u32, pub masks: Vec<OcclusionMask>, // 遮罩区域列表 pub title: String, // 卡片标题 pub description: Option<String>, // 卡片描述 pub tags: Vec<String>, // 标签 pub created_at: String, // 创建时间 pub updated_at: String, // 更新时间 pub subject: String, // 学科 } // 创建图片遮罩卡请求 #[derive(Debug, Deserialize)] pub struct CreateImageOcclusionRequest { pub image_base64: String, // 图片数据 pub title: String, // 卡片标题 pub description: Option<String>, // 卡片描述 pub subject: String, // 学科 pub tags: Vec<String>, // 标签 pub selected_regions: Vec<String>, // 用户选择的要遮罩的区域ID pub mask_style: MaskStyle, // 遮罩样式 #[serde(default)] pub use_high_resolution: bool, // 是否使用高分辨率模式 } // 图片遮罩卡生成响应 #[derive(Debug, Serialize)] pub struct ImageOcclusionResponse { pub success: bool, pub card: Option<ImageOcclusionCard>, pub error_message: Option<String>, } // ==================== RAG相关数据结构 ==================== use std::collections::HashMap; // 文档块结构 #[derive(Serialize, Deserialize, Debug, Clone)] pub struct DocumentChunk { pub id: String, // UUID for the chunk pub document_id: String, // ID of the source document pub chunk_index: usize, // Order of the chunk within the document pub text: String, pub metadata: HashMap<String, String>, // e.g., filename, page_number } // 带向量的文档块结构 #[derive(Debug, Clone)] pub struct DocumentChunkWithEmbedding { pub chunk: DocumentChunk, pub embedding: Vec<f32>, } // 检索到的文档块结构 #[derive(Serialize, Deserialize, Debug, Clone)] pub struct RetrievedChunk { pub chunk: DocumentChunk, pub score: f32, // Similarity score } // RAG查询选项 #[derive(Serialize, Deserialize, Debug, Clone)] pub struct RagQueryOptions { pub top_k: usize, pub enable_reranking: Option<bool>, // pub filters: Option<HashMap<String, String>>, // Future: metadata-based filtering } // 知识库状态结构 #[derive(Serialize, Deserialize, Debug, Clone)] pub struct KnowledgeBaseStatusPayload { pub total_documents: usize, pub total_chunks: usize, pub embedding_model_name: Option<String>, // Name of the currently used embedding model pub vector_store_type: String, } // RAG设置结构 #[derive(Serialize, Deserialize, Debug, Clone)] pub struct RagSettings { pub knowledge_base_path: String, // Path to the vector store / knowledge base files pub default_embedding_model_id: Option<String>, // ID of ApiConfig to use for embeddings pub default_reranker_model_id: Option<String>, // ID of ApiConfig to use for reranking pub default_top_k: usize, pub enable_rag_by_default: bool, } // RAG增强的分析请求 #[derive(Debug, Deserialize)] pub struct RagEnhancedAnalysisRequest { pub temp_id: String, pub enable_chain_of_thought: bool, pub enable_rag: Option<bool>, pub rag_options: Option<RagQueryOptions>, } // RAG增强的对话请求 #[derive(Debug, Deserialize)] pub struct RagEnhancedChatRequest { pub temp_id: String, pub chat_history: Vec<ChatMessage>, pub enable_chain_of_thought: Option<bool>, pub enable_rag: Option<bool>, pub rag_options: Option<RagQueryOptions>, } // 向量存储统计信息 #[derive(Debug, Clone)] pub struct VectorStoreStats { pub total_documents: usize, pub total_chunks: usize, pub storage_size_bytes: u64, } // 文档上传和处理相关结构 #[derive(Debug, Deserialize)] pub struct DocumentUploadRequest { pub file_paths: Vec<String>, pub chunk_size: Option<usize>, pub chunk_overlap: Option<usize>, pub enable_preprocessing: Option<bool>, } #[derive(Debug, Serialize)] pub struct DocumentProcessingStatus { pub document_id: String, pub file_name: String, pub status: DocumentProcessingStage, pub progress: f32, // 0.0 to 1.0 pub error_message: Option<String>, pub chunks_processed: usize, pub total_chunks: usize, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum DocumentProcessingStage { Pending, Reading, Preprocessing, Chunking, Embedding, Storing, Completed, Failed, } // RAG查询响应结构 #[derive(Debug, Serialize)] pub struct RagQueryResponse { pub retrieved_chunks: Vec<RetrievedChunk>, pub query_vector_time_ms: u64, pub search_time_ms: u64, pub reranking_time_ms: Option<u64>, pub total_time_ms: u64, } // RAG配置结构 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RagConfiguration { pub id: String, pub chunk_size: i32, pub chunk_overlap: i32, pub chunking_strategy: String, // "fixed_size" or "semantic" pub min_chunk_size: i32, pub default_top_k: i32, pub default_rerank_enabled: bool, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } // RAG配置请求 #[derive(Debug, Deserialize)] pub struct RagConfigRequest { pub chunk_size: i32, pub chunk_overlap: i32, pub chunking_strategy: String, pub min_chunk_size: i32, pub default_top_k: i32, pub default_rerank_enabled: bool, } // RAG配置响应 #[derive(Debug, Serialize)] pub struct RagConfigResponse { pub chunk_size: i32, pub chunk_overlap: i32, pub chunking_strategy: String, pub min_chunk_size: i32, pub default_top_k: i32, pub default_rerank_enabled: bool, } // ==================== RAG多分库相关数据结构 ==================== /// RAG分库/子库实体 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SubLibrary { pub id: String, // UUID 主键 pub name: String, // 分库名称,用户定义 pub description: Option<String>, // 可选描述 pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, pub document_count: usize, // 文档数量(查询时计算) pub chunk_count: usize, // 文本块数量(查询时计算) } /// 创建分库请求 #[derive(Debug, Deserialize)] pub struct CreateSubLibraryRequest { pub name: String, pub description: Option<String>, } /// 更新分库请求 #[derive(Debug, Deserialize)] pub struct UpdateSubLibraryRequest { pub name: Option<String>, pub description: Option<String>, } /// 删除分库选项 #[derive(Debug, Deserialize)] pub struct DeleteSubLibraryOptions { /// 是否删除包含的文档,默认false(移到默认分库) pub delete_contained_documents: Option<bool>, } /// 带分库信息的文档上传请求 #[derive(Debug, Deserialize)] pub struct RagAddDocumentsRequest { pub file_paths: Vec<String>, pub sub_library_id: Option<String>, // 目标分库ID,None为默认分库 } /// 带分库信息的Base64文档上传请求 #[derive(Debug, Deserialize)] pub struct RagAddDocumentsFromContentRequest { pub documents: Vec<RagDocumentContent>, pub sub_library_id: Option<String>, // 目标分库ID,None为默认分库 } /// RAG文档内容 #[derive(Debug, Deserialize)] pub struct RagDocumentContent { pub file_name: String, pub base64_content: String, } /// 带分库过滤的RAG查询选项 #[derive(Debug, Deserialize)] pub struct RagQueryOptionsWithLibraries { pub top_k: usize, pub enable_reranking: Option<bool>, pub target_sub_library_ids: Option<Vec<String>>, // 目标分库ID列表,None表示查询所有分库 } /// 获取文档列表请求 #[derive(Debug, Deserialize)] pub struct GetDocumentsRequest { pub sub_library_id: Option<String>, // 分库ID过滤,None表示获取所有文档 pub page: Option<usize>, // 分页页码 pub page_size: Option<usize>, // 每页大小 } /// RAG增强的分析请求(带分库支持) #[derive(Debug, Deserialize)] pub struct RagEnhancedAnalysisRequestWithLibraries { pub temp_id: String, pub enable_chain_of_thought: bool, pub enable_rag: Option<bool>, pub rag_options: Option<RagQueryOptionsWithLibraries>, } /// RAG增强的对话请求(带分库支持) #[derive(Debug, Deserialize)] pub struct RagEnhancedChatRequestWithLibraries { pub temp_id: String, pub chat_history: Vec<ChatMessage>, pub enable_chain_of_thought: Option<bool>, pub enable_rag: Option<bool>, pub rag_options: Option<RagQueryOptionsWithLibraries>, }
31,459
models
rs
en
rust
code
{"qsc_code_num_words": 3530, "qsc_code_num_chars": 31459.0, "qsc_code_mean_word_length": 5.87280453, "qsc_code_frac_words_unique": 0.19093484, "qsc_code_frac_chars_top_2grams": 0.05339829, "qsc_code_frac_chars_top_3grams": 0.05884907, "qsc_code_frac_chars_top_4grams": 0.04582509, "qsc_code_frac_chars_dupe_5grams": 0.50373836, "qsc_code_frac_chars_dupe_6grams": 0.39525349, "qsc_code_frac_chars_dupe_7grams": 0.33457141, "qsc_code_frac_chars_dupe_8grams": 0.23621629, "qsc_code_frac_chars_dupe_9grams": 0.19029473, "qsc_code_frac_chars_dupe_10grams": 0.15532295, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00621367, "qsc_code_frac_chars_whitespace": 0.20706316, "qsc_code_size_file_byte": 31459.0, "qsc_code_num_lines": 1080.0, "qsc_code_num_chars_line_max": 333.0, "qsc_code_num_chars_line_mean": 29.1287037, "qsc_code_frac_chars_alphabet": 0.8247745, "qsc_code_frac_chars_comments": 0.11449824, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.41810919, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00266312, "qsc_code_frac_chars_string_length": 0.02595398, "qsc_code_frac_chars_long_word_length": 0.01565136, "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}
006lp/akashchat-api-go
internal/model/response.go
package model // APIResponse represents the standard API response format type APIResponse struct { Code int `json:"code"` Data interface{} `json:"data"` } // ImageGenerationData represents response data for image generation type ImageGenerationData struct { Model string `json:"model"` JobID string `json:"jobId"` Prompt string `json:"prompt"` Pic string `json:"pic"` } // ErrorData represents error response data type ErrorData struct { Message string `json:"msg"` } // SessionResponse represents the session response from Akash type SessionResponse struct { SessionToken string `json:"session_token,omitempty"` } // OpenAIChatCompletion represents the chat completion response in OpenAI format. type OpenAIChatCompletion struct { ID string `json:"id"` Object string `json:"object"` Created int64 `json:"created"` Model string `json:"model"` Choices []Choice `json:"choices"` Usage Usage `json:"usage"` } // Choice represents a single choice in the chat completion response. type Choice struct { Index int `json:"index"` Message Message `json:"message"` FinishReason string `json:"finish_reason"` } // Message represents a message in the chat completion response. type Message struct { Role string `json:"role"` Content string `json:"content"` } // Usage represents the token usage statistics. type Usage struct { PromptTokens int `json:"prompt_tokens"` CompletionTokens int `json:"completion_tokens"` TotalTokens int `json:"total_tokens"` } // OpenAIStreamCompletion represents the chat completion response in OpenAI stream format. type OpenAIStreamCompletion struct { ID string `json:"id"` Object string `json:"object"` Created int64 `json:"created"` Model string `json:"model"` Choices []OpenAIStreamChoice `json:"choices"` } // OpenAIStreamChoice represents a single choice in the chat completion stream response. type OpenAIStreamChoice struct { Index int `json:"index"` Delta Delta `json:"delta"` FinishReason string `json:"finish_reason,omitempty"` } // Delta represents a delta in the chat completion stream response. type Delta struct { Role string `json:"role,omitempty"` Content string `json:"content,omitempty"` } // OpenAIModel represents a single model in the OpenAI models list. type OpenAIModel struct { ID string `json:"id"` Object string `json:"object"` Created int64 `json:"created"` OwnedBy string `json:"owned_by"` Permission interface{} `json:"permission"` Root string `json:"root"` Parent interface{} `json:"parent"` } // OpenAIModelsList represents the list of OpenAI models. type OpenAIModelsList struct { Object string `json:"object"` Data []OpenAIModel `json:"data"` }
2,862
response
go
en
go
code
{"qsc_code_num_words": 324, "qsc_code_num_chars": 2862.0, "qsc_code_mean_word_length": 6.16358025, "qsc_code_frac_words_unique": 0.2345679, "qsc_code_frac_chars_top_2grams": 0.11517276, "qsc_code_frac_chars_top_3grams": 0.05107661, "qsc_code_frac_chars_top_4grams": 0.05007511, "qsc_code_frac_chars_dupe_5grams": 0.34001002, "qsc_code_frac_chars_dupe_6grams": 0.25888833, "qsc_code_frac_chars_dupe_7grams": 0.23735603, "qsc_code_frac_chars_dupe_8grams": 0.16675013, "qsc_code_frac_chars_dupe_9grams": 0.12468703, "qsc_code_frac_chars_dupe_10grams": 0.12468703, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00262467, "qsc_code_frac_chars_whitespace": 0.20125786, "qsc_code_size_file_byte": 2862.0, "qsc_code_num_lines": 93.0, "qsc_code_num_chars_line_max": 91.0, "qsc_code_num_chars_line_mean": 30.77419355, "qsc_code_frac_chars_alphabet": 0.87095363, "qsc_code_frac_chars_comments": 0.30048917, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.22058824, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.15327009, "qsc_code_frac_chars_long_word_length": 0.02296555, "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.0, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.19117647, "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
main.go
package main import ( "context" "log" "net/http" "sync" "time" "github.com/gin-gonic/gin" "go.uber.org/zap" "github.com/006lp/akashgen-api-go/config" "github.com/006lp/akashgen-api-go/handlers" "github.com/006lp/akashgen-api-go/middleware" ) var ( logger *zap.Logger concurrentLimiter chan struct{} wg sync.WaitGroup ) func init() { var err error logger, err = zap.NewProduction() if err != nil { log.Fatal("Failed to initialize logger:", err) } concurrentLimiter = make(chan struct{}, config.MaxConcurrentRequests) } func main() { gin.SetMode(gin.ReleaseMode) r := gin.New() r.Use(middleware.GinLogger(logger)) r.Use(gin.Recovery()) r.POST("/api/generate", handlers.HandleGenerate(logger, concurrentLimiter, &wg)) r.GET("/health", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"status": "ok"}) }) server := &http.Server{ Addr: ":6571", Handler: r, } go func() { logger.Info("Server starting", zap.String("addr", ":6571")) if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { logger.Fatal("Server failed to start", zap.Error(err)) } }() quit := make(chan struct{}) go func() { time.Sleep(1 * time.Hour) // In production, use signal handling close(quit) }() <-quit logger.Info("Shutting down server...") close(concurrentLimiter) wg.Wait() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := server.Shutdown(ctx); err != nil { logger.Fatal("Server forced to shutdown", zap.Error(err)) } logger.Info("Server exited") }
1,600
main
go
en
go
code
{"qsc_code_num_words": 210, "qsc_code_num_chars": 1600.0, "qsc_code_mean_word_length": 5.03333333, "qsc_code_frac_words_unique": 0.44285714, "qsc_code_frac_chars_top_2grams": 0.03405866, "qsc_code_frac_chars_top_3grams": 0.0397351, "qsc_code_frac_chars_top_4grams": 0.06244087, "qsc_code_frac_chars_dupe_5grams": 0.07663198, "qsc_code_frac_chars_dupe_6grams": 0.07663198, "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.01421092, "qsc_code_frac_chars_whitespace": 0.164375, "qsc_code_size_file_byte": 1600.0, "qsc_code_num_lines": 77.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 20.77922078, "qsc_code_frac_chars_alphabet": 0.776365, "qsc_code_frac_chars_comments": 0.023125, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.06557377, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.22762148, "qsc_code_frac_chars_long_word_length": 0.09398977, "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.03278689, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.06557377, "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
README.md
<center> # AkashGen API Go [![Go Version](https://img.shields.io/badge/Go-1.21+-blue.svg)](https://golang.org) [![License](https://img.shields.io/badge/license-AGPL_v3-green.svg)](LICENSE) [![API](https://img.shields.io/badge/API-REST-orange.svg)](https://restfulapi.net/) A high-performance Go-based API proxy service for the Akash Network's image generation capabilities. This service provides a clean REST API interface to interact with Akash Network's decentralized AI image generation infrastructure. [中文文档](README_CN.md) | [English](README.md) </center> ## Features - 🚀 **High Performance**: Built with Go and Gin framework for optimal performance - 🔄 **Asynchronous Processing**: Non-blocking job submission with status polling - 🛡️ **Concurrency Control**: Built-in rate limiting to prevent resource exhaustion - 📊 **Structured Logging**: Comprehensive logging with Zap for production monitoring - 🏗️ **Clean Architecture**: Modular design following Go best practices - 🌐 **REST API**: Simple and intuitive HTTP endpoints - ⚡ **Graceful Shutdown**: Proper cleanup and connection handling - 🎯 **GPU Preference**: Automatic GPU selection from available options ## Quick Start ### Prerequisites - Go 1.21 or higher - Internet connection to access Akash Network ### Installation 1. **Clone the repository** ```bash git clone https://github.com/006lp/akashgen-api-go.git cd akashgen-api-go ``` 2. **Initialize Go modules** ```bash go mod init akashgen-api-go go mod tidy ``` 3. **Build and run** ```bash go build -o akashgen-api . ./akashgen-api ``` Or run directly: ```bash go run main.go ``` The server will start on port `6571` by default. ## API Documentation ### Generate Image Generate an AI image using Akash Network's decentralized infrastructure. **Endpoint:** `POST /api/generate` **Request Body:** ```json { "prompt": "A beautiful sunset over mountains", "negative": "blurry, low quality", "sampler": "DPM++ 2M Karras", "scheduler": "karras" } ``` **Parameters:** - `prompt` (required): Text description of the desired image - `negative` (optional): Text describing what to avoid in the image - `sampler` (required): The sampling method to use - `scheduler` (required): The scheduling algorithm **Supported Samplers:** ``` euler, euler_cfg_pp, euler_ancestral, euler_ancestral_cfg_pp, heun, heunpp2, dpm_2, dpm_2_ancestral, lms, dpm_fast, dpm_adaptive, dpmpp_2s_ancestral, dpmpp_2s_ancestral_cfg_pp, dpmpp_sde, dpmpp_sde_gpu, dpmpp_2m, dpmpp_2m_cfg_pp, dpmpp_2m_sde, dpmpp_2m_sde_gpu, dpmpp_3m_sde, dpmpp_3m_sde_gpu, ddpm, lcm, ipndm, ipndm_v, deis, ddim, uni_pc, uni_pc_bh2 ``` **Supported Schedulers:** ``` normal, karras, exponential, sgm_uniform, simple, ddim_uniform, beta, linear_quadratic ``` **Response:** - **Success (200)**: Returns the generated image as binary data - **Error (400)**: Invalid request format - **Error (500)**: Generation failed or timeout **Example using curl:** ```bash curl -X POST http://localhost:6571/api/generate \ -H "Content-Type: application/json" \ -d '{ "prompt": "A serene lake with mountains in the background", "negative": "ugly, blurry, low resolution", "sampler": "DPM++ 2M Karras", "scheduler": "karras" }' \ --output generated_image.png ``` ### Health Check Check if the service is running properly. **Endpoint:** `GET /health` **Response:** ```json { "status": "ok" } ``` ## Configuration The service can be configured by modifying the constants in `config/config.go`: ```go const ( // Timeout configurations GenerateTimeout = 30 * time.Second // Max time for generation request StatusTimeout = 10 * time.Second // Max time for status check ImageFetchTimeout = 30 * time.Second // Max time for image download PollingInterval = 1 * time.Second // How often to check job status MaxPollingDuration = 5 * time.Minute // Max time to wait for completion // Concurrency MaxConcurrentRequests = 10 // Max simultaneous requests // Server ServerPort = ":6571" // Port to listen on ) ``` ## Architecture ``` akashgen-api-go/ ├── main.go # Application entry point ├── config/ │ └── config.go # Configuration constants ├── handlers/ │ └── generate.go # HTTP request handlers ├── models/ │ └── types.go # Data structures and types ├── services/ │ ├── akash.go # Akash Network API client │ └── image.go # Image fetching service ├── middleware/ │ └── logger.go # HTTP logging middleware └── utils/ └── http.go # HTTP utilities ``` ### Components - **Handlers**: Process HTTP requests and responses - **Services**: Business logic for interacting with external APIs - **Models**: Data structures for requests and responses - **Middleware**: Cross-cutting concerns like logging - **Config**: Centralized configuration management - **Utils**: Reusable utility functions ## Development ### Project Structure This project follows Go best practices with clear separation of concerns: - Clean architecture with dependency injection - Modular design for easy testing and maintenance - Proper error handling and logging - Context-based timeout management ### Building for Production ```bash # Build optimized binary go build -ldflags="-w -s" -o akashgen-api . # Or build for different platforms GOOS=linux GOARCH=amd64 go build -o akashgen-api-linux . ``` ### Docker Support Create a `Dockerfile`: ```dockerfile FROM golang:1.21-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . RUN go build -o akashgen-api . FROM alpine:latest RUN apk --no-cache add ca-certificates WORKDIR /root/ COPY --from=builder /app/akashgen-api . EXPOSE 6571 CMD ["./akashgen-api"] ``` Build and run: ```bash docker build -t akashgen-api . docker run -p 6571:6571 akashgen-api ``` ## GPU Support The service automatically selects from preferred GPU types in order: 1. RTX4090 2. A10 3. A100 4. V100-32Gi 5. H100 ## Error Handling The API provides detailed error responses: ```json { "error": "Failed to generate image", "details": "specific error description" } ``` Common error scenarios: - Invalid JSON format - Missing required fields - Network timeouts - Upstream service failures - Job execution failures ## Performance - **Concurrency**: Configurable request limiting prevents overload - **Timeouts**: Multiple timeout layers prevent hanging requests - **Connection Pooling**: HTTP client reuse for efficiency - **Memory Management**: Proper cleanup of resources - **Graceful Shutdown**: Clean termination handling ## Monitoring The service provides structured JSON logs suitable for aggregation: ```json { "level": "info", "ts": 1640995200.123456, "msg": "HTTP Request", "method": "POST", "path": "/api/generate", "status": 200, "duration": "2.5s", "client_ip": "192.168.1.100" } ``` ## Contributing 1. Fork the repository 2. Create your feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add some amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ### Development Guidelines - Follow Go conventions and best practices - Add tests for new functionality - Update documentation for API changes - Use meaningful commit messages - Ensure code passes `go fmt` and `go vet` ## Testing ```bash # Run tests go test ./... # Run tests with coverage go test -cover ./... # Run race condition detection go test -race ./... ``` ## Troubleshooting ### Common Issues 1. **Port already in use**: Change the port in `config/config.go` 2. **Timeout errors**: Increase timeout values for slower networks 3. **Memory issues**: Reduce `MaxConcurrentRequests` if experiencing memory pressure 4. **Connection refused**: Ensure Akash Network endpoints are accessible ### Debug Mode For development, you can enable debug logging by modifying the logger initialization in `main.go`: ```go // Replace zap.NewProduction() with: logger, err = zap.NewDevelopment() ``` ## License This project is licensed under the AGPL v3 License - see the [LICENSE](LICENSE) file for details. ## Support - Create an [issue](https://github.com/yourusername/akashgen-api-go/issues) for bugs or feature requests - Check [Akash Network documentation](https://docs.akash.network) for network-related questions - Join the discussion in [Akash Community](https://akash.network/community) ## Acknowledgments - [Akash Network](https://akash.network) for providing decentralized cloud infrastructure - [Gin Web Framework](https://github.com/gin-gonic/gin) for HTTP routing - [Zap](https://github.com/uber-go/zap) for structured logging --- **Note**: This is an unofficial proxy service for Akash Network's image generation API. Please refer to Akash Network's official documentation for the most up-to-date information about their services.
8,992
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0011121, "qsc_doc_frac_words_redpajama_stop": 0.11105063, "qsc_doc_num_sentences": 92.0, "qsc_doc_num_words": 1197, "qsc_doc_num_chars": 8992.0, "qsc_doc_num_lines": 343.0, "qsc_doc_mean_word_length": 5.33834586, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.00874636, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.42188805, "qsc_doc_entropy_unigram": 5.74107019, "qsc_doc_frac_words_all_caps": 0.03756124, "qsc_doc_frac_lines_dupe_lines": 0.18918919, "qsc_doc_frac_chars_dupe_lines": 0.03434034, "qsc_doc_frac_chars_top_2grams": 0.0258216, "qsc_doc_frac_chars_top_3grams": 0.01220657, "qsc_doc_frac_chars_top_4grams": 0.00798122, "qsc_doc_frac_chars_dupe_5grams": 0.04835681, "qsc_doc_frac_chars_dupe_6grams": 0.0172144, "qsc_doc_frac_chars_dupe_7grams": 0.0, "qsc_doc_frac_chars_dupe_8grams": 0.0, "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": 19.16367713, "qsc_doc_frac_chars_hyperlink_html_tag": 0.04826512, "qsc_doc_frac_chars_alphabet": 0.82707972, "qsc_doc_frac_chars_digital": 0.01842703, "qsc_doc_frac_chars_whitespace": 0.16714858, "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}
006lp/akashchat-api-go
internal/model/request.go
package model // ChatMessage represents a chat message type ChatMessage struct { Role string `json:"role" binding:"required"` Content string `json:"content" binding:"required"` } // ChatCompletionRequest represents the incoming request type ChatCompletionRequest struct { Messages []ChatMessage `json:"messages" binding:"required"` Model string `json:"model" binding:"required"` Temperature *float64 `json:"temperature,omitempty"` TopP *float64 `json:"topP,omitempty"` Stream *bool `json:"stream,omitempty"` } // AkashChatRequest represents the request to Akash API type AkashChatRequest struct { ID string `json:"id"` Messages []ChatMessage `json:"messages"` Model string `json:"model"` System string `json:"system"` Temperature float64 `json:"temperature"` TopP float64 `json:"topP"` Context []interface{} `json:"context"` } // ImageStatusResponse represents the image generation status response type ImageStatusResponse struct { JobID string `json:"job_id"` WorkerName string `json:"worker_name"` WorkerCity string `json:"worker_city"` WorkerCountry string `json:"worker_country"` Status string `json:"status"` Result string `json:"result"` WorkerGPU string `json:"worker_gpu"` ElapsedTime float64 `json:"elapsed_time"` QueuePosition int `json:"queue_position"` }
1,454
request
go
en
go
code
{"qsc_code_num_words": 148, "qsc_code_num_chars": 1454.0, "qsc_code_mean_word_length": 6.62162162, "qsc_code_frac_words_unique": 0.39189189, "qsc_code_frac_chars_top_2grams": 0.13265306, "qsc_code_frac_chars_top_3grams": 0.06530612, "qsc_code_frac_chars_top_4grams": 0.06326531, "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.00874126, "qsc_code_frac_chars_whitespace": 0.21320495, "qsc_code_size_file_byte": 1454.0, "qsc_code_num_lines": 40.0, "qsc_code_num_chars_line_max": 71.0, "qsc_code_num_chars_line_mean": 36.35, "qsc_code_frac_chars_alphabet": 0.8479021, "qsc_code_frac_chars_comments": 0.1519945, "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.19448947, "qsc_code_frac_chars_long_word_length": 0.01701783, "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.0, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.125, "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
README_CN.md
<center> # AkashGen API Go [![Go Version](https://img.shields.io/badge/Go-1.21+-blue.svg)](https://golang.org) [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) [![API](https://img.shields.io/badge/API-REST-orange.svg)](https://restfulapi.net/) 一个基于 Go 语言的高性能 API 代理服务,用于访问 Akash Network 的图像生成功能。该服务提供了一个简洁的 REST API 接口,方便与 Akash Network 的去中心化 AI 图像生成基础设施进行交互。 [中文文档](README_CN.md) | [English](README.md) </center> ## 特性 - 🚀 **高性能**: 使用 Go 和 Gin 框架构建,性能优异 - 🔄 **异步处理**: 非阻塞的任务提交和状态轮询机制 - 🛡️ **并发控制**: 内置速率限制防止资源耗尽 - 📊 **结构化日志**: 使用 Zap 记录详细日志,便于生产环境监控 - 🏗️ **清晰架构**: 采用模块化设计,遵循 Go 最佳实践 - 🌐 **REST API**: 简单直观的 HTTP 端点 - ⚡ **优雅关闭**: 正确的清理和连接处理 - 🎯 **GPU 偏好**: 自动从可用选项中选择 GPU ## 快速开始 ### 前置要求 - Go 1.21 或更高版本 - 能够访问 Akash Network 的网络连接 ### 安装 1. **克隆仓库** ```bash git clone https://github.com/006lp/akashgen-api-go.git cd akashgen-api-go ``` 2. **初始化 Go 模块** ```bash go mod init akashgen-api-go go mod tidy ``` 3. **构建并运行** ```bash go build -o akashgen-api . ./akashgen-api ``` 或直接运行: ```bash go run main.go ``` 服务默认会在端口 `6571` 上启动。 ## API 文档 ### 生成图像 使用 Akash Network 的去中心化基础设施生成 AI 图像。 **端点:** `POST /api/generate` **请求体:** ```json { "prompt": "山脉上美丽的日落", "negative": "模糊,低质量", "sampler": "dpmpp_2m", "scheduler": "karras" } ``` > 注意:提示词建议使用英语描述,识别效果更佳。 **参数说明:** - `prompt` (必需): 对期望图像的文本描述 - `negative` (可选): 描述图像中要避免的内容 - `sampler` (必需): 使用的采样方法(详见下方支持的采样器) - `scheduler` (必需): 调度算法(详见下方支持的调度器) **支持的采样器 (Samplers):** ``` euler, euler_cfg_pp, euler_ancestral, euler_ancestral_cfg_pp, heun, heunpp2, dpm_2, dpm_2_ancestral, lms, dpm_fast, dpm_adaptive, dpmpp_2s_ancestral, dpmpp_2s_ancestral_cfg_pp, dpmpp_sde, dpmpp_sde_gpu, dpmpp_2m, dpmpp_2m_cfg_pp, dpmpp_2m_sde, dpmpp_2m_sde_gpu, dpmpp_3m_sde, dpmpp_3m_sde_gpu, ddpm, lcm, ipndm, ipndm_v, deis, ddim, uni_pc, uni_pc_bh2 ``` **支持的调度器 (Schedulers):** ``` normal, karras, exponential, sgm_uniform, simple, ddim_uniform, beta, linear_quadratic ``` **响应:** - **成功 (200)**: 返回生成的图像二进制数据 - **错误 (400)**: 无效的请求格式 - **错误 (500)**: 生成失败或超时 **使用 curl 的示例:** ```bash curl -X POST http://localhost:6571/api/generate \ -H "Content-Type: application/json" \ -d '{ "prompt": "宁静的湖泊,背景是山脉", "negative": "丑陋,模糊,低分辨率", "sampler": "dpmpp_2m", "scheduler": "karras" }' \ --output generated_image.png ``` ### 健康检查 检查服务是否正常运行。 **端点:** `GET /health` **响应:** ```json { "status": "ok" } ``` ## 配置 可以通过修改 `config/config.go` 中的常量来配置服务: ```go const ( // 超时配置 GenerateTimeout = 30 * time.Second // 生成请求最大时间 StatusTimeout = 10 * time.Second // 状态检查最大时间 ImageFetchTimeout = 30 * time.Second // 图像下载最大时间 PollingInterval = 1 * time.Second // 状态检查间隔 MaxPollingDuration = 5 * time.Minute // 等待完成的最大时间 // 并发控制 MaxConcurrentRequests = 10 // 最大同时请求数 // 服务器配置 ServerPort = ":6571" // 监听端口 ) ``` ## 项目架构 ``` akashgen-api-go/ ├── main.go # 应用程序入口点 ├── config/ │ └── config.go # 配置常量 ├── handlers/ │ └── generate.go # HTTP 请求处理器 ├── models/ │ └── types.go # 数据结构和类型 ├── services/ │ ├── akash.go # Akash Network API 客户端 │ └── image.go # 图像获取服务 ├── middleware/ │ └── logger.go # HTTP 日志中间件 └── utils/ └── http.go # HTTP 工具函数 ``` ### 组件说明 - **Handlers**: 处理 HTTP 请求和响应 - **Services**: 与外部 API 交互的业务逻辑 - **Models**: 请求和响应的数据结构 - **Middleware**: 横切关注点,如日志记录 - **Config**: 集中的配置管理 - **Utils**: 可重用的工具函数 ## 开发 ### 项目结构 该项目遵循 Go 最佳实践,关注点清晰分离: - 依赖注入的清晰架构 - 模块化设计,便于测试和维护 - 适当的错误处理和日志记录 - 基于上下文的超时管理 ### 生产构建 ```bash # 构建优化的二进制文件 go build -ldflags="-w -s" -o akashgen-api . # 或为不同平台构建 GOOS=linux GOARCH=amd64 go build -o akashgen-api-linux . ``` ### Docker 支持 创建 `Dockerfile`: ```dockerfile FROM golang:1.21-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . RUN go build -o akashgen-api . FROM alpine:latest RUN apk --no-cache add ca-certificates WORKDIR /root/ COPY --from=builder /app/akashgen-api . EXPOSE 6571 CMD ["./akashgen-api"] ``` 构建和运行: ```bash docker build -t akashgen-api . docker run -p 6571:6571 akashgen-api ``` ## GPU 支持 服务会自动按顺序从首选 GPU 类型中选择: 1. RTX4090 2. A10 3. A100 4. V100-32Gi 5. H100 ## 错误处理 API 提供详细的错误响应: ```json { "error": "生成图像失败", "details": "具体错误描述" } ``` 常见错误场景: - 无效的 JSON 格式 - 缺少必需字段 - 网络超时 - 上游服务失败 - 作业执行失败 ## 性能 - **并发控制**: 可配置的请求限制防止过载 - **超时机制**: 多层超时防止请求挂起 - **连接池**: HTTP 客户端重用提高效率 - **内存管理**: 适当的资源清理 - **优雅关闭**: 干净的终止处理 ## 监控 服务提供适合聚合的结构化 JSON 日志: ```json { "level": "info", "ts": 1640995200.123456, "msg": "HTTP Request", "method": "POST", "path": "/api/generate", "status": 200, "duration": "2.5s", "client_ip": "192.168.1.100" } ``` ## 贡献 1. Fork 这个仓库 2. 创建你的功能分支 (`git checkout -b feature/amazing-feature`) 3. 提交你的更改 (`git commit -m 'Add some amazing feature'`) 4. 推送到分支 (`git push origin feature/amazing-feature`) 5. 开启一个 Pull Request ### 开发指南 - 遵循 Go 约定和最佳实践 - 为新功能添加测试 - 更新 API 变更的文档 - 使用有意义的提交消息 - 确保代码通过 `go fmt` 和 `go vet` ## 测试 ```bash # 运行测试 go test ./... # 运行覆盖率测试 go test -cover ./... # 运行竞态条件检测 go test -race ./... ``` ## 故障排除 ### 常见问题 1. **端口已被占用**: 在 `config/config.go` 中更改端口 2. **超时错误**: 对于较慢的网络,增加超时值 3. **内存问题**: 如果遇到内存压力,减少 `MaxConcurrentRequests` 4. **连接被拒绝**: 确保 Akash Network 端点可访问 ### 调试模式 在开发环境中,可以通过修改 `main.go` 中的日志初始化来启用调试日志: ```go // 将 zap.NewProduction() 替换为: logger, err = zap.NewDevelopment() ``` ## 许可证 该项目基于 AGPL v3 许可证 - 详见 [LICENSE](LICENSE) 文件。 ## 支持 - 为 bug 或功能请求创建 [issue](https://github.com/yourusername/akashgen-api-go/issues) - 查看 [Akash Network 文档](https://docs.akash.network) 了解网络相关问题 - 参与 [Akash 社区](https://akash.network/community) 讨论 ## 致谢 - [Akash Network](https://akash.network) 提供去中心化云基础设施 - [Gin Web Framework](https://github.com/gin-gonic/gin) 用于 HTTP 路由 - [Zap](https://github.com/uber-go/zap) 用于结构化日志 --- **注意**: 这是 Akash Network 图像生成 API 的非官方代理服务。请参考 Akash Network 官方文档获取有关其服务的最新信息。
5,991
README_CN
md
zh
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.00166917, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 93.0, "qsc_doc_num_words": 1237, "qsc_doc_num_chars": 5991.0, "qsc_doc_num_lines": 345.0, "qsc_doc_mean_word_length": 3.04446241, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.00869565, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.4349232, "qsc_doc_entropy_unigram": 5.78176154, "qsc_doc_frac_words_all_caps": 0.02852128, "qsc_doc_frac_lines_dupe_lines": 0.18846154, "qsc_doc_frac_chars_dupe_lines": 0.04843721, "qsc_doc_frac_chars_top_2grams": 0.04381306, "qsc_doc_frac_chars_top_3grams": 0.00557621, "qsc_doc_frac_chars_top_4grams": 0.00531067, "qsc_doc_frac_chars_dupe_5grams": 0.05708975, "qsc_doc_frac_chars_dupe_6grams": 0.0, "qsc_doc_frac_chars_dupe_7grams": 0.0, "qsc_doc_frac_chars_dupe_8grams": 0.0, "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": 12.61818182, "qsc_doc_frac_chars_hyperlink_html_tag": 0.07177433, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.02812564, "qsc_doc_frac_chars_whitespace": 0.18694709, "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}
006lp/akashchat-api-go
pkg/client/http.go
package client import ( "io" "net/http" "time" ) // HTTPClient wraps http.Client with additional functionality type HTTPClient struct { client *http.Client } // NewHTTPClient creates a new HTTPClient instance func NewHTTPClient() *HTTPClient { return &HTTPClient{ client: &http.Client{ Timeout: 60 * time.Second, }, } } // Get performs a GET request with optional headers func (c *HTTPClient) Get(url string, headers map[string]string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } // Add headers for key, value := range headers { req.Header.Set(key, value) } return c.client.Do(req) } // Post performs a POST request with body and optional headers func (c *HTTPClient) Post(url string, body io.Reader, headers map[string]string) (*http.Response, error) { req, err := http.NewRequest("POST", url, body) if err != nil { return nil, err } // Add headers for key, value := range headers { req.Header.Set(key, value) } return c.client.Do(req) }
1,043
http
go
en
go
code
{"qsc_code_num_words": 145, "qsc_code_num_chars": 1043.0, "qsc_code_mean_word_length": 4.95172414, "qsc_code_frac_words_unique": 0.35862069, "qsc_code_frac_chars_top_2grams": 0.04456825, "qsc_code_frac_chars_top_3grams": 0.04456825, "qsc_code_frac_chars_top_4grams": 0.05571031, "qsc_code_frac_chars_dupe_5grams": 0.50139276, "qsc_code_frac_chars_dupe_6grams": 0.4178273, "qsc_code_frac_chars_dupe_7grams": 0.4178273, "qsc_code_frac_chars_dupe_8grams": 0.4178273, "qsc_code_frac_chars_dupe_9grams": 0.4178273, "qsc_code_frac_chars_dupe_10grams": 0.4178273, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00234742, "qsc_code_frac_chars_whitespace": 0.1831256, "qsc_code_size_file_byte": 1043.0, "qsc_code_num_lines": 51.0, "qsc_code_num_chars_line_max": 107.0, "qsc_code_num_chars_line_mean": 20.45098039, "qsc_code_frac_chars_alphabet": 0.84037559, "qsc_code_frac_chars_comments": 0.24161074, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.27777778, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.02651515, "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.08333333, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.27777778, "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
handlers/generate.go
package handlers import ( "context" "net/http" "sync" "github.com/gin-gonic/gin" "go.uber.org/zap" "github.com/006lp/akashgen-api-go/config" "github.com/006lp/akashgen-api-go/models" "github.com/006lp/akashgen-api-go/services" ) // HandleGenerate handles the image generation request func HandleGenerate(logger *zap.Logger, limiter chan struct{}, wg *sync.WaitGroup) gin.HandlerFunc { return func(c *gin.Context) { limiter <- struct{}{} wg.Add(1) defer func() { <-limiter wg.Done() }() var req models.GenerateRequest if err := c.ShouldBindJSON(&req); err != nil { logger.Warn("Invalid JSON request", zap.Error(err)) c.JSON(http.StatusBadRequest, gin.H{ "error": "Invalid JSON", "details": err.Error(), }) return } logger.Info("Received generate request", zap.String("prompt", req.Prompt), zap.String("sampler", req.Sampler), zap.String("scheduler", req.Scheduler), ) upstreamReq := models.UpstreamGenerateRequest{ Prompt: req.Prompt, Negative: req.Negative, Sampler: req.Sampler, Scheduler: req.Scheduler, PreferredGpu: config.PreferredGPUs(), } ctx, cancel := context.WithTimeout(context.Background(), config.GenerateTimeout) defer cancel() akashService := services.NewAkashService(logger) jobID, err := akashService.SendGenerateRequest(ctx, upstreamReq) if err != nil { logger.Error("Failed to generate image", zap.Error(err)) c.JSON(http.StatusInternalServerError, gin.H{ "error": "Failed to generate image", "details": err.Error(), }) return } logger.Info("Generate request sent successfully", zap.String("job_id", jobID)) resultURL, err := akashService.PollJobStatus(ctx, jobID) if err != nil { logger.Error("Failed to poll job status", zap.Error(err), zap.String("job_id", jobID)) c.JSON(http.StatusInternalServerError, gin.H{ "error": "Failed to poll job status", "details": err.Error(), }) return } imageService := services.NewImageService(logger) imageCtx, imageCancel := context.WithTimeout(context.Background(), config.ImageFetchTimeout) defer imageCancel() imageData, contentType, err := imageService.FetchImage(imageCtx, resultURL) if err != nil { logger.Error("Failed to fetch image", zap.Error(err), zap.String("result_url", resultURL)) c.JSON(http.StatusInternalServerError, gin.H{ "error": "Failed to fetch image", "details": err.Error(), }) return } logger.Info("Image fetched successfully", zap.String("job_id", jobID), zap.String("content_type", contentType), zap.Int("size", len(imageData)), ) c.Data(http.StatusOK, contentType, imageData) } }
2,696
generate
go
en
go
code
{"qsc_code_num_words": 318, "qsc_code_num_chars": 2696.0, "qsc_code_mean_word_length": 5.77987421, "qsc_code_frac_words_unique": 0.33333333, "qsc_code_frac_chars_top_2grams": 0.03917301, "qsc_code_frac_chars_top_3grams": 0.04243743, "qsc_code_frac_chars_top_4grams": 0.04570185, "qsc_code_frac_chars_dupe_5grams": 0.3835691, "qsc_code_frac_chars_dupe_6grams": 0.2921654, "qsc_code_frac_chars_dupe_7grams": 0.16648531, "qsc_code_frac_chars_dupe_8grams": 0.08324266, "qsc_code_frac_chars_dupe_9grams": 0.08324266, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00445831, "qsc_code_frac_chars_whitespace": 0.16802671, "qsc_code_size_file_byte": 2696.0, "qsc_code_num_lines": 99.0, "qsc_code_num_chars_line_max": 101.0, "qsc_code_num_chars_line_mean": 27.23232323, "qsc_code_frac_chars_alphabet": 0.81497994, "qsc_code_frac_chars_comments": 0.02002967, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.2195122, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.20741862, "qsc_code_frac_chars_long_word_length": 0.05412566, "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.01219512, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.08536585, "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
models/types.go
package models // GenerateRequest represents the incoming request for image generation type GenerateRequest struct { Prompt string `json:"prompt" binding:"required"` Negative string `json:"negative"` Sampler string `json:"sampler" binding:"required"` Scheduler string `json:"scheduler" binding:"required"` } // UpstreamGenerateRequest represents the request sent to upstream API type UpstreamGenerateRequest struct { Prompt string `json:"prompt"` Negative string `json:"negative"` Sampler string `json:"sampler"` Scheduler string `json:"scheduler"` PreferredGpu []string `json:"preferred_gpu"` } // UpstreamStatusResponse represents the status response from upstream API type UpstreamStatusResponse struct { JobID string `json:"job_id"` WorkerName string `json:"worker_name"` WorkerCity string `json:"worker_city"` WorkerCountry string `json:"worker_country"` Status string `json:"status"` Result string `json:"result"` WorkerGPU string `json:"worker_gpu"` ElapsedTime float64 `json:"elapsed_time"` QueuePosition int `json:"queue_position"` } // GenerateJobResponse represents the response from generate request type GenerateJobResponse struct { JobID string `json:"job_id"` }
1,276
types
go
en
go
code
{"qsc_code_num_words": 136, "qsc_code_num_chars": 1276.0, "qsc_code_mean_word_length": 6.83088235, "qsc_code_frac_words_unique": 0.39705882, "qsc_code_frac_chars_top_2grams": 0.18299247, "qsc_code_frac_chars_top_3grams": 0.06889128, "qsc_code_frac_chars_top_4grams": 0.04736276, "qsc_code_frac_chars_dupe_5grams": 0.22389666, "qsc_code_frac_chars_dupe_6grams": 0.16361679, "qsc_code_frac_chars_dupe_7grams": 0.10764263, "qsc_code_frac_chars_dupe_8grams": 0.10764263, "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.00188679, "qsc_code_frac_chars_whitespace": 0.169279, "qsc_code_size_file_byte": 1276.0, "qsc_code_num_lines": 36.0, "qsc_code_num_chars_line_max": 75.0, "qsc_code_num_chars_line_mean": 35.44444444, "qsc_code_frac_chars_alphabet": 0.8745283, "qsc_code_frac_chars_comments": 0.22178683, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.14285714, "qsc_code_cate_autogen": 1.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.19416499, "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.0, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.14285714, "qsc_codego_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": 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": 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_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}
003random/getJS
runner/runner.go
package runner import ( "bufio" "crypto/tls" "errors" "fmt" "io" "log" "net/http" "net/url" "sync" "github.com/003random/getJS/v2/extractor" ) // ExtractionPoints defines the default HTML tags and their attributes from which JavaScript sources are extracted. var ExtractionPoints = map[string][]string{ "script": {"src", "data-src"}, } // New creates a new runner with the provided options. func New(options *Options) *runner { http.DefaultClient.Transport = &http.Transport{ TLSHandshakeTimeout: options.Request.Timeout, TLSClientConfig: &tls.Config{ InsecureSkipVerify: options.Request.InsecureSkipVerify, }, } http.DefaultClient.Timeout = options.Request.Timeout return &runner{ Options: *options, Results: make(chan url.URL), } } // Run starts processing the inputs and extracts JavaScript sources into the runner's Results channel. func (r *runner) Run() error { if !r.Options.Verbose { log.SetOutput(io.Discard) } go func() { for _, input := range r.Options.Inputs { switch input.Type { case InputURL: r.ProcessURLs(input.Data) case InputResponse: r.ProcessResponse(input.Data) } if input, ok := input.Data.(io.Closer); ok { input.Close() } } close(r.Results) }() r.listen() return nil } func (r *runner) listen() { for s := range r.Results { for _, output := range r.Options.Outputs { _, err := output.Write([]byte(fmt.Sprintf("%s\n", s.String()))) if err != nil { log.Println(fmt.Errorf("[error] writing result %s to output: %v", s.String(), err)) } } } for _, output := range r.Options.Outputs { if o, ok := output.(io.Closer); ok { o.Close() } } } // ProcessURLs will fetch the HTTP response for all URLs in the provided reader // and stream the extracted sources to the runner's Results channel. func (r *runner) ProcessURLs(data io.Reader) { var ( next = Read(data) wg = sync.WaitGroup{} throttle = make(chan struct{}, r.Options.Threads) ) for i := 0; i < r.Options.Threads; i++ { throttle <- struct{}{} } for { u, err := next() if errors.Is(err, io.EOF) { break } if err != nil { log.Println(fmt.Errorf("[error] parsing url %v: %w", u, err)) continue } wg.Add(1) go func(u *url.URL) { defer func() { throttle <- struct{}{} wg.Done() }() resp, err := extractor.FetchResponse(u.String(), r.Options.Request.Method, r.Options.Request.Headers) if err != nil { log.Println(fmt.Errorf("[error] fetching response for url %s: %w", u.String(), err)) return } defer resp.Body.Close() sources, err := extractor.ExtractSources(resp.Body) if err != nil { log.Println(fmt.Errorf("[error] extracting sources from response for url %s: %w", u.String(), err)) return } filtered, err := extractor.Filter(sources, r.filters(u)...) if err != nil { log.Println(fmt.Errorf("[error] filtering sources for url %s: %w", u.String(), err)) return } for source := range filtered { r.Results <- source } }(u) <-throttle } wg.Wait() } // Read is a wrapper around the bufio.Scanner Text() method. // Upon reading from the input, the line is automatically parsed to a *url.URL. // An io.EOF error is returned when there are no more lines. func Read(input io.Reader) func() (*url.URL, error) { scanner := bufio.NewScanner(input) return func() (*url.URL, error) { if !scanner.Scan() { return nil, io.EOF } return url.Parse(scanner.Text()) } } func (r *runner) ProcessResponse(data io.Reader) { sources, err := extractor.ExtractSources(data) if err != nil { log.Println(fmt.Errorf("[error] extracting sources from response file: %w", err)) } filtered, err := extractor.Filter(sources, r.filters(nil)...) if err != nil { log.Println(fmt.Errorf("[error] filtering sources from response file: %w", err)) return } for source := range filtered { r.Results <- source } } func (r *runner) filters(base *url.URL) (options []func([]url.URL) []url.URL) { if r.Options.Complete && base != nil { options = append(options, extractor.WithComplete(base)) } if r.Options.Resolve { options = append(options, extractor.WithResolve()) } return }
4,195
runner
go
en
go
code
{"qsc_code_num_words": 568, "qsc_code_num_chars": 4195.0, "qsc_code_mean_word_length": 4.80985915, "qsc_code_frac_words_unique": 0.3028169, "qsc_code_frac_chars_top_2grams": 0.02928258, "qsc_code_frac_chars_top_3grams": 0.0204978, "qsc_code_frac_chars_top_4grams": 0.02818448, "qsc_code_frac_chars_dupe_5grams": 0.25988287, "qsc_code_frac_chars_dupe_6grams": 0.25988287, "qsc_code_frac_chars_dupe_7grams": 0.2295022, "qsc_code_frac_chars_dupe_8grams": 0.19948755, "qsc_code_frac_chars_dupe_9grams": 0.13323572, "qsc_code_frac_chars_dupe_10grams": 0.07979502, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00177567, "qsc_code_frac_chars_whitespace": 0.19451728, "qsc_code_size_file_byte": 4195.0, "qsc_code_num_lines": 185.0, "qsc_code_num_chars_line_max": 116.0, "qsc_code_num_chars_line_mean": 22.67567568, "qsc_code_frac_chars_alphabet": 0.80674756, "qsc_code_frac_chars_comments": 0.14707986, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.15172414, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.11319173, "qsc_code_frac_chars_long_word_length": 0.01089994, "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.04827586, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.12413793, "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/akashchat-api-go
README.md
# akashchat-api-go 基于 Go 语言开发的 REST API 服务,为 Akash Chat API 提供代理接口,支持文本和图像生成模型。 [![Go Version](https://img.shields.io/badge/Go-1.21+-blue.svg)](https://golang.org) [![License](https://img.shields.io/badge/license-AGPL_v3-green.svg)](LICENSE) [中文文档](README.md) | [English](README_EN.md) ## 功能特性 - **统一 API 接口**: 兼容 OpenAI ChatGPT API 格式 - **文本生成**: 支持多种文本生成模型,并支持流式响应 - **图像生成**: 支持 AkashGen 图像生成模型 - **会话管理**: 自动会话令牌缓存和刷新 - **错误处理**: 全面的错误处理和验证 - **可配置**: 基于环境变量的配置 - **Docker 支持**: 提供即用的 Docker 配置 ## 快速开始 ### 前置要求 - Go 1.21 或更高版本 - Git ### 安装 1. 克隆仓库: ```bash git clone https://github.com/006lp/akashchat-api-go.git cd akashchat-api-go ``` 2. 安装依赖: ```bash go mod tidy ``` 3. 运行应用: ```bash go run cmd/server/main.go ``` 服务器默认在 `localhost:16571` 启动。 ### 使用 Docker #### 从 Docker Hub 拉取镜像 ```bash docker pull 006lp/akashchat-api-go:latest ``` #### 本地构建 1. 构建 Docker 镜像: ```bash docker build -t 006lp/akashchat-api-go . ``` 2. 运行容器: ```bash docker run -p 16571:16571 006lp/akashchat-api-go ``` ## API 使用 ### 文本生成 向 `/v1/chat/completions` 发送 POST 请求: ```bash curl -X POST http://localhost:16571/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "messages": [ { "role": "user", "content": "你好,你怎么样?" } ], "model": "Meta-Llama-3-3-70B-Instruct", "temperature": 0.85, "topP": 1.0 }' ``` **响应:** ```json { "choices": [ { "finish_reason": "stop", "index": 0, "message": { "content": "你好!我很好,谢谢你的询问...", "role": "assistant" } } ], "created": 1755506652, "id": "chatcmpl-1755506652.79333", "model": "Meta-Llama-3-3-70B-Instruct", "object": "chat.completion", "usage": { "completion_tokens": 0, "prompt_tokens": 0, "total_tokens": 0 } } ``` ### 图像生成 使用 `AkashGen` 模型进行图像生成: ```bash curl -X POST http://localhost:16571/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "messages": [ { "role": "user", "content": "一个蓝眼睛的可爱动漫女孩" } ], "model": "AkashGen", "temperature": 0.85 }' ``` **响应:** ```json { "code": 200, "data": { "model": "AkashGen", "jobId": "727ef62f-76c9-45b8-9637-dc461590fe49", "prompt": "一个蓝眼睛的可爱动漫女孩,有着彩色头发和闪亮的蓝眼睛...", "pic": "https://chat.akash.network/api/image/job_727ef62f_00001_.webp" } } ``` ### 获取模型列表 获取所有可用模型的列表: ```bash curl http://localhost:16571/v1/models ``` **响应:** ```json { "data": [ { "id": "openai-gpt-oss-120b", "object": "model", "created": 1626777600, "owned_by": "Akash Network", "permission": null, "root": "openai-gpt-oss-120b", "parent": null }, { "id": "Qwen3-235B-A22B-Instruct-2507-FP8", "object": "model", "created": 1626777600, "owned_by": "Akash Network", "permission": null, "root": "Qwen3-235B-A22B-Instruct-2507-FP8", "parent": null } ], "object": "list" } ``` ### 健康检查 检查服务是否正常运行: ```bash curl http://localhost:16571/health ``` ## 配置 应用程序可以通过环境变量进行配置: | 变量 | 默认值 | 描述 | |------|--------|------| | `SERVER_ADDRESS` | `localhost:16571` | 服务器地址和端口 | | `AKASH_BASE_URL` | `https://chat.akash.network` | Akash Chat API 基础 URL | 示例: ```bash export SERVER_ADDRESS="0.0.0.0:8080" export AKASH_BASE_URL="https://chat.akash.network" go run cmd/server/main.go ``` ## 项目结构 ``` akashchat-api-go/ ├── cmd/server/ # 应用程序入口 ├── internal/ # 私有应用程序代码 │ ├── config/ # 配置管理 │ ├── handler/ # HTTP 请求处理器 │ ├── model/ # 数据模型 │ ├── service/ # 业务逻辑 │ └── utils/ # 工具函数 ├── pkg/ # 公共包 │ └── client/ # HTTP 客户端封装 ├── Dockerfile # Docker 配置 └── README.md # 说明文档 ``` ## API 参数 ### 请求参数 | 参数 | 类型 | 必需 | 默认值 | 描述 | |------|------|------|--------|------| | `messages` | 数组 | 是 | - | 消息对象数组 | | `model` | 字符串 | 是 | - | 模型名称(例如:"Meta-Llama-3-3-70B-Instruct"、"AkashGen") | | `temperature` | 浮点数 | 否 | 0.85 | 采样温度(0.0-2.0) | | `topP` | 浮点数 | 否 | 1.0 | Top-p 采样参数 | | `stream` | 布尔值 | 否 | false | 是否启用流式响应 | ### 消息对象 | 字段 | 类型 | 必需 | 描述 | |------|------|------|------| | `role` | 字符串 | 是 | 消息角色("user"、"assistant"、"system") | | `content` | 字符串 | 是 | 消息内容 | ## 错误处理 API 返回标准化的错误响应: ```json { "code": 500, "data": { "msg": "Error Model." } } ``` 常见错误代码: - `400`: 请求错误(无效 JSON 或缺少必需字段) - `500`: 内部服务器错误(无效模型、API 错误) ## 开发 ### 运行测试 ```bash go test ./... ``` ### 构建 ```bash go build -o bin/akashchat-api-go cmd/server/main.go ``` ### 代码结构 项目遵循标准的 Go 项目布局: - **cmd/**: 项目的主要应用程序 - **internal/**: 私有应用程序和库代码 - **pkg/**: 可以被外部应用程序使用的库代码 ## 贡献 1. Fork 仓库 2. 创建你的功能分支 (`git checkout -b feature/amazing-feature`) 3. 提交你的更改 (`git commit -m '添加一些很棒的功能'`) 4. 推送到分支 (`git push origin feature/amazing-feature`) 5. 打开一个 Pull Request ## 许可证 本项目采用 AGPL v3 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情。 ## 致谢 - [Gin Web Framework](https://github.com/gin-gonic/gin) - HTTP Web 框架 - [Akash Network](https://akash.network/) - 去中心化云计算平台 ## 支持 如果你遇到任何问题或有疑问,请在 GitHub 上[创建 issue](https://github.com/006lp/akashchat-api-go/issues)。 ## 部署说明 ### 本地开发 1. 确保已安装 Go 1.21+ 2. 克隆项目并进入目录 3. 运行 `go mod tidy` 安装依赖 4. 运行 `go run cmd/server/main.go` 启动服务 ### 生产部署 推荐使用 Docker 进行部署: ```bash # 构建镜像 docker build -t akashchat-api-go:latest . # 运行容器 docker run -d \ --name akashchat-api \ -p 16571:16571 \ -e SERVER_ADDRESS="0.0.0.0:16571" \ akashchat-api-go:latest ``` ### 注意事项 - 会话令牌有效期为 1 小时,系统会自动处理刷新 - 图像生成请求可能需要较长时间,系统会自动轮询直到完成 - 建议在生产环境中设置适当的请求超时和限流策略
5,558
README
md
zh
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.00539763, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 72.0, "qsc_doc_num_words": 967, "qsc_doc_num_chars": 5558.0, "qsc_doc_num_lines": 330.0, "qsc_doc_mean_word_length": 3.26783868, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0030303, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.40641158, "qsc_doc_entropy_unigram": 5.55666445, "qsc_doc_frac_words_all_caps": 0.02588352, "qsc_doc_frac_lines_dupe_lines": 0.37647059, "qsc_doc_frac_chars_dupe_lines": 0.17988986, "qsc_doc_frac_chars_top_2grams": 0.04556962, "qsc_doc_frac_chars_top_3grams": 0.04873418, "qsc_doc_frac_chars_top_4grams": 0.03006329, "qsc_doc_frac_chars_dupe_5grams": 0.25506329, "qsc_doc_frac_chars_dupe_6grams": 0.22468354, "qsc_doc_frac_chars_dupe_7grams": 0.16265823, "qsc_doc_frac_chars_dupe_8grams": 0.10379747, "qsc_doc_frac_chars_dupe_9grams": 0.10379747, "qsc_doc_frac_chars_dupe_10grams": 0.10379747, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 12.79404467, "qsc_doc_frac_chars_hyperlink_html_tag": 0.04372076, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.06040423, "qsc_doc_frac_chars_whitespace": 0.21662469, "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}
006lp/akashchat-api-go
README_EN.md
# akashchat-api-go A Go-based REST API service that provides a proxy interface to Akash Chat API, supporting both text and image generation models. [![Go Version](https://img.shields.io/badge/Go-1.21+-blue.svg)](https://golang.org) [![License](https://img.shields.io/badge/license-AGPL_v3-green.svg)](LICENSE) [中文文档](README.md) | [English](README_EN.md) ## Features - **Unified API Interface**: Compatible with OpenAI ChatGPT API format - **Text Generation**: Support for various text generation models, including streaming support. - **Image Generation**: Support for AkashGen image generation model - **Session Management**: Automatic session token caching and refresh - **Error Handling**: Comprehensive error handling and validation - **Configurable**: Environment-based configuration - **Docker Support**: Ready-to-use Docker configuration ## Quick Start ### Prerequisites - Go 1.21 or higher - Git ### Installation 1. Clone the repository: ```bash git clone https://github.com/006lp/akashchat-api-go.git cd akashchat-api-go ``` 2. Install dependencies: ```bash go mod tidy ``` 3. Run the application: ```bash go run cmd/server/main.go ``` The server will start on `localhost:16571` by default. ### Using Docker #### Pull from Docker Hub ```bash docker pull 006lp/akashchat-api-go:latest ``` #### Build Locally 1. Build the Docker image: ```bash docker build -t 006lp/akashchat-api-go . ``` 2. Run the container: ```bash docker run -p 16571:16571 006lp/akashchat-api-go ``` ## API Usage ### Text Generation Send a POST request to `/v1/chat/completions`: ```bash curl -X POST http://localhost:16571/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "messages": [ { "role": "user", "content": "Hello, how are you?" } ], "model": "Meta-Llama-3-3-70B-Instruct", "temperature": 0.85, "topP": 1.0 }' ``` **Response:** ```json { "choices": [ { "finish_reason": "stop", "index": 0, "message": { "content": "Hello! I'm doing well, thank you for asking...", "role": "assistant" } } ], "created": 1755506652, "id": "chatcmpl-1755506652.79333", "model": "Meta-Llama-3-3-70B-Instruct", "object": "chat.completion", "usage": { "completion_tokens": 0, "prompt_tokens": 0, "total_tokens": 0 } } ``` ### Image Generation Use the `AkashGen` model for image generation: ```bash curl -X POST http://localhost:16571/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "messages": [ { "role": "user", "content": "a cute anime girl with blue eyes" } ], "model": "AkashGen", "temperature": 0.85 }' ``` **Response:** ```json { "code": 200, "data": { "model": "AkashGen", "jobId": "727ef62f-76c9-45b8-9637-dc461590fe49", "prompt": "a cute anime girl with pastel-colored hair and sparkling blue eyes...", "pic": "https://chat.akash.network/api/image/job_727ef62f_00001_.webp" } } ``` ### Get Model List Get a list of all available models: ```bash curl http://localhost:16571/v1/models ``` **Response:** ```json { "data": [ { "id": "openai-gpt-oss-120b", "object": "model", "created": 1626777600, "owned_by": "Akash Network", "permission": null, "root": "openai-gpt-oss-120b", "parent": null }, { "id": "Qwen3-235B-A22B-Instruct-2507-FP8", "object": "model", "created": 1626777600, "owned_by": "Akash Network", "permission": null, "root": "Qwen3-235B-A22B-Instruct-2507-FP8", "parent": null } ], "object": "list" } ``` ### Health Check Check if the service is running: ```bash curl http://localhost:16571/health ``` ## Configuration The application can be configured using environment variables: | Variable | Default | Description | |----------|---------|-------------| | `SERVER_ADDRESS` | `localhost:16571` | Server address and port | | `AKASH_BASE_URL` | `https://chat.akash.network` | Akash Chat API base URL | Example: ```bash export SERVER_ADDRESS="0.0.0.0:8080" export AKASH_BASE_URL="https://chat.akash.network" go run cmd/server/main.go ``` ## Project Structure ``` akashchat-api-go/ ├── cmd/server/ # Application entry point ├── internal/ # Private application code │ ├── config/ # Configuration management │ ├── handler/ # HTTP request handlers │ ├── model/ # Data models │ ├── service/ # Business logic │ └── utils/ # Utility functions ├── pkg/ # Public packages │ └── client/ # HTTP client wrapper ├── Dockerfile # Docker configuration └── README.md # This file ``` ## API Parameters ### Request Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `messages` | Array | Yes | - | Array of message objects | | `model` | String | Yes | - | Model name (e.g., "Meta-Llama-3-3-70B-Instruct", "AkashGen") | | `temperature` | Float | No | 0.85 | Sampling temperature (0.0-2.0) | | `topP` | Float | No | 1.0 | Top-p sampling parameter | | `stream` | Boolean | No | false | Enable streaming response | ### Message Object | Field | Type | Required | Description | |-------|------|----------|-------------| | `role` | String | Yes | Message role ("user", "assistant", "system") | | `content` | String | Yes | Message content | ## Error Handling The API returns standardized error responses: ```json { "code": 500, "data": { "msg": "Error Model." } } ``` Common error codes: - `400`: Bad Request (invalid JSON or missing required fields) - `500`: Internal Server Error (invalid model, API errors) ## Development ### Running Tests ```bash go test ./... ``` ### Building ```bash go build -o bin/akashchat-api-go cmd/server/main.go ``` ### Code Structure The project follows standard Go project layout: - **cmd/**: Main applications for this project - **internal/**: Private application and library code - **pkg/**: Library code that's ok to use by external applications ## Contributing 1. Fork the repository 2. Create your feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add some amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ## License This project is licensed under the AGPL v3 License - see the [LICENSE](LICENSE) file for details. ## Acknowledgments - [Gin Web Framework](https://github.com/gin-gonic/gin) - HTTP web framework - [Akash Network](https://akash.network/) - Decentralized cloud compute platform ## Support If you encounter any issues or have questions, please [open an issue](https://github.com/006lp/akashchat-api-go/issues) on GitHub.
6,845
README_EN
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.00438276, "qsc_doc_frac_words_redpajama_stop": 0.07509628, "qsc_doc_num_sentences": 64.0, "qsc_doc_num_words": 855, "qsc_doc_num_chars": 6845.0, "qsc_doc_num_lines": 299.0, "qsc_doc_mean_word_length": 5.06081871, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.00334448, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.39415205, "qsc_doc_entropy_unigram": 5.45846777, "qsc_doc_frac_words_all_caps": 0.02824134, "qsc_doc_frac_lines_dupe_lines": 0.40343348, "qsc_doc_frac_chars_dupe_lines": 0.14288008, "qsc_doc_frac_chars_top_2grams": 0.02495956, "qsc_doc_frac_chars_top_3grams": 0.02911948, "qsc_doc_frac_chars_top_4grams": 0.02195517, "qsc_doc_frac_chars_dupe_5grams": 0.17656575, "qsc_doc_frac_chars_dupe_6grams": 0.14605963, "qsc_doc_frac_chars_dupe_7grams": 0.118789, "qsc_doc_frac_chars_dupe_8grams": 0.0758031, "qsc_doc_frac_chars_dupe_9grams": 0.0758031, "qsc_doc_frac_chars_dupe_10grams": 0.0758031, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 17.45283019, "qsc_doc_frac_chars_hyperlink_html_tag": 0.03550037, "qsc_doc_frac_chars_alphabet": 0.73605813, "qsc_doc_frac_chars_digital": 0.04287012, "qsc_doc_frac_chars_whitespace": 0.19576333, "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}
006lp/akashchat-api-go
cmd/server/main.go
package main import ( "log" "github.com/006lp/akashchat-api-go/internal/config" "github.com/006lp/akashchat-api-go/internal/handler" "github.com/006lp/akashchat-api-go/internal/service" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) func main() { // Load configuration cfg := config.Load() // Initialize services sessionService := service.NewSessionService() akashService := service.NewAkashService() // Initialize handlers chatHandler := handler.NewChatHandler(sessionService, akashService) modelHandler := handler.NewModelHandler() // Setup Gin router r := gin.Default() // Setup CORS r.Use(cors.New(cors.Config{ AllowAllOrigins: true, AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}, AllowHeaders: []string{"*"}, ExposeHeaders: []string{"*"}, AllowCredentials: true, })) // Setup routes v1 := r.Group("/v1") { v1.POST("/chat/completions", chatHandler.ChatCompletions) v1.GET("/models", modelHandler.GetModels) } // Health check endpoint r.GET("/health", func(c *gin.Context) { c.JSON(200, gin.H{ "status": "ok", "message": "akashchat-api-go is running", }) }) // Start server log.Printf("Starting server on %s", cfg.ServerAddress) if err := r.Run(cfg.ServerAddress); err != nil { log.Fatal("Failed to start server: ", err) } }
1,356
main
go
en
go
code
{"qsc_code_num_words": 159, "qsc_code_num_chars": 1356.0, "qsc_code_mean_word_length": 5.77358491, "qsc_code_frac_words_unique": 0.55345912, "qsc_code_frac_chars_top_2grams": 0.04901961, "qsc_code_frac_chars_top_3grams": 0.06100218, "qsc_code_frac_chars_top_4grams": 0.0751634, "qsc_code_frac_chars_dupe_5grams": 0.11764706, "qsc_code_frac_chars_dupe_6grams": 0.11764706, "qsc_code_frac_chars_dupe_7grams": 0.11764706, "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.01384083, "qsc_code_frac_chars_whitespace": 0.14749263, "qsc_code_size_file_byte": 1356.0, "qsc_code_num_lines": 57.0, "qsc_code_num_chars_line_max": 90.0, "qsc_code_num_chars_line_mean": 23.78947368, "qsc_code_frac_chars_alphabet": 0.78027682, "qsc_code_frac_chars_comments": 0.11135693, "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.29709544, "qsc_code_frac_chars_long_word_length": 0.1659751, "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.02564103, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.05128205, "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/akashchat-api-go
internal/service/akash.go
package service import ( "bufio" "bytes" "encoding/json" "fmt" "io" "net/http" "regexp" "strings" "time" "github.com/006lp/akashchat-api-go/internal/model" "github.com/006lp/akashchat-api-go/internal/utils" "github.com/006lp/akashchat-api-go/pkg/client" ) // AkashService handles communication with Akash API type AkashService struct { httpClient *client.HTTPClient } // NewAkashService creates a new AkashService instance func NewAkashService() *AkashService { return &AkashService{ httpClient: client.NewHTTPClient(), } } // ProcessImageGeneration handles image generation requests func (a *AkashService) ProcessImageGeneration(req model.ChatCompletionRequest, sessionToken string, temperature, topP float64) (*model.ImageGenerationData, error) { // Create Akash chat request akashReq := model.AkashChatRequest{ ID: utils.GenerateRandomID(16), Messages: req.Messages, Model: req.Model, System: getSystemPrompt(), Temperature: temperature, TopP: topP, Context: []interface{}{}, } // Send chat request respText, err := a.sendChatRequest(akashReq, sessionToken) if err != nil { return nil, err } // Check for error response if strings.Contains(respText, "error") && strings.Contains(respText, "Invalid model name") { return nil, fmt.Errorf("invalid model") } // Extract jobId and prompt from response jobID, prompt, err := a.extractImageGenerationInfo(respText) if err != nil { return nil, fmt.Errorf("failed to extract image generation info: %w", err) } // Poll for image completion imageURL, err := a.pollImageStatus(jobID) if err != nil { return nil, fmt.Errorf("failed to get image result: %w", err) } return &model.ImageGenerationData{ Model: req.Model, JobID: jobID, Prompt: prompt, Pic: imageURL, }, nil } // ProcessTextGeneration handles text generation requests func (a *AkashService) ProcessTextGeneration(req model.ChatCompletionRequest, sessionToken string, temperature, topP float64) (*model.OpenAIChatCompletion, error) { // Create Akash chat request akashReq := model.AkashChatRequest{ ID: utils.GenerateRandomID(16), Messages: req.Messages, Model: req.Model, System: getSystemPrompt(), Temperature: temperature, TopP: topP, Context: []interface{}{}, } // Send chat request respText, err := a.sendChatRequest(akashReq, sessionToken) if err != nil { return nil, err } // Check for error response if strings.Contains(respText, "error") && strings.Contains(respText, "Invalid model name") { return nil, fmt.Errorf("invalid model") } // Extract and format the response openAIResp := a.extractTextGenerationInfo(respText, req.Model) return openAIResp, nil } // ProcessTextGenerationStream handles text generation requests with streaming func (a *AkashService) ProcessTextGenerationStream(req model.ChatCompletionRequest, sessionToken string, temperature, topP float64, writer io.Writer) error { akashReq := model.AkashChatRequest{ ID: utils.GenerateRandomID(16), Messages: req.Messages, Model: req.Model, System: getSystemPrompt(), Temperature: temperature, TopP: topP, Context: []interface{}{}, } respBody, err := a.sendStreamChatRequest(akashReq, sessionToken) if err != nil { return err } defer respBody.Close() // Process the stream return a.processStream(respBody, req.Model, writer) } func (a *AkashService) processStream(body io.Reader, modelName string, writer io.Writer) error { scanner := bufio.NewScanner(body) var messageID string var contentStarted bool for scanner.Scan() { line := scanner.Text() line = strings.TrimSpace(line) if strings.HasPrefix(line, "f:{\"messageId\":") { msgIDRegex := regexp.MustCompile(`"messageId":"([^"]+)"`) match := msgIDRegex.FindStringSubmatch(line) if len(match) > 1 { messageID = "chatcmpl-" + match[1] } contentStarted = true // Send initial stream message streamResp := model.OpenAIStreamCompletion{ ID: messageID, Object: "chat.completion.chunk", Created: time.Now().Unix(), Model: modelName, Choices: []model.OpenAIStreamChoice{ { Index: 0, Delta: model.Delta{ Role: "assistant", }, }, }, } a.writeStreamResponse(writer, streamResp) continue } if strings.HasPrefix(line, "e:{\"finishReason\":") { reasonRegex := regexp.MustCompile(`"finishReason":"([^"]+)"`) match := reasonRegex.FindStringSubmatch(line) var finishReason string if len(match) > 1 { finishReason = match[1] } // Send final stream message streamResp := model.OpenAIStreamCompletion{ ID: messageID, Object: "chat.completion.chunk", Created: time.Now().Unix(), Model: modelName, Choices: []model.OpenAIStreamChoice{ { Index: 0, Delta: model.Delta{}, FinishReason: finishReason, }, }, } a.writeStreamResponse(writer, streamResp) break } if contentStarted && strings.HasPrefix(line, "0:\"") { content := line[3:] content = strings.TrimSuffix(content, "\"") content = strings.ReplaceAll(content, "\\n", "\n") content = strings.ReplaceAll(content, "\\\"", "\"") streamResp := model.OpenAIStreamCompletion{ ID: messageID, Object: "chat.completion.chunk", Created: time.Now().Unix(), Model: modelName, Choices: []model.OpenAIStreamChoice{ { Index: 0, Delta: model.Delta{ Content: content, }, }, }, } a.writeStreamResponse(writer, streamResp) } } if err := scanner.Err(); err != nil { return fmt.Errorf("error reading stream: %w", err) } return nil } func (a *AkashService) writeStreamResponse(writer io.Writer, resp model.OpenAIStreamCompletion) { var buf bytes.Buffer enc := json.NewEncoder(&buf) enc.SetEscapeHTML(false) enc.Encode(resp) fmt.Fprintf(writer, "data: %s\n\n", buf.String()) if flusher, ok := writer.(http.Flusher); ok { flusher.Flush() } } // sendStreamChatRequest sends a request to Akash chat API and returns the response body as a stream func (a *AkashService) sendStreamChatRequest(req model.AkashChatRequest, sessionToken string) (io.ReadCloser, error) { jsonData, err := json.Marshal(req) if err != nil { return nil, fmt.Errorf("failed to marshal request: %w", err) } headers := map[string]string{ "Referer": "https://chat.akash.network/", "Cookie": sessionToken, "Accept": "*/*", "Content-Type": "application/json", } resp, err := a.httpClient.Post("https://chat.akash.network/api/chat/", bytes.NewBuffer(jsonData), headers) if err != nil { return nil, fmt.Errorf("failed to send chat request: %w", err) } return resp.Body, nil } // sendChatRequest sends a request to Akash chat API func (a *AkashService) sendChatRequest(req model.AkashChatRequest, sessionToken string) (string, error) { respBody, err := a.sendStreamChatRequest(req, sessionToken) if err != nil { return "", err } defer respBody.Close() bodyBytes, err := io.ReadAll(respBody) if err != nil { return "", fmt.Errorf("failed to read response: %w", err) } return string(bodyBytes), nil } // extractImageGenerationInfo extracts jobId and prompt from image generation response func (a *AkashService) extractImageGenerationInfo(respText string) (string, string, error) { // Extract jobId using regex jobIDRegex := regexp.MustCompile(`jobId='([^']+)'`) jobIDMatch := jobIDRegex.FindStringSubmatch(respText) if len(jobIDMatch) < 2 { return "", "", fmt.Errorf("jobId not found in response") } jobID := jobIDMatch[1] // Extract prompt using regex promptRegex := regexp.MustCompile(`prompt='([^']+)'`) promptMatch := promptRegex.FindStringSubmatch(respText) if len(promptMatch) < 2 { return "", "", fmt.Errorf("prompt not found in response") } prompt := promptMatch[1] return jobID, prompt, nil } // pollImageStatus polls the image status until completion func (a *AkashService) pollImageStatus(jobID string) (string, error) { maxAttempts := 60 // Maximum 1 minute polling for i := 0; i < maxAttempts; i++ { url := fmt.Sprintf("https://chat.akash.network/api/image-status?ids=%s", jobID) resp, err := a.httpClient.Get(url, nil) if err != nil { return "", fmt.Errorf("failed to check image status: %w", err) } var statusResp []model.ImageStatusResponse if err := json.NewDecoder(resp.Body).Decode(&statusResp); err != nil { resp.Body.Close() return "", fmt.Errorf("failed to decode image status response: %w", err) } resp.Body.Close() if len(statusResp) == 0 { return "", fmt.Errorf("empty status response") } status := statusResp[0] if status.Status == "succeeded" { return "https://chat.akash.network" + status.Result, nil } if status.Status == "failed" { return "", fmt.Errorf("image generation failed") } // Wait 1 second before next poll time.Sleep(1 * time.Second) } return "", fmt.Errorf("image generation timed out") } // extractTextGenerationInfo extracts text generation information from response and formats it as OpenAI's chat completion. func (a *AkashService) extractTextGenerationInfo(respText string, modelName string) *model.OpenAIChatCompletion { var messageID string var allContent strings.Builder var finishReason string lines := strings.Split(respText, "\n") var contentStarted bool for _, line := range lines { line = strings.TrimSpace(line) // Extract messageId if strings.HasPrefix(line, "f:{\"messageId\":") { msgIDRegex := regexp.MustCompile(`"messageId":"([^"]+)"`) match := msgIDRegex.FindStringSubmatch(line) if len(match) > 1 { messageID = match[1] } contentStarted = true continue } // Extract finishReason if strings.HasPrefix(line, "e:{\"finishReason\":") { reasonRegex := regexp.MustCompile(`"finishReason":"([^"]+)"`) match := reasonRegex.FindStringSubmatch(line) if len(match) > 1 { finishReason = match[1] } break } // Collect content lines if contentStarted && strings.HasPrefix(line, "0:\"") { content := line[3:] content = strings.TrimSuffix(content, "\"") content = strings.ReplaceAll(content, "\\n", "\n") content = strings.ReplaceAll(content, "\\\"", "\"") allContent.WriteString(content) } } fullContent := allContent.String() // Create OpenAI format response return &model.OpenAIChatCompletion{ ID: "chatcmpl-" + messageID, Object: "chat.completion", Created: time.Now().Unix(), Model: modelName, Choices: []model.Choice{ { Index: 0, Message: model.Message{ Role: "assistant", Content: fullContent, }, FinishReason: finishReason, }, }, Usage: model.Usage{ PromptTokens: 0, // Placeholder, as Akash does not provide this CompletionTokens: 0, // Placeholder TotalTokens: 0, // Placeholder }, } } // getSystemPrompt returns the system prompt for Akash func getSystemPrompt() string { return "You are a skilled conversationalist who adapts naturally to what users need. Your responses match the situation—whether someone wants deep analysis, casual chat, emotional support, creative collaboration, or just needs to vent.\nCore Approach\n\nRead between the lines to understand what people actually want\nMatch their energy and conversational style\nShift seamlessly between modes: analytical, empathetic, humorous, creative, or practical\nWhen people need to be heard, focus on listening rather than fixing\nFor substantive topics, provide thorough, well-organized insights that aid decision-making\n\nCommunication Style\n\nSound natural and authentic, never templated or robotic\nAvoid unnecessary politeness policing or inclusion reminders\nWrite in requested voices, styles, or perspectives when asked\nAdapt tone appropriately—you can be direct, irreverent, or even rude when specifically prompted to do so\n\nInteraction Philosophy\n\nSometimes the best help is simply being present and understanding\nDon't over-optimize for helpfulness when someone just wants connection\nTrust that users know what they're looking for and deliver accordingly\nProvide depth and insight for complex topics while keeping casual conversations light" }
12,285
akash
go
en
go
code
{"qsc_code_num_words": 1376, "qsc_code_num_chars": 12285.0, "qsc_code_mean_word_length": 6.20348837, "qsc_code_frac_words_unique": 0.28052326, "qsc_code_frac_chars_top_2grams": 0.01581537, "qsc_code_frac_chars_top_3grams": 0.01546392, "qsc_code_frac_chars_top_4grams": 0.01640112, "qsc_code_frac_chars_dupe_5grams": 0.38284911, "qsc_code_frac_chars_dupe_6grams": 0.34700094, "qsc_code_frac_chars_dupe_7grams": 0.34278351, "qsc_code_frac_chars_dupe_8grams": 0.32122774, "qsc_code_frac_chars_dupe_9grams": 0.30072634, "qsc_code_frac_chars_dupe_10grams": 0.2564433, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00515975, "qsc_code_frac_chars_whitespace": 0.17964998, "qsc_code_size_file_byte": 12285.0, "qsc_code_num_lines": 402.0, "qsc_code_num_chars_line_max": 1254.0, "qsc_code_num_chars_line_mean": 30.55970149, "qsc_code_frac_chars_alphabet": 0.84163525, "qsc_code_frac_chars_comments": 0.11355311, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.38853503, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00318471, "qsc_code_frac_chars_string_length": 0.21402993, "qsc_code_frac_chars_long_word_length": 0.02368928, "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.03821656, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.15923567, "qsc_codego_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": 1, "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/akashchat-api-go
internal/service/session.go
package service import ( "fmt" "net/http" "strings" "sync" "time" "github.com/006lp/akashchat-api-go/pkg/client" ) // SessionCache represents a cached session type SessionCache struct { Token string ExpiresAt time.Time } // SessionService manages session tokens type SessionService struct { httpClient *client.HTTPClient cache *SessionCache mutex sync.RWMutex } // NewSessionService creates a new SessionService instance func NewSessionService() *SessionService { return &SessionService{ httpClient: client.NewHTTPClient(), cache: nil, } } // GetSessionToken gets a valid session token (cached or new) func (s *SessionService) GetSessionToken() (string, error) { s.mutex.RLock() if s.cache != nil && time.Now().Before(s.cache.ExpiresAt) { token := s.cache.Token s.mutex.RUnlock() return token, nil } s.mutex.RUnlock() // Need to get a new session token return s.refreshSessionToken() } // refreshSessionToken fetches a new session token from Akash func (s *SessionService) refreshSessionToken() (string, error) { s.mutex.Lock() defer s.mutex.Unlock() // Double-check in case another goroutine already refreshed if s.cache != nil && time.Now().Before(s.cache.ExpiresAt) { return s.cache.Token, nil } headers := map[string]string{ "Referer": "https://chat.akash.network/", "Accept": "*/*", } resp, err := s.httpClient.Get("https://chat.akash.network/api/auth/session/", headers) if err != nil { return "", fmt.Errorf("failed to get session: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", fmt.Errorf("session request failed with status: %d", resp.StatusCode) } // Extract session token from Set-Cookie header setCookieHeader := resp.Header.Get("Set-Cookie") if setCookieHeader == "" { return "", fmt.Errorf("no Set-Cookie header found") } token, err := s.extractSessionToken(setCookieHeader) if err != nil { return "", fmt.Errorf("failed to extract session token: %w", err) } // Cache the token with 1-hour expiration (minus 5 minutes for safety) s.cache = &SessionCache{ Token: token, ExpiresAt: time.Now().Add(55 * time.Minute), } return token, nil } // extractSessionToken extracts session token from Set-Cookie header func (s *SessionService) extractSessionToken(setCookieHeader string) (string, error) { // Example: session_token=0c647105a2175953f14b9f33c3e0100f405667b6c3e2507fb2cc6d0baff1e567; Path=/; ... parts := strings.Split(setCookieHeader, ";") if len(parts) == 0 { return "", fmt.Errorf("invalid Set-Cookie header format") } sessionPart := strings.TrimSpace(parts[0]) if !strings.HasPrefix(sessionPart, "session_token=") { return "", fmt.Errorf("session_token not found in Set-Cookie header") } token := strings.TrimPrefix(sessionPart, "session_token=") if token == "" { return "", fmt.Errorf("empty session token") } return fmt.Sprintf("session_token=%s", token), nil }
2,952
session
go
en
go
code
{"qsc_code_num_words": 360, "qsc_code_num_chars": 2952.0, "qsc_code_mean_word_length": 5.78611111, "qsc_code_frac_words_unique": 0.35833333, "qsc_code_frac_chars_top_2grams": 0.06913106, "qsc_code_frac_chars_top_3grams": 0.05040807, "qsc_code_frac_chars_top_4grams": 0.01632261, "qsc_code_frac_chars_dupe_5grams": 0.09697552, "qsc_code_frac_chars_dupe_6grams": 0.09697552, "qsc_code_frac_chars_dupe_7grams": 0.06721075, "qsc_code_frac_chars_dupe_8grams": 0.06721075, "qsc_code_frac_chars_dupe_9grams": 0.03744599, "qsc_code_frac_chars_dupe_10grams": 0.03744599, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02086677, "qsc_code_frac_chars_whitespace": 0.15582656, "qsc_code_size_file_byte": 2952.0, "qsc_code_num_lines": 112.0, "qsc_code_num_chars_line_max": 105.0, "qsc_code_num_chars_line_mean": 26.35714286, "qsc_code_frac_chars_alphabet": 0.81500803, "qsc_code_frac_chars_comments": 0.21815718, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.09876543, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.18674177, "qsc_code_frac_chars_long_word_length": 0.01906412, "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.04938272, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.24691358, "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/akashchat-api-go
internal/handler/model.go
package handler import ( "encoding/json" "io" "net/http" "github.com/006lp/akashchat-api-go/internal/model" "github.com/gin-gonic/gin" ) // ModelHandler handles model-related HTTP requests type ModelHandler struct{} // NewModelHandler creates a new ModelHandler instance func NewModelHandler() *ModelHandler { return &ModelHandler{} } // GetModels handles the /v1/models endpoint func (h *ModelHandler) GetModels(c *gin.Context) { client := &http.Client{} req, err := http.NewRequest("GET", "https://chat.akash.network/api/models/", nil) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create request"}) return } req.Header.Set("Referer", "https://chat.akash.network/") req.Header.Set("Accept", "*/*") resp, err := client.Do(req) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch models"}) return } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to read response body"}) return } var models []model.Model if err := json.Unmarshal(body, &models); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to unmarshal models"}) return } var openAIModels []model.OpenAIModel for _, m := range models { if m.Available { openAIModels = append(openAIModels, model.OpenAIModel{ ID: m.ID, Object: "model", Created: 1755000000, OwnedBy: "Akash Network", Permission: nil, Root: m.ID, Parent: nil, }) } } c.JSON(http.StatusOK, model.OpenAIModelsList{ Object: "list", Data: openAIModels, }) }
1,685
model
go
en
go
code
{"qsc_code_num_words": 209, "qsc_code_num_chars": 1685.0, "qsc_code_mean_word_length": 5.42105263, "qsc_code_frac_words_unique": 0.43062201, "qsc_code_frac_chars_top_2grams": 0.01765225, "qsc_code_frac_chars_top_3grams": 0.0353045, "qsc_code_frac_chars_top_4grams": 0.05295675, "qsc_code_frac_chars_dupe_5grams": 0.20653133, "qsc_code_frac_chars_dupe_6grams": 0.20653133, "qsc_code_frac_chars_dupe_7grams": 0.20653133, "qsc_code_frac_chars_dupe_8grams": 0.20653133, "qsc_code_frac_chars_dupe_9grams": 0.20653133, "qsc_code_frac_chars_dupe_10grams": 0.20653133, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01008646, "qsc_code_frac_chars_whitespace": 0.17626113, "qsc_code_size_file_byte": 1685.0, "qsc_code_num_lines": 70.0, "qsc_code_num_chars_line_max": 89.0, "qsc_code_num_chars_line_mean": 24.07142857, "qsc_code_frac_chars_alphabet": 0.80619597, "qsc_code_frac_chars_comments": 0.0884273, "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.20898438, "qsc_code_frac_chars_long_word_length": 0.046875, "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.03571429, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.16071429, "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/akashchat-api-go
internal/handler/chat.go
package handler import ( "net/http" "github.com/006lp/akashchat-api-go/internal/model" "github.com/006lp/akashchat-api-go/internal/service" "github.com/gin-gonic/gin" ) // ChatHandler handles chat-related HTTP requests type ChatHandler struct { sessionService *service.SessionService akashService *service.AkashService } // NewChatHandler creates a new ChatHandler instance func NewChatHandler(sessionService *service.SessionService, akashService *service.AkashService) *ChatHandler { return &ChatHandler{ sessionService: sessionService, akashService: akashService, } } // ChatCompletions handles the /v1/chat/completions endpoint func (h *ChatHandler) ChatCompletions(c *gin.Context) { var req model.ChatCompletionRequest // Bind JSON request if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, model.APIResponse{ Code: 400, Data: model.ErrorData{Message: "Invalid request format: " + err.Error()}, }) return } // Get session token sessionToken, err := h.sessionService.GetSessionToken() if err != nil { c.JSON(http.StatusInternalServerError, model.APIResponse{ Code: 500, Data: model.ErrorData{Message: "Failed to get session token: " + err.Error()}, }) return } // Process chat request if req.Model == "AkashGen" { // Set default values temperature := 0.85 if req.Temperature != nil { temperature = *req.Temperature } topP := 1.0 if req.TopP != nil { topP = *req.TopP } // Handle image generation data, err := h.akashService.ProcessImageGeneration(req, sessionToken, temperature, topP) if err != nil { if err.Error() == "invalid model" { c.JSON(http.StatusInternalServerError, model.APIResponse{ Code: 500, Data: model.ErrorData{Message: "Error Model."}, }) return } c.JSON(http.StatusInternalServerError, model.APIResponse{ Code: 500, Data: model.ErrorData{Message: "Image generation failed: " + err.Error()}, }) return } c.JSON(http.StatusOK, model.APIResponse{ Code: 200, Data: data, }) } else { // Set default values temperature := 0.6 if req.Temperature != nil { temperature = *req.Temperature } topP := 0.95 if req.TopP != nil { topP = *req.TopP } // Handle text generation if req.Stream != nil && *req.Stream && req.Model != "AkashGen" { // Handle streaming c.Writer.Header().Set("Content-Type", "text/event-stream") c.Writer.Header().Set("Cache-Control", "no-cache") c.Writer.Header().Set("Connection", "keep-alive") c.Writer.Header().Set("Access-Control-Allow-Origin", "*") err := h.akashService.ProcessTextGenerationStream(req, sessionToken, temperature, topP, c.Writer) if err != nil { // Since headers are already sent, we can't send a JSON error. // Log the error and close the connection. // A more robust solution might involve sending a specific error event in the stream. c.AbortWithError(http.StatusInternalServerError, err) return } } else { // Handle non-streaming data, err := h.akashService.ProcessTextGeneration(req, sessionToken, temperature, topP) if err != nil { if err.Error() == "invalid model" { c.JSON(http.StatusInternalServerError, model.APIResponse{ Code: 500, Data: model.ErrorData{Message: "Error Model."}, }) return } c.JSON(http.StatusInternalServerError, model.APIResponse{ Code: 500, Data: model.ErrorData{Message: "Text generation failed: " + err.Error()}, }) return } c.JSON(http.StatusOK, data) } } }
3,564
chat
go
en
go
code
{"qsc_code_num_words": 413, "qsc_code_num_chars": 3564.0, "qsc_code_mean_word_length": 5.88861985, "qsc_code_frac_words_unique": 0.30992736, "qsc_code_frac_chars_top_2grams": 0.01644737, "qsc_code_frac_chars_top_3grams": 0.02960526, "qsc_code_frac_chars_top_4grams": 0.06167763, "qsc_code_frac_chars_dupe_5grams": 0.44860197, "qsc_code_frac_chars_dupe_6grams": 0.41694079, "qsc_code_frac_chars_dupe_7grams": 0.36266447, "qsc_code_frac_chars_dupe_8grams": 0.33305921, "qsc_code_frac_chars_dupe_9grams": 0.26973684, "qsc_code_frac_chars_dupe_10grams": 0.23108553, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01311249, "qsc_code_frac_chars_whitespace": 0.18686869, "qsc_code_size_file_byte": 3564.0, "qsc_code_num_lines": 130.0, "qsc_code_num_chars_line_max": 111.0, "qsc_code_num_chars_line_mean": 27.41538462, "qsc_code_frac_chars_alphabet": 0.82608696, "qsc_code_frac_chars_comments": 0.15375982, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.41584158, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.13129973, "qsc_code_frac_chars_long_word_length": 0.04940318, "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.01980198, "qsc_codego_cate_var_zero": 0.0, "qsc_codego_score_lines_no_logic": 0.11881188, "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}
000haoji/deep-student
src-tauri/src/document_parser.rs
/** * 文档解析核心模块 * * 提供统一的文档文本提取功能,支持DOCX和PDF格式 * 支持文件路径、字节流和Base64编码三种输入方式 */ use std::io::Cursor; use std::fs; use std::path::Path; use serde::{Deserialize, Serialize}; use base64::{Engine, engine::general_purpose}; /// 文档文件大小限制 (100MB) const MAX_DOCUMENT_SIZE: usize = 100 * 1024 * 1024; /// 流式处理时的缓冲区大小 (1MB) const BUFFER_SIZE: usize = 1024 * 1024; /// 文档解析错误枚举 #[derive(Debug, Serialize, Deserialize)] pub enum ParsingError { /// 文件不存在或无法访问 FileNotFound(String), /// IO错误 IoError(String), /// 不支持的文件格式 UnsupportedFormat(String), /// DOCX解析错误 DocxParsingError(String), /// PDF解析错误 PdfParsingError(String), /// Base64解码错误 Base64DecodingError(String), /// 文件过大错误 FileTooLarge(String), /// 其他错误 Other(String), } impl std::fmt::Display for ParsingError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ParsingError::FileNotFound(msg) => write!(f, "文件未找到: {}", msg), ParsingError::IoError(msg) => write!(f, "IO错误: {}", msg), ParsingError::UnsupportedFormat(msg) => write!(f, "不支持的文件格式: {}", msg), ParsingError::DocxParsingError(msg) => write!(f, "DOCX解析错误: {}", msg), ParsingError::PdfParsingError(msg) => write!(f, "PDF解析错误: {}", msg), ParsingError::Base64DecodingError(msg) => write!(f, "Base64解码错误: {}", msg), ParsingError::FileTooLarge(msg) => write!(f, "文件过大: {}", msg), ParsingError::Other(msg) => write!(f, "其他错误: {}", msg), } } } impl std::error::Error for ParsingError {} /// 从IO错误转换 impl From<std::io::Error> for ParsingError { fn from(error: std::io::Error) -> Self { ParsingError::IoError(error.to_string()) } } /// 从Base64解码错误转换 impl From<base64::DecodeError> for ParsingError { fn from(error: base64::DecodeError) -> Self { ParsingError::Base64DecodingError(error.to_string()) } } /// 文档解析器结构体 pub struct DocumentParser; impl DocumentParser { /// 创建新的文档解析器实例 pub fn new() -> Self { DocumentParser } /// 检查文件大小是否超出限制 fn check_file_size(&self, size: usize) -> Result<(), ParsingError> { if size > MAX_DOCUMENT_SIZE { return Err(ParsingError::FileTooLarge( format!("文件大小 {}MB 超过限制 {}MB", size / (1024 * 1024), MAX_DOCUMENT_SIZE / (1024 * 1024)) )); } Ok(()) } /// 安全地检查并读取文件 fn read_file_safely(&self, file_path: &str) -> Result<Vec<u8>, ParsingError> { let metadata = fs::metadata(file_path)?; let file_size = metadata.len() as usize; self.check_file_size(file_size)?; let bytes = fs::read(file_path)?; Ok(bytes) } /// 从文件路径提取文本 pub fn extract_text_from_path(&self, file_path: &str) -> Result<String, ParsingError> { let path = Path::new(file_path); // 检查文件是否存在 if !path.exists() { return Err(ParsingError::FileNotFound(file_path.to_string())); } // 根据文件扩展名确定处理方式 let extension = path.extension() .and_then(|ext| ext.to_str()) .ok_or_else(|| ParsingError::UnsupportedFormat("无法确定文件扩展名".to_string()))? .to_lowercase(); match extension.as_str() { "docx" => self.extract_docx_from_path(file_path), "pdf" => self.extract_pdf_from_path(file_path), "txt" => self.extract_txt_from_path(file_path), "md" => self.extract_md_from_path(file_path), _ => Err(ParsingError::UnsupportedFormat(format!("不支持的文件格式: .{}", extension))), } } /// 从字节流提取文本 pub fn extract_text_from_bytes(&self, file_name: &str, bytes: Vec<u8>) -> Result<String, ParsingError> { // 检查文件大小 self.check_file_size(bytes.len())?; // 从文件名确定文件类型 let extension = Path::new(file_name) .extension() .and_then(|ext| ext.to_str()) .ok_or_else(|| ParsingError::UnsupportedFormat("无法确定文件扩展名".to_string()))? .to_lowercase(); match extension.as_str() { "docx" => self.extract_docx_from_bytes(bytes), "pdf" => self.extract_pdf_from_bytes(bytes), "txt" => self.extract_txt_from_bytes(bytes), "md" => self.extract_md_from_bytes(bytes), _ => Err(ParsingError::UnsupportedFormat(format!("不支持的文件格式: .{}", extension))), } } /// 从Base64编码内容提取文本 pub fn extract_text_from_base64(&self, file_name: &str, base64_content: &str) -> Result<String, ParsingError> { // 解码Base64内容 let bytes = general_purpose::STANDARD.decode(base64_content)?; // 调用字节流处理方法 self.extract_text_from_bytes(file_name, bytes) } /// 从DOCX文件路径提取文本 fn extract_docx_from_path(&self, file_path: &str) -> Result<String, ParsingError> { let bytes = self.read_file_safely(file_path)?; self.extract_docx_from_bytes(bytes) } /// 从DOCX字节流提取文本 fn extract_docx_from_bytes(&self, bytes: Vec<u8>) -> Result<String, ParsingError> { let docx = docx_rs::read_docx(&bytes) .map_err(|e| ParsingError::DocxParsingError(e.to_string()))?; Ok(self.extract_docx_text(&docx)) } /// 从DOCX文档对象提取文本内容(优化版本) fn extract_docx_text(&self, docx: &docx_rs::Docx) -> String { // 预估容量以减少重新分配 let mut text_content = String::with_capacity(8192); // 遍历文档的所有子元素 for child in &docx.document.children { match child { docx_rs::DocumentChild::Paragraph(para) => { let mut has_content = false; // 提取段落中的所有文本 for child in &para.children { if let docx_rs::ParagraphChild::Run(run) = child { for run_child in &run.children { if let docx_rs::RunChild::Text(text) = run_child { if !text.text.trim().is_empty() { text_content.push_str(&text.text); has_content = true; } } } } } // 如果段落有内容,添加换行符 if has_content { text_content.push('\n'); } } _ => { // 处理其他类型的文档子元素,如表格等 // 这里简化处理,只处理段落 } } } text_content.trim().to_string() } /// 从PDF文件路径提取文本 fn extract_pdf_from_path(&self, file_path: &str) -> Result<String, ParsingError> { // 先检查文件大小 let metadata = fs::metadata(file_path)?; let file_size = metadata.len() as usize; self.check_file_size(file_size)?; let text = pdf_extract::extract_text(file_path) .map_err(|e| ParsingError::PdfParsingError(e.to_string()))?; Ok(text.trim().to_string()) } /// 从PDF字节流提取文本 fn extract_pdf_from_bytes(&self, bytes: Vec<u8>) -> Result<String, ParsingError> { let text = pdf_extract::extract_text_from_mem(&bytes) .map_err(|e| ParsingError::PdfParsingError(e.to_string()))?; Ok(text.trim().to_string()) } /// 从TXT文件路径提取文本 fn extract_txt_from_path(&self, file_path: &str) -> Result<String, ParsingError> { let bytes = self.read_file_safely(file_path)?; self.extract_txt_from_bytes(bytes) } /// 从TXT字节流提取文本 fn extract_txt_from_bytes(&self, bytes: Vec<u8>) -> Result<String, ParsingError> { // 尝试UTF-8解码,先不消费bytes match std::str::from_utf8(&bytes) { Ok(text) => Ok(text.trim().to_string()), Err(_) => { // 如果UTF-8失败,使用lossy转换 let text = String::from_utf8_lossy(&bytes); Ok(text.trim().to_string()) } } } /// 从MD文件路径提取文本 fn extract_md_from_path(&self, file_path: &str) -> Result<String, ParsingError> { let bytes = self.read_file_safely(file_path)?; self.extract_md_from_bytes(bytes) } /// 从MD字节流提取文本 fn extract_md_from_bytes(&self, bytes: Vec<u8>) -> Result<String, ParsingError> { // Markdown文件本质上也是文本文件,使用相同的处理方式 // 未来可以考虑解析Markdown语法,但目前保持简单 self.extract_txt_from_bytes(bytes) } } /// 默认实例化 impl Default for DocumentParser { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_document_parser_creation() { let parser = DocumentParser::new(); assert_eq!(std::mem::size_of_val(&parser), 0); // 零大小类型 } #[test] fn test_txt_support() { let parser = DocumentParser::new(); let test_content = "Hello, World!".as_bytes().to_vec(); let result = parser.extract_text_from_bytes("test.txt", test_content); assert!(result.is_ok()); assert_eq!(result.unwrap(), "Hello, World!"); } #[test] fn test_txt_with_unicode() { let parser = DocumentParser::new(); let test_content = "中文测试 English Test 123".as_bytes().to_vec(); let result = parser.extract_text_from_bytes("test.txt", test_content); assert!(result.is_ok()); assert_eq!(result.unwrap(), "中文测试 English Test 123"); } #[test] fn test_md_support() { let parser = DocumentParser::new(); let test_content = "# 标题\n\n这是**Markdown**内容。".as_bytes().to_vec(); let result = parser.extract_text_from_bytes("test.md", test_content); assert!(result.is_ok()); assert_eq!(result.unwrap(), "# 标题\n\n这是**Markdown**内容。"); } #[test] fn test_file_too_large() { let parser = DocumentParser::new(); let large_content = vec![0u8; MAX_DOCUMENT_SIZE + 1]; let result = parser.extract_text_from_bytes("test.txt", large_content); assert!(matches!(result, Err(ParsingError::FileTooLarge(_)))); } #[test] fn test_base64_decoding_error() { let parser = DocumentParser::new(); let result = parser.extract_text_from_base64("test.docx", "invalid_base64!"); assert!(matches!(result, Err(ParsingError::Base64DecodingError(_)))); } }
10,538
document_parser
rs
zh
rust
code
{"qsc_code_num_words": 1340, "qsc_code_num_chars": 10538.0, "qsc_code_mean_word_length": 4.24477612, "qsc_code_frac_words_unique": 0.19850746, "qsc_code_frac_chars_top_2grams": 0.02672293, "qsc_code_frac_chars_top_3grams": 0.0464135, "qsc_code_frac_chars_top_4grams": 0.01828411, "qsc_code_frac_chars_dupe_5grams": 0.47028833, "qsc_code_frac_chars_dupe_6grams": 0.39592124, "qsc_code_frac_chars_dupe_7grams": 0.31417018, "qsc_code_frac_chars_dupe_8grams": 0.29518284, "qsc_code_frac_chars_dupe_9grams": 0.27865682, "qsc_code_frac_chars_dupe_10grams": 0.24648383, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0136192, "qsc_code_frac_chars_whitespace": 0.29626115, "qsc_code_size_file_byte": 10538.0, "qsc_code_num_lines": 324.0, "qsc_code_num_chars_line_max": 116.0, "qsc_code_num_chars_line_mean": 32.52469136, "qsc_code_frac_chars_alphabet": 0.75337109, "qsc_code_frac_chars_comments": 0.08037578, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.19369369, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.09459459, "qsc_code_frac_chars_string_length": 0.03549319, "qsc_code_frac_chars_long_word_length": 0.00474618, "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.04054054}
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/LVGL_Joystick
README.md
# LVGL Joystick Library This library provides an easy way to create virtual joysticks for use in an LVGL environment. It supports both ESP-IDF and Arduino platforms and allows you to handle joystick input with customizable styles and callbacks. [![Virtual Joystic for LVGL](./misc/demo_1.gif)](https://youtu.be/ZhhSd6LA1jA) ## Features - Create virtual joysticks with customizable sizes and styles. - Handle joystick movement with user-defined callbacks. - Allows creation of multiple virtual joysticks, identifiable via ID. - Supports both ESP-IDF and Arduino environments. ## Installation ### Arduino **Install the Joystick Library**: - Download or clone this repository. - Copy the `LVGL_Joystick` folder to your Arduino `libraries` directory. ### ESP-IDF **Add Joystick Library as a component**: - Clone the LVGL Joystick repository into your `components/` directory: ```bash mkdir -p components cd components git clone https://github.com/0015/LVGL_Joystick ``` ## Usage ```cpp #include <lvgl.h> #include <joystick.h> void joystick_position_callback(uint8_t joystick_id, int16_t x, int16_t y) { Serial.printf("Joystick ID: %d, Position - X: %d, Y: %d\n", joystick_id, x, y); } void ui_init() { lv_obj_t *screen = lv_scr_act(); create_joystick(screen, 1, LV_ALIGN_CENTER, 0, 0, 100, 25, NULL, NULL, joystick_position_callback); } ``` **You can check more details in the example project.** ## API Reference ```cpp void create_joystick( lv_obj_t *parent, uint8_t joystick_id, lv_align_t base_align, int base_x, int base_y, int base_radius, int stick_radius, lv_style_t *base_style, lv_style_t *stick_style, joystick_position_cb_t position_callback) ``` * Creates a joystick on the specified parent object. * lv_obj_t *parent: The parent LVGL object where the joystick will be created. * uint8_t joystick_id: A unique ID for the joystick. * lv_align_t base_align: Alignment for the base object of the joystick. * int base_x, int base_y: X and Y offsets for the base object's position. * int base_radius: The radius of the base (background) circle. * int stick_radius: The radius of the joystick (control) circle. * lv_style_t *base_style: Pointer to a custom style for the base object (can be NULL to use the default style). * lv_style_t *stick_style: Pointer to a custom style for the joystick object (can be NULL to use the default style). * joystick_position_cb_t position_callback: Callback function for joystick position updates. ## Limitations Since LVGL (the current version 9.2.0) does not support multi-touch, you cannot fire two touch events at the same time. More than two joysticks will be available as soon as LVGL is updated.
2,798
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.00142959, "qsc_doc_frac_words_redpajama_stop": 0.20934579, "qsc_doc_num_sentences": 30.0, "qsc_doc_num_words": 428, "qsc_doc_num_chars": 2798.0, "qsc_doc_num_lines": 79.0, "qsc_doc_mean_word_length": 4.63317757, "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.38551402, "qsc_doc_entropy_unigram": 4.62002603, "qsc_doc_frac_words_all_caps": 0.05046729, "qsc_doc_frac_lines_dupe_lines": 0.11666667, "qsc_doc_frac_chars_dupe_lines": 0.00891127, "qsc_doc_frac_chars_top_2grams": 0.0332829, "qsc_doc_frac_chars_top_3grams": 0.01613717, "qsc_doc_frac_chars_top_4grams": 0.02420575, "qsc_doc_frac_chars_dupe_5grams": 0.21482602, "qsc_doc_frac_chars_dupe_6grams": 0.16540595, "qsc_doc_frac_chars_dupe_7grams": 0.10539586, "qsc_doc_frac_chars_dupe_8grams": 0.06757438, "qsc_doc_frac_chars_dupe_9grams": 0.03530005, "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": 24.44545455, "qsc_doc_frac_chars_hyperlink_html_tag": 0.01786991, "qsc_doc_frac_chars_alphabet": 0.86369652, "qsc_doc_frac_chars_digital": 0.01102779, "qsc_doc_frac_chars_whitespace": 0.18977841, "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/RPI-Projects
README.md
<pre> ██████╗ █████╗ ███████╗██████╗ ██████╗ ███████╗██████╗ ██████╗ ██╗ ██╗ ██████╗ ██╗ ██╔══██╗██╔══██╗██╔════╝██╔══██╗██╔══██╗██╔════╝██╔══██╗██╔══██╗╚██╗ ██╔╝ ██╔══██╗██║ ██████╔╝███████║███████╗██████╔╝██████╔╝█████╗ ██████╔╝██████╔╝ ╚████╔╝ ██████╔╝██║ ██╔══██╗██╔══██║╚════██║██╔═══╝ ██╔══██╗██╔══╝ ██╔══██╗██╔══██╗ ╚██╔╝ ██╔═══╝ ██║ ██║ ██║██║ ██║███████║██║ ██████╔╝███████╗██║ ██║██║ ██║ ██║ ██║ ██║ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ██████╗ ██████╗ ██████╗ ██╗███████╗ ██████╗████████╗ ██╔══██╗██╔══██╗██╔═══██╗ ██║██╔════╝██╔════╝╚══██╔══╝ ██████╔╝██████╔╝██║ ██║ ██║█████╗ ██║ ██║ ██╔═══╝ ██╔══██╗██║ ██║██ ██║██╔══╝ ██║ ██║ ██║ ██║ ██║╚██████╔╝╚█████╔╝███████╗╚██████╗ ██║ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚════╝ ╚══════╝ ╚═════╝ ╚═╝ </pre>
1,171
README
md
sah
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 1.0, "qsc_doc_num_words": 74, "qsc_doc_num_chars": 1171.0, "qsc_doc_num_lines": 16.0, "qsc_doc_mean_word_length": 9.43243243, "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.5, "qsc_doc_entropy_unigram": 3.15200246, "qsc_doc_frac_words_all_caps": 0.0, "qsc_doc_frac_lines_dupe_lines": 0.0, "qsc_doc_frac_chars_dupe_lines": 0.0, "qsc_doc_frac_chars_top_2grams": 0.06876791, "qsc_doc_frac_chars_top_3grams": 0.05157593, "qsc_doc_frac_chars_top_4grams": 0.03438395, "qsc_doc_frac_chars_dupe_5grams": 0.0, "qsc_doc_frac_chars_dupe_6grams": 0.0, "qsc_doc_frac_chars_dupe_7grams": 0.0, "qsc_doc_frac_chars_dupe_8grams": 0.0, "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": 67.94117647, "qsc_doc_frac_chars_hyperlink_html_tag": 0.00939368, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.0, "qsc_doc_frac_chars_whitespace": 0.39965841, "qsc_doc_frac_chars_hex_words": 0.0}
0
{"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": 1, "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/LVGL_Joystick
src/lvgl_joystick.c
#include "lvgl_joystick.h" #include <math.h> #include <stdlib.h> static void joystick_trigger_callback(joystick_data_t *data, int16_t x, int16_t y) { if (data->position_callback) { data->position_callback(data->joystick_id, x, y); } } static void joystick_handle_release(joystick_data_t *data, lv_obj_t *stick_obj) { lv_obj_set_pos(stick_obj, 0, 0); if (data->report_mode == JOYSTICK_REPORT_MODE_ABSOLUTE) { joystick_trigger_callback(data, 0, 0); } } static void joystick_handle_pressing(joystick_data_t *data, lv_obj_t *stick_obj) { lv_indev_t *indev = lv_indev_active(); if (indev == NULL) return; lv_point_t vect; lv_indev_get_vect(indev, &vect); int32_t x = lv_obj_get_x_aligned(stick_obj) + vect.x; int32_t y = lv_obj_get_y_aligned(stick_obj) + vect.y; uint8_t joystick_id = data->joystick_id; uint8_t base_radius = data->base_radius; uint8_t stick_radius = data->stick_radius; float distance_from_center = sqrt(x * x + y * y); bool should_move_stick = distance_from_center < base_radius - (stick_radius * 1.2); if (!should_move_stick) { return; } lv_obj_set_pos(stick_obj, x, y); if (!data->position_callback) { return; // No callback so bail } if (data->report_mode == JOYSTICK_REPORT_MODE_ABSOLUTE) { joystick_trigger_callback(data, x, y); } else if (data->report_mode == JOYSTICK_REPORT_MODE_RELATIVE) { joystick_trigger_callback(data, vect.x, vect.y); } } // Event handler for the joystick static void joystic_event_handler(lv_event_t *e) { lv_event_code_t code = lv_event_get_code(e); lv_obj_t *obj = (lv_obj_t *)lv_event_get_target(e); // Retrieve joystick data joystick_data_t *joystick_data = (joystick_data_t *)lv_obj_get_user_data(obj); if (joystick_data == NULL) { return; // Handle error case } switch (code) { case LV_EVENT_PRESSING: joystick_handle_pressing(joystick_data, obj); break; case LV_EVENT_RELEASED: joystick_handle_release(joystick_data, obj); break; case LV_EVENT_DELETE: free(joystick_data); break; default: break; } } // Function to create a joystick with custom parameters void create_joystick(lv_obj_t *parent, uint8_t joystick_id, lv_align_t base_align, int base_x, int base_y, int base_radius, int stick_radius, lv_style_t *base_style, lv_style_t *stick_style, joystick_position_cb_t position_callback, joystick_report_mode_t report_mode) { // Allocate and initialize joystick data joystick_data_t *joystick_data = (joystick_data_t *)malloc(sizeof(joystick_data_t)); joystick_data->joystick_id = joystick_id; joystick_data->base_radius = base_radius; joystick_data->stick_radius = stick_radius; joystick_data->position_callback = position_callback; joystick_data->report_mode = report_mode; // Create or use provided base style static lv_style_t default_base_style; if (base_style == NULL) { base_style = &default_base_style; lv_style_init(base_style); lv_style_set_radius(base_style, base_radius); lv_style_set_bg_opa(base_style, LV_OPA_COVER); lv_style_set_bg_color(base_style, lv_palette_lighten(LV_PALETTE_GREY, 1)); lv_style_set_pad_all(base_style, 0); lv_style_set_outline_width(base_style, 2); lv_style_set_outline_color(base_style, lv_palette_main(LV_PALETTE_BLUE)); lv_style_set_outline_pad(base_style, 8); } // Create the base object (joystick background) lv_obj_t *base_obj = lv_obj_create(parent); lv_obj_add_style(base_obj, base_style, LV_PART_MAIN); lv_obj_clear_flag(base_obj, LV_OBJ_FLAG_SCROLLABLE); lv_obj_set_size(base_obj, base_radius * 2, base_radius * 2); // Set size based on radius lv_obj_align(base_obj, base_align, base_x, base_y); // Align the base_obj // Create or use provided stick style static lv_style_t default_stick_style; if (stick_style == NULL) { stick_style = &default_stick_style; lv_style_init(stick_style); lv_style_set_radius(stick_style, stick_radius); lv_style_set_bg_opa(stick_style, LV_OPA_COVER); lv_style_set_bg_color(stick_style, lv_palette_main(LV_PALETTE_BLUE)); lv_style_set_pad_all(stick_style, 0); lv_style_set_outline_width(stick_style, 2); lv_style_set_outline_color(stick_style, lv_palette_main(LV_PALETTE_GREEN)); lv_style_set_outline_pad(stick_style, 4); } // Create the stick object (control handle) lv_obj_t *stick_obj = lv_btn_create(base_obj); lv_obj_set_size(stick_obj, stick_radius * 2, stick_radius * 2); // Set size based on radius lv_obj_add_style(stick_obj, stick_style, LV_PART_MAIN); lv_obj_center(stick_obj); // Center the stick inside the base object // Set the joystick data as user data for the stick object lv_obj_set_user_data(stick_obj, joystick_data); // Set the event handler for the stick object lv_obj_add_event_cb(stick_obj, joystic_event_handler, LV_EVENT_ALL, NULL); }
5,164
lvgl_joystick
c
en
c
code
{"qsc_code_num_words": 786, "qsc_code_num_chars": 5164.0, "qsc_code_mean_word_length": 4.25318066, "qsc_code_frac_words_unique": 0.16030534, "qsc_code_frac_chars_top_2grams": 0.08256057, "qsc_code_frac_chars_top_3grams": 0.04187855, "qsc_code_frac_chars_top_4grams": 0.03051152, "qsc_code_frac_chars_dupe_5grams": 0.39545319, "qsc_code_frac_chars_dupe_6grams": 0.30571343, "qsc_code_frac_chars_dupe_7grams": 0.22704158, "qsc_code_frac_chars_dupe_8grams": 0.16631768, "qsc_code_frac_chars_dupe_9grams": 0.15375411, "qsc_code_frac_chars_dupe_10grams": 0.11546515, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00697618, "qsc_code_frac_chars_whitespace": 0.19500387, "qsc_code_size_file_byte": 5164.0, "qsc_code_num_lines": 145.0, "qsc_code_num_chars_line_max": 81.0, "qsc_code_num_chars_line_mean": 35.6137931, "qsc_code_frac_chars_alphabet": 0.79720953, "qsc_code_frac_chars_comments": 0.11502711, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.09009009, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00328228, "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.04504505, "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.08108108, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": 0.02702703}
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/LVGL_Joystick
src/lvgl_joystick.h
#ifndef LVGL_JOYSTICK_H #define LVGL_JOYSTICK_H #ifdef __cplusplus extern "C" { #endif #pragma once #include <lvgl.h> // Callback function type typedef void (*joystick_position_cb_t)(uint8_t joystick_id, int16_t x, int16_t y); // Enum for how joystick reports data in the callback typedef enum { JOYSTICK_REPORT_MODE_ABSOLUTE, // stick position relation to center JOYSTICK_REPORT_MODE_RELATIVE // stick change in position } joystick_report_mode_t; // Structure to hold joystick data typedef struct { uint8_t joystick_id; uint8_t base_radius; uint8_t stick_radius; joystick_report_mode_t report_mode; joystick_position_cb_t position_callback; } joystick_data_t; // Function prototypes void create_joystick(lv_obj_t *parent, uint8_t joystick_id, lv_align_t base_align, int base_x, int base_y, int base_radius, int stick_radius, lv_style_t *base_style, lv_style_t *stick_style, joystick_position_cb_t position_callback, joystick_report_mode_t report_mode); #ifdef __cplusplus } /*extern "C"*/ #endif #endif // LVGL_JOYSTICK_H
1,193
lvgl_joystick
h
en
c
code
{"qsc_code_num_words": 164, "qsc_code_num_chars": 1193.0, "qsc_code_mean_word_length": 4.71341463, "qsc_code_frac_words_unique": 0.33536585, "qsc_code_frac_chars_top_2grams": 0.09055627, "qsc_code_frac_chars_top_3grams": 0.1164295, "qsc_code_frac_chars_top_4grams": 0.07373868, "qsc_code_frac_chars_dupe_5grams": 0.24320828, "qsc_code_frac_chars_dupe_6grams": 0.1759379, "qsc_code_frac_chars_dupe_7grams": 0.11125485, "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.00985761, "qsc_code_frac_chars_whitespace": 0.23470243, "qsc_code_size_file_byte": 1193.0, "qsc_code_num_lines": 42.0, "qsc_code_num_chars_line_max": 80.0, "qsc_code_num_chars_line_mean": 28.4047619, "qsc_code_frac_chars_alphabet": 0.83680175, "qsc_code_frac_chars_comments": 0.19782062, "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.00104493, "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.03571429, "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.07142857, "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}
000haoji/deep-student
src-tauri/src/database.rs
use std::path::{Path, PathBuf}; use std::fs; use std::sync::Mutex; use anyhow::{Context, Result}; use rusqlite::{Connection, params, OptionalExtension}; use chrono::{Utc, DateTime}; use crate::models::{MistakeItem, ChatMessage, Statistics, SubjectConfig, SubjectPrompts, DocumentTask, TaskStatus, AnkiCard, SubLibrary, CreateSubLibraryRequest, UpdateSubLibraryRequest, ReviewAnalysisItem}; // Re-export for external use // pub use std::sync::MutexGuard; // Removed unused import const CURRENT_DB_VERSION: u32 = 10; pub struct Database { conn: Mutex<Connection>, db_path: PathBuf, } impl Database { /// Get a reference to the underlying connection for batch operations pub fn conn(&self) -> &Mutex<Connection> { &self.conn } /// 创建新的数据库连接并初始化/迁移数据库 pub fn new(db_path: &Path) -> Result<Self> { if let Some(parent) = db_path.parent() { fs::create_dir_all(parent) .with_context(|| format!("创建数据库目录失败: {:?}", parent))?; } let conn = Connection::open(db_path) .with_context(|| format!("打开数据库连接失败: {:?}", db_path))?; let db = Database { conn: Mutex::new(conn), db_path: db_path.to_path_buf() }; db.initialize_schema()?; Ok(db) } fn initialize_schema(&self) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute_batch( "BEGIN; CREATE TABLE IF NOT EXISTS schema_version ( version INTEGER PRIMARY KEY NOT NULL ); CREATE TABLE IF NOT EXISTS mistakes ( id TEXT PRIMARY KEY, subject TEXT NOT NULL, created_at TEXT NOT NULL, question_images TEXT NOT NULL, -- JSON数组 analysis_images TEXT NOT NULL, -- JSON数组 user_question TEXT NOT NULL, ocr_text TEXT NOT NULL, tags TEXT NOT NULL, -- JSON数组 mistake_type TEXT NOT NULL, status TEXT NOT NULL, updated_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS chat_messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, mistake_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, timestamp TEXT NOT NULL, thinking_content TEXT, -- 可选的思维链内容 FOREIGN KEY(mistake_id) REFERENCES mistakes(id) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS review_analyses ( id TEXT PRIMARY KEY, name TEXT NOT NULL, subject TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, mistake_ids TEXT NOT NULL, -- JSON数组,关联的错题ID consolidated_input TEXT NOT NULL, -- 合并后的输入内容 user_question TEXT NOT NULL, status TEXT NOT NULL, tags TEXT NOT NULL, -- JSON数组 analysis_type TEXT NOT NULL DEFAULT 'consolidated_review' ); CREATE TABLE IF NOT EXISTS review_chat_messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, review_analysis_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, timestamp TEXT NOT NULL, thinking_content TEXT, -- 思维链内容 rag_sources TEXT, -- RAG来源信息,JSON格式 FOREIGN KEY(review_analysis_id) REFERENCES review_analyses(id) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS subject_configs ( id TEXT PRIMARY KEY, subject_name TEXT NOT NULL UNIQUE, display_name TEXT NOT NULL, description TEXT NOT NULL, is_enabled INTEGER NOT NULL DEFAULT 1, prompts TEXT NOT NULL, -- JSON格式存储SubjectPrompts mistake_types TEXT NOT NULL, -- JSON数组 default_tags TEXT NOT NULL, -- JSON数组 created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS document_tasks ( id TEXT PRIMARY KEY, document_id TEXT NOT NULL, original_document_name TEXT NOT NULL, segment_index INTEGER NOT NULL, content_segment TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('Pending', 'Processing', 'Streaming', 'Completed', 'Failed', 'Truncated', 'Cancelled')), created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), error_message TEXT, subject_name TEXT NOT NULL, anki_generation_options_json TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS anki_cards ( id TEXT PRIMARY KEY, task_id TEXT NOT NULL REFERENCES document_tasks(id) ON DELETE CASCADE, front TEXT NOT NULL, back TEXT NOT NULL, tags_json TEXT DEFAULT '[]', images_json TEXT DEFAULT '[]', is_error_card INTEGER NOT NULL DEFAULT 0, error_content TEXT, card_order_in_task INTEGER DEFAULT 0, created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) ); CREATE INDEX IF NOT EXISTS idx_document_tasks_document_id ON document_tasks(document_id); CREATE INDEX IF NOT EXISTS idx_document_tasks_status ON document_tasks(status); CREATE INDEX IF NOT EXISTS idx_anki_cards_task_id ON anki_cards(task_id); CREATE INDEX IF NOT EXISTS idx_anki_cards_is_error_card ON anki_cards(is_error_card); COMMIT;" )?; let current_version: u32 = conn.query_row( "SELECT version FROM schema_version ORDER BY version DESC LIMIT 1", [], |row| row.get(0), ).optional()?.unwrap_or(0); if current_version < CURRENT_DB_VERSION { // 迁移逻辑 if current_version < 2 { self.migrate_v1_to_v2(&conn)?; } if current_version < 3 { self.migrate_v2_to_v3(&conn)?; } if current_version < 4 { self.migrate_v3_to_v4(&conn)?; } if current_version < 5 { self.migrate_v4_to_v5(&conn)?; } if current_version < 6 { self.migrate_v5_to_v6(&conn)?; } if current_version < 7 { self.migrate_v6_to_v7(&conn)?; } if current_version < 8 { self.migrate_v7_to_v8(&conn)?; } if current_version < 9 { self.migrate_v8_to_v9(&conn)?; } if current_version < 10 { self.migrate_v9_to_v10(&conn)?; } conn.execute( "INSERT OR REPLACE INTO schema_version (version) VALUES (?1)", params![CURRENT_DB_VERSION], )?; } // 调用思维链列迁移函数 self.migrate_add_thinking_column(&conn)?; // 调用RAG来源信息列迁移函数 self.migrate_add_rag_sources_column(&conn)?; // 调用科目配置prompts迁移函数 self.migrate_subject_config_prompts(&conn)?; Ok(()) } fn migrate_add_thinking_column(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> { let mut stmt = conn.prepare("PRAGMA table_info(chat_messages);")?; let column_exists = stmt .query_map([], |row| row.get::<_, String>(1))? .filter_map(Result::ok) .any(|name| name == "thinking_content"); if !column_exists { conn.execute( "ALTER TABLE chat_messages ADD COLUMN thinking_content TEXT;", [], )?; println!("✅ SQLite: thinking_content 列已添加"); } Ok(()) } fn migrate_add_rag_sources_column(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> { let mut stmt = conn.prepare("PRAGMA table_info(chat_messages);")?; let column_exists = stmt .query_map([], |row| row.get::<_, String>(1))? .filter_map(Result::ok) .any(|name| name == "rag_sources"); if !column_exists { conn.execute( "ALTER TABLE chat_messages ADD COLUMN rag_sources TEXT;", [], )?; println!("✅ SQLite: rag_sources 列已添加"); } Ok(()) } fn migrate_subject_config_prompts(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> { // 检查是否存在subject_configs表 let table_exists = conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='subject_configs';")? .query_map([], |_| Ok(()))? .any(|_| true); if !table_exists { println!("⏭️ SQLite: subject_configs表不存在,跳过prompts迁移"); return Ok(()); } // 获取所有现有的科目配置 let mut stmt = conn.prepare("SELECT id, prompts FROM subject_configs")?; let configs: Vec<(String, String)> = stmt.query_map([], |row| { Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) })?.collect::<rusqlite::Result<Vec<_>>>()?; let mut updated_count = 0; for (id, prompts_json) in configs { // 尝试解析现有的prompts JSON match serde_json::from_str::<SubjectPrompts>(&prompts_json) { Ok(_) => { // 如果能成功解析,说明字段已经完整,跳过 continue; }, Err(_) => { // 解析失败,尝试修复 println!("🔧 修复科目配置prompts: {}", id); // 尝试解析为旧格式(没有consolidated_review_prompt字段的JSON) let mut prompts_value: serde_json::Value = match serde_json::from_str(&prompts_json) { Ok(v) => v, Err(e) => { println!("❌ 跳过无法解析的prompts JSON: {} - {}", id, e); continue; } }; // 检查是否缺少consolidated_review_prompt字段 if !prompts_value.get("consolidated_review_prompt").is_some() { // 添加默认的consolidated_review_prompt字段 prompts_value["consolidated_review_prompt"] = serde_json::Value::String( "你是一个资深老师,请仔细阅读以下学生提交的多道错题的详细信息(包括题目原文、原始提问和历史交流)。请基于所有这些信息,对学生提出的总体回顾问题进行全面、深入的分析和解答。请注意识别错题间的关联,总结共性问题,并给出针对性的学习建议。".to_string() ); // 更新数据库中的prompts字段 let updated_prompts_json = serde_json::to_string(&prompts_value)?; conn.execute( "UPDATE subject_configs SET prompts = ?1 WHERE id = ?2", params![updated_prompts_json, id], )?; updated_count += 1; println!("✅ 已修复科目配置prompts: {}", id); } } } } if updated_count > 0 { println!("✅ SQLite: 已修复 {} 个科目配置的prompts字段", updated_count); } else { println!("✅ SQLite: 所有科目配置的prompts字段都已是最新格式"); } Ok(()) } fn migrate_v1_to_v2(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> { println!("🔄 数据库迁移: v1 -> v2 (添加Anki增强功能表)"); // 检查document_tasks表是否已存在 let document_tasks_exists = conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='document_tasks';")? .query_map([], |_| Ok(()))? .any(|_| true); if !document_tasks_exists { conn.execute( "CREATE TABLE document_tasks ( id TEXT PRIMARY KEY, document_id TEXT NOT NULL, original_document_name TEXT NOT NULL, segment_index INTEGER NOT NULL, content_segment TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('Pending', 'Processing', 'Streaming', 'Completed', 'Failed', 'Truncated', 'Cancelled')), created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), error_message TEXT, subject_name TEXT NOT NULL, anki_generation_options_json TEXT NOT NULL );", [], )?; println!("✅ 创建document_tasks表"); } // 检查anki_cards表是否已存在 let anki_cards_exists = conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='anki_cards';")? .query_map([], |_| Ok(()))? .any(|_| true); if !anki_cards_exists { conn.execute( "CREATE TABLE anki_cards ( id TEXT PRIMARY KEY, task_id TEXT NOT NULL REFERENCES document_tasks(id) ON DELETE CASCADE, front TEXT NOT NULL, back TEXT NOT NULL, tags_json TEXT DEFAULT '[]', images_json TEXT DEFAULT '[]', is_error_card INTEGER NOT NULL DEFAULT 0, error_content TEXT, card_order_in_task INTEGER DEFAULT 0, created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) );", [], )?; println!("✅ 创建anki_cards表"); } // 创建索引 conn.execute("CREATE INDEX IF NOT EXISTS idx_document_tasks_document_id ON document_tasks(document_id);", [])?; conn.execute("CREATE INDEX IF NOT EXISTS idx_document_tasks_status ON document_tasks(status);", [])?; conn.execute("CREATE INDEX IF NOT EXISTS idx_anki_cards_task_id ON anki_cards(task_id);", [])?; conn.execute("CREATE INDEX IF NOT EXISTS idx_anki_cards_is_error_card ON anki_cards(is_error_card);", [])?; println!("✅ 数据库迁移完成: v1 -> v2"); Ok(()) } fn migrate_v2_to_v3(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> { println!("🔄 数据库迁移: v2 -> v3 (添加RAG配置表)"); // 检查rag_configurations表是否已存在 let rag_config_exists = conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='rag_configurations';")? .query_map([], |_| Ok(()))? .any(|_| true); if !rag_config_exists { conn.execute( "CREATE TABLE rag_configurations ( id TEXT PRIMARY KEY, chunk_size INTEGER NOT NULL DEFAULT 512, chunk_overlap INTEGER NOT NULL DEFAULT 50, chunking_strategy TEXT NOT NULL DEFAULT 'fixed_size', min_chunk_size INTEGER NOT NULL DEFAULT 20, default_top_k INTEGER NOT NULL DEFAULT 5, default_rerank_enabled INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL );", [], )?; println!("✅ 创建rag_configurations表"); // 插入默认配置 let now = Utc::now().to_rfc3339(); conn.execute( "INSERT INTO rag_configurations (id, chunk_size, chunk_overlap, chunking_strategy, min_chunk_size, default_top_k, default_rerank_enabled, created_at, updated_at) VALUES ('default', 512, 50, 'fixed_size', 20, 5, 0, ?1, ?2)", params![now, now], )?; println!("✅ 插入默认RAG配置"); } println!("✅ 数据库迁移完成: v2 -> v3"); Ok(()) } fn migrate_v3_to_v4(&self, _conn: &rusqlite::Connection) -> anyhow::Result<()> { println!("📦 开始数据库迁移 v3 -> v4: 添加RAG来源信息支持"); // v3到v4的迁移主要通过migrate_add_rag_sources_column处理 // 这里可以添加其他v4特有的迁移逻辑 println!("✅ 数据库迁移 v3 -> v4 完成"); Ok(()) } fn migrate_v4_to_v5(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> { println!("📦 开始数据库迁移 v4 -> v5: 升级回顾分析表结构"); // 强制创建review_analyses和review_chat_messages表(如果不存在) conn.execute( "CREATE TABLE IF NOT EXISTS review_analyses ( id TEXT PRIMARY KEY, name TEXT NOT NULL, subject TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, mistake_ids TEXT NOT NULL, consolidated_input TEXT NOT NULL, user_question TEXT NOT NULL, status TEXT NOT NULL, tags TEXT NOT NULL, analysis_type TEXT NOT NULL DEFAULT 'consolidated_review' )", [], )?; conn.execute( "CREATE TABLE IF NOT EXISTS review_chat_messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, review_analysis_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, timestamp TEXT NOT NULL, thinking_content TEXT, rag_sources TEXT, FOREIGN KEY(review_analysis_id) REFERENCES review_analyses(id) ON DELETE CASCADE )", [], )?; println!("✅ 强制创建了review_analyses和review_chat_messages表"); // 迁移旧的review_sessions到新的review_analyses self.migrate_review_sessions_to_review_analyses(conn)?; println!("✅ 数据库迁移 v4 -> v5 完成"); Ok(()) } fn migrate_v5_to_v6(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> { println!("📦 开始数据库迁移 v5 -> v6: 修复回顾分析表结构"); // 强制重新创建review_analyses和review_chat_messages表,确保schema正确 conn.execute("DROP TABLE IF EXISTS review_chat_messages", [])?; conn.execute("DROP TABLE IF EXISTS review_analyses", [])?; conn.execute( "CREATE TABLE review_analyses ( id TEXT PRIMARY KEY, name TEXT NOT NULL, subject TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, mistake_ids TEXT NOT NULL, consolidated_input TEXT NOT NULL, user_question TEXT NOT NULL, status TEXT NOT NULL, tags TEXT NOT NULL, analysis_type TEXT NOT NULL DEFAULT 'consolidated_review' )", [], )?; conn.execute( "CREATE TABLE review_chat_messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, review_analysis_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, timestamp TEXT NOT NULL, thinking_content TEXT, rag_sources TEXT, FOREIGN KEY(review_analysis_id) REFERENCES review_analyses(id) ON DELETE CASCADE )", [], )?; println!("✅ 重新创建了review_analyses和review_chat_messages表"); println!("✅ 数据库迁移 v5 -> v6 完成"); Ok(()) } fn migrate_v6_to_v7(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> { println!("📦 开始数据库迁移 v6 -> v7: 添加错题总结字段"); // 为mistakes表添加新的总结字段 conn.execute( "ALTER TABLE mistakes ADD COLUMN mistake_summary TEXT", [], )?; conn.execute( "ALTER TABLE mistakes ADD COLUMN user_error_analysis TEXT", [], )?; println!("✅ 已为mistakes表添加mistake_summary和user_error_analysis字段"); println!("✅ 数据库迁移 v6 -> v7 完成"); Ok(()) } fn migrate_v7_to_v8(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> { println!("📦 开始数据库迁移 v7 -> v8: 添加模板支持字段"); // 为anki_cards表添加扩展字段和模板ID字段 let add_extra_fields = conn.execute( "ALTER TABLE anki_cards ADD COLUMN extra_fields_json TEXT DEFAULT '{}'", [], ); let add_template_id = conn.execute( "ALTER TABLE anki_cards ADD COLUMN template_id TEXT", [], ); match (add_extra_fields, add_template_id) { (Ok(_), Ok(_)) => { println!("✅ 已为anki_cards表添加extra_fields_json和template_id字段"); } (Err(e1), Err(e2)) => { println!("⚠️ 添加字段时遇到错误,可能字段已存在: {} / {}", e1, e2); } (Ok(_), Err(e)) => { println!("⚠️ 添加template_id字段时遇到错误,可能字段已存在: {}", e); } (Err(e), Ok(_)) => { println!("⚠️ 添加extra_fields_json字段时遇到错误,可能字段已存在: {}", e); } } // 创建自定义模板表 conn.execute( "CREATE TABLE IF NOT EXISTS custom_anki_templates ( id TEXT PRIMARY KEY, name TEXT NOT NULL UNIQUE, description TEXT, author TEXT, version TEXT NOT NULL DEFAULT '1.0.0', preview_front TEXT NOT NULL, preview_back TEXT NOT NULL, note_type TEXT NOT NULL DEFAULT 'Basic', fields_json TEXT NOT NULL DEFAULT '[]', generation_prompt TEXT NOT NULL, front_template TEXT NOT NULL, back_template TEXT NOT NULL, css_style TEXT NOT NULL, field_extraction_rules_json TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), is_active INTEGER NOT NULL DEFAULT 1, is_built_in INTEGER NOT NULL DEFAULT 0 );", [], )?; // 创建模板表索引 conn.execute("CREATE INDEX IF NOT EXISTS idx_custom_anki_templates_is_active ON custom_anki_templates(is_active);", [])?; conn.execute("CREATE INDEX IF NOT EXISTS idx_custom_anki_templates_is_built_in ON custom_anki_templates(is_built_in);", [])?; println!("✅ 已创建custom_anki_templates表"); println!("✅ 数据库迁移 v7 -> v8 完成"); Ok(()) } // 自定义模板管理方法 /// 创建自定义模板 pub fn create_custom_template(&self, request: &crate::models::CreateTemplateRequest) -> Result<String> { let conn = self.conn.lock().unwrap(); let template_id = uuid::Uuid::new_v4().to_string(); let now = Utc::now().to_rfc3339(); conn.execute( "INSERT INTO custom_anki_templates (id, name, description, author, version, preview_front, preview_back, note_type, fields_json, generation_prompt, front_template, back_template, css_style, field_extraction_rules_json, created_at, updated_at, is_active, is_built_in) VALUES (?1, ?2, ?3, ?4, '1.0.0', ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, 1, 0)", params![ template_id, request.name, request.description, request.author, request.preview_front, request.preview_back, request.note_type, serde_json::to_string(&request.fields)?, request.generation_prompt, request.front_template, request.back_template, request.css_style, serde_json::to_string(&request.field_extraction_rules)?, now.clone(), now ] )?; Ok(template_id) } /// 获取所有自定义模板 pub fn get_all_custom_templates(&self) -> Result<Vec<crate::models::CustomAnkiTemplate>> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT id, name, description, author, version, preview_front, preview_back, note_type, fields_json, generation_prompt, front_template, back_template, css_style, field_extraction_rules_json, created_at, updated_at, is_active, is_built_in FROM custom_anki_templates ORDER BY created_at DESC" )?; let template_iter = stmt.query_map([], |row| { let fields_json: String = row.get(8)?; let fields: Vec<String> = serde_json::from_str(&fields_json).unwrap_or_default(); let rules_json: String = row.get(13)?; let field_extraction_rules: std::collections::HashMap<String, crate::models::FieldExtractionRule> = serde_json::from_str(&rules_json).unwrap_or_default(); let created_at_str: String = row.get(14)?; let updated_at_str: String = row.get(15)?; Ok(crate::models::CustomAnkiTemplate { id: row.get(0)?, name: row.get(1)?, description: row.get(2)?, author: row.get(3)?, version: row.get(4)?, preview_front: row.get(5)?, preview_back: row.get(6)?, note_type: row.get(7)?, fields, generation_prompt: row.get(9)?, front_template: row.get(10)?, back_template: row.get(11)?, css_style: row.get(12)?, field_extraction_rules, created_at: DateTime::parse_from_rfc3339(&created_at_str).unwrap().with_timezone(&Utc), updated_at: DateTime::parse_from_rfc3339(&updated_at_str).unwrap().with_timezone(&Utc), is_active: row.get::<_, i32>(16)? != 0, is_built_in: row.get::<_, i32>(17)? != 0, }) })?; let mut templates = Vec::new(); for template in template_iter { templates.push(template?); } Ok(templates) } /// 获取指定ID的自定义模板 pub fn get_custom_template_by_id(&self, template_id: &str) -> Result<Option<crate::models::CustomAnkiTemplate>> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT id, name, description, author, version, preview_front, preview_back, note_type, fields_json, generation_prompt, front_template, back_template, css_style, field_extraction_rules_json, created_at, updated_at, is_active, is_built_in FROM custom_anki_templates WHERE id = ?1" )?; let result = stmt.query_row(params![template_id], |row| { let fields_json: String = row.get(8)?; let fields: Vec<String> = serde_json::from_str(&fields_json).unwrap_or_default(); let rules_json: String = row.get(13)?; let field_extraction_rules: std::collections::HashMap<String, crate::models::FieldExtractionRule> = serde_json::from_str(&rules_json).unwrap_or_default(); let created_at_str: String = row.get(14)?; let updated_at_str: String = row.get(15)?; Ok(crate::models::CustomAnkiTemplate { id: row.get(0)?, name: row.get(1)?, description: row.get(2)?, author: row.get(3)?, version: row.get(4)?, preview_front: row.get(5)?, preview_back: row.get(6)?, note_type: row.get(7)?, fields, generation_prompt: row.get(9)?, front_template: row.get(10)?, back_template: row.get(11)?, css_style: row.get(12)?, field_extraction_rules, created_at: DateTime::parse_from_rfc3339(&created_at_str).unwrap().with_timezone(&Utc), updated_at: DateTime::parse_from_rfc3339(&updated_at_str).unwrap().with_timezone(&Utc), is_active: row.get::<_, i32>(16)? != 0, is_built_in: row.get::<_, i32>(17)? != 0, }) }).optional()?; Ok(result) } /// 更新自定义模板 pub fn update_custom_template(&self, template_id: &str, request: &crate::models::UpdateTemplateRequest) -> Result<()> { let conn = self.conn.lock().unwrap(); let now = Utc::now().to_rfc3339(); let mut query_parts = Vec::new(); let mut params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new(); // 将需要长期存储的值移动到这里,避免借用生命周期问题 let mut owned_fields_json = None; let mut owned_rules_json = None; let mut owned_active_val = None; if let Some(name) = &request.name { query_parts.push("name = ?".to_string()); params.push(Box::new(name.clone())); } if let Some(description) = &request.description { query_parts.push("description = ?".to_string()); params.push(Box::new(description.clone())); } if let Some(author) = &request.author { query_parts.push("author = ?".to_string()); params.push(Box::new(author.clone())); } if let Some(preview_front) = &request.preview_front { query_parts.push("preview_front = ?".to_string()); params.push(Box::new(preview_front.clone())); } if let Some(preview_back) = &request.preview_back { query_parts.push("preview_back = ?".to_string()); params.push(Box::new(preview_back.clone())); } if let Some(note_type) = &request.note_type { query_parts.push("note_type = ?".to_string()); params.push(Box::new(note_type.clone())); } if let Some(fields) = &request.fields { query_parts.push("fields_json = ?".to_string()); let fields_json = serde_json::to_string(fields)?; owned_fields_json = Some(fields_json.clone()); params.push(Box::new(fields_json)); } if let Some(generation_prompt) = &request.generation_prompt { query_parts.push("generation_prompt = ?".to_string()); params.push(Box::new(generation_prompt.clone())); } if let Some(front_template) = &request.front_template { query_parts.push("front_template = ?".to_string()); params.push(Box::new(front_template.clone())); } if let Some(back_template) = &request.back_template { query_parts.push("back_template = ?".to_string()); params.push(Box::new(back_template.clone())); } if let Some(css_style) = &request.css_style { query_parts.push("css_style = ?".to_string()); params.push(Box::new(css_style.clone())); } if let Some(field_extraction_rules) = &request.field_extraction_rules { query_parts.push("field_extraction_rules_json = ?".to_string()); let rules_json = serde_json::to_string(field_extraction_rules)?; owned_rules_json = Some(rules_json.clone()); params.push(Box::new(rules_json)); } if let Some(is_active) = &request.is_active { query_parts.push("is_active = ?".to_string()); let active_val = if *is_active { 1 } else { 0 }; owned_active_val = Some(active_val); params.push(Box::new(active_val)); } if query_parts.is_empty() { return Ok(()); } query_parts.push("updated_at = ?".to_string()); params.push(Box::new(now)); params.push(Box::new(template_id.to_string())); let query = format!( "UPDATE custom_anki_templates SET {} WHERE id = ?", query_parts.join(", ") ); conn.execute(&query, rusqlite::params_from_iter(params.iter().map(|p| p.as_ref())))?; Ok(()) } /// 删除自定义模板 pub fn delete_custom_template(&self, template_id: &str) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute("DELETE FROM custom_anki_templates WHERE id = ?1 AND is_built_in = 0", params![template_id])?; Ok(()) } fn migrate_review_sessions_to_review_analyses(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> { // 检查旧表是否存在 let old_table_exists = conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='review_sessions';")? .query_map([], |_| Ok(()))? .any(|_| true); if !old_table_exists { println!("⏭️ 旧的review_sessions表不存在,跳过迁移"); return Ok(()); } println!("🔄 迁移review_sessions数据到review_analyses"); // 创建新表(如果不存在) conn.execute( "CREATE TABLE IF NOT EXISTS review_analyses ( id TEXT PRIMARY KEY, name TEXT NOT NULL, subject TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, mistake_ids TEXT NOT NULL, consolidated_input TEXT NOT NULL, user_question TEXT NOT NULL, status TEXT NOT NULL, tags TEXT NOT NULL, analysis_type TEXT NOT NULL DEFAULT 'consolidated_review' )", [], )?; conn.execute( "CREATE TABLE IF NOT EXISTS review_chat_messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, review_analysis_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, timestamp TEXT NOT NULL, thinking_content TEXT, rag_sources TEXT, FOREIGN KEY(review_analysis_id) REFERENCES review_analyses(id) ON DELETE CASCADE )", [], )?; // 迁移数据 let mut stmt = conn.prepare("SELECT id, subject, mistake_ids, analysis_result, created_at FROM review_sessions")?; let old_sessions: Vec<(String, String, String, String, String)> = stmt.query_map([], |row| { Ok(( row.get::<_, String>(0)?, // id row.get::<_, String>(1)?, // subject row.get::<_, String>(2)?, // mistake_ids row.get::<_, String>(3)?, // analysis_result row.get::<_, String>(4)?, // created_at )) })?.collect::<rusqlite::Result<Vec<_>>>()?; let migration_count = old_sessions.len(); for (id, subject, mistake_ids, analysis_result, created_at) in old_sessions { // 插入到新表 conn.execute( "INSERT OR IGNORE INTO review_analyses (id, name, subject, created_at, updated_at, mistake_ids, consolidated_input, user_question, status, tags, analysis_type) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", params![ id, format!("回顾分析-{}", chrono::Utc::now().format("%Y%m%d")), // 默认名称 subject, created_at, chrono::Utc::now().to_rfc3339(), // updated_at mistake_ids, analysis_result, // 作为consolidated_input "统一回顾分析", // 默认用户问题 "completed", // 默认状态 "[]", // 空标签数组 "consolidated_review" ] )?; // 迁移聊天记录 let mut chat_stmt = conn.prepare("SELECT role, content, timestamp FROM review_chat_messages WHERE review_id = ?1")?; let chat_messages: Vec<(String, String, String)> = chat_stmt.query_map([&id], |row| { Ok(( row.get::<_, String>(0)?, // role row.get::<_, String>(1)?, // content row.get::<_, String>(2)?, // timestamp )) })?.collect::<rusqlite::Result<Vec<_>>>()?; for (role, content, timestamp) in chat_messages { conn.execute( "INSERT INTO review_chat_messages (review_analysis_id, role, content, timestamp, thinking_content, rag_sources) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", params![id, role, content, timestamp, None::<String>, None::<String>] )?; } } // 删除旧表(可选,为了保险起见先保留) // conn.execute("DROP TABLE IF EXISTS review_sessions", [])?; // conn.execute("DROP TABLE IF EXISTS review_chat_messages", [])?; println!("✅ review_sessions迁移完成,迁移了{}条记录", migration_count); Ok(()) } /// 保存错题及其聊天记录 pub fn save_mistake(&self, mistake: &MistakeItem) -> Result<()> { // 验证JSON格式以防止存储损坏的数据 self.validate_mistake_json_fields(mistake)?; let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction()?; tx.execute( "INSERT OR REPLACE INTO mistakes (id, subject, created_at, question_images, analysis_images, user_question, ocr_text, tags, mistake_type, status, updated_at, mistake_summary, user_error_analysis) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)", params![ mistake.id, mistake.subject, mistake.created_at.to_rfc3339(), serde_json::to_string(&mistake.question_images)?, serde_json::to_string(&mistake.analysis_images)?, mistake.user_question, mistake.ocr_text, serde_json::to_string(&mistake.tags)?, mistake.mistake_type, mistake.status, Utc::now().to_rfc3339(), mistake.mistake_summary, mistake.user_error_analysis, ], )?; // 删除旧的聊天记录,然后插入新的 tx.execute("DELETE FROM chat_messages WHERE mistake_id = ?1", params![mistake.id])?; for message in &mistake.chat_history { // 序列化RAG来源信息为JSON let rag_sources_json = message.rag_sources.as_ref() .map(|sources| serde_json::to_string(sources).unwrap_or_default()); tx.execute( "INSERT INTO chat_messages (mistake_id, role, content, timestamp, thinking_content, rag_sources) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", params![mistake.id, message.role, message.content, message.timestamp.to_rfc3339(), message.thinking_content, rag_sources_json], )?; } tx.commit()?; Ok(()) } /// 保存回顾分析及其聊天记录 - 复用错题分析的保存模式 pub fn save_review_analysis(&self, review: &ReviewAnalysisItem) -> Result<()> { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction()?; tx.execute( "INSERT OR REPLACE INTO review_analyses (id, name, subject, created_at, updated_at, mistake_ids, consolidated_input, user_question, status, tags, analysis_type) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", params![ review.id, review.name, review.subject, review.created_at.to_rfc3339(), review.updated_at.to_rfc3339(), serde_json::to_string(&review.mistake_ids)?, review.consolidated_input, review.user_question, review.status, serde_json::to_string(&review.tags)?, review.analysis_type, ], )?; // 删除旧的聊天记录,然后插入新的 tx.execute("DELETE FROM review_chat_messages WHERE review_analysis_id = ?1", params![review.id])?; for message in &review.chat_history { let rag_sources_json = message.rag_sources.as_ref() .map(|sources| serde_json::to_string(sources)) .transpose()?; tx.execute( "INSERT INTO review_chat_messages (review_analysis_id, role, content, timestamp, thinking_content, rag_sources) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", params![ review.id, message.role, message.content, message.timestamp.to_rfc3339(), message.thinking_content, rag_sources_json, ], )?; } tx.commit()?; Ok(()) } /// 根据ID获取错题及其聊天记录 pub fn get_mistake_by_id(&self, id: &str) -> Result<Option<MistakeItem>> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT id, subject, created_at, question_images, analysis_images, user_question, ocr_text, tags, mistake_type, status, updated_at, mistake_summary, user_error_analysis FROM mistakes WHERE id = ?1" )?; let mistake_item = stmt.query_row(params![id], |row| { let created_at_str: String = row.get(2)?; let updated_at_str: String = row.get(10)?; let question_images_str: String = row.get(3)?; let analysis_images_str: String = row.get(4)?; let tags_str: String = row.get(7)?; let created_at = DateTime::parse_from_rfc3339(&created_at_str) .map_err(|_| rusqlite::Error::InvalidColumnType(2, "created_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let updated_at = DateTime::parse_from_rfc3339(&updated_at_str) .map_err(|_| rusqlite::Error::InvalidColumnType(10, "updated_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let question_images: Vec<String> = serde_json::from_str(&question_images_str) .map_err(|_| rusqlite::Error::InvalidColumnType(3, "question_images".to_string(), rusqlite::types::Type::Text))?; let analysis_images: Vec<String> = serde_json::from_str(&analysis_images_str) .map_err(|_| rusqlite::Error::InvalidColumnType(4, "analysis_images".to_string(), rusqlite::types::Type::Text))?; let tags: Vec<String> = serde_json::from_str(&tags_str) .map_err(|_| rusqlite::Error::InvalidColumnType(7, "tags".to_string(), rusqlite::types::Type::Text))?; Ok(MistakeItem { id: row.get(0)?, subject: row.get(1)?, created_at, question_images, analysis_images, user_question: row.get(5)?, ocr_text: row.get(6)?, tags, mistake_type: row.get(8)?, status: row.get(9)?, updated_at, chat_history: vec![], // 稍后填充 mistake_summary: row.get(11)?, // 新增字段 user_error_analysis: row.get(12)?, // 新增字段 }) }).optional()?; if let Some(mut item) = mistake_item { let mut chat_stmt = conn.prepare( "SELECT role, content, timestamp, thinking_content, rag_sources FROM chat_messages WHERE mistake_id = ?1 ORDER BY timestamp ASC" )?; let chat_iter = chat_stmt.query_map(params![id], |row| { let timestamp_str: String = row.get(2)?; let timestamp = DateTime::parse_from_rfc3339(&timestamp_str) .map_err(|_| rusqlite::Error::InvalidColumnType(2, "timestamp".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); // 反序列化RAG来源信息 let rag_sources: Option<Vec<crate::models::RagSourceInfo>> = if let Ok(Some(rag_sources_str)) = row.get::<_, Option<String>>(4) { serde_json::from_str(&rag_sources_str).ok() } else { None }; Ok(ChatMessage { role: row.get(0)?, content: row.get(1)?, timestamp, thinking_content: row.get(3)?, rag_sources, image_paths: None, image_base64: None, }) })?; for msg_result in chat_iter { item.chat_history.push(msg_result?); } Ok(Some(item)) } else { Ok(None) } } /// 根据ID获取回顾分析及其聊天记录 - 复用错题分析的查询模式 pub fn get_review_analysis_by_id(&self, id: &str) -> Result<Option<ReviewAnalysisItem>> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT id, name, subject, created_at, updated_at, mistake_ids, consolidated_input, user_question, status, tags, analysis_type FROM review_analyses WHERE id = ?1" )?; let review_item = stmt.query_row(params![id], |row| { let created_at_str: String = row.get(3)?; let updated_at_str: String = row.get(4)?; let mistake_ids_str: String = row.get(5)?; let tags_str: String = row.get(9)?; let created_at = DateTime::parse_from_rfc3339(&created_at_str) .map_err(|_| rusqlite::Error::InvalidColumnType(3, "created_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let updated_at = DateTime::parse_from_rfc3339(&updated_at_str) .map_err(|_| rusqlite::Error::InvalidColumnType(4, "updated_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let mistake_ids: Vec<String> = serde_json::from_str(&mistake_ids_str) .map_err(|_| rusqlite::Error::InvalidColumnType(5, "mistake_ids".to_string(), rusqlite::types::Type::Text))?; let tags: Vec<String> = serde_json::from_str(&tags_str) .map_err(|_| rusqlite::Error::InvalidColumnType(9, "tags".to_string(), rusqlite::types::Type::Text))?; Ok(ReviewAnalysisItem { id: row.get(0)?, name: row.get(1)?, subject: row.get(2)?, created_at, updated_at, mistake_ids, consolidated_input: row.get(6)?, user_question: row.get(7)?, status: row.get(8)?, tags, analysis_type: row.get(10)?, chat_history: vec![], // 稍后填充 }) }).optional()?; if let Some(mut item) = review_item { let mut chat_stmt = conn.prepare( "SELECT role, content, timestamp, thinking_content, rag_sources FROM review_chat_messages WHERE review_analysis_id = ?1 ORDER BY timestamp ASC" )?; let chat_iter = chat_stmt.query_map(params![id], |row| { let timestamp_str: String = row.get(2)?; let timestamp = DateTime::parse_from_rfc3339(&timestamp_str) .map_err(|_| rusqlite::Error::InvalidColumnType(2, "timestamp".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); // 反序列化RAG来源信息 let rag_sources: Option<Vec<crate::models::RagSourceInfo>> = if let Ok(Some(rag_sources_str)) = row.get::<_, Option<String>>(4) { serde_json::from_str(&rag_sources_str).ok() } else { None }; Ok(ChatMessage { role: row.get(0)?, content: row.get(1)?, timestamp, thinking_content: row.get(3)?, rag_sources, image_paths: None, image_base64: None, }) })?; for msg_result in chat_iter { item.chat_history.push(msg_result?); } Ok(Some(item)) } else { Ok(None) } } /// 获取错题列表(支持筛选) pub fn get_mistakes( &self, subject_filter: Option<&str>, type_filter: Option<&str>, tags_filter: Option<&[String]>, // 标签包含任意一个即可 ) -> Result<Vec<MistakeItem>> { let mut query = "SELECT id, subject, created_at, question_images, analysis_images, user_question, ocr_text, tags, mistake_type, status, updated_at FROM mistakes WHERE 1=1".to_string(); let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = Vec::new(); if let Some(s) = subject_filter { query.push_str(" AND subject = ?"); params_vec.push(Box::new(s.to_string())); } if let Some(t) = type_filter { query.push_str(" AND mistake_type = ?"); params_vec.push(Box::new(t.to_string())); } // 注意: SQLite JSON 函数通常需要特定构建或扩展。 // 这里的标签过滤是一个简化版本,实际可能需要更复杂的查询或在应用层过滤。 // 一个更健壮的方法是使用JSON1扩展的json_each或json_extract。 // 为简单起见,如果提供了标签过滤器,我们暂时获取所有数据并在Rust中过滤。 // 或者,如果标签数量不多,可以构建 LIKE '%tag1%' OR LIKE '%tag2%' 这样的查询。 let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare(&query)?; let mut rows = stmt.query(rusqlite::params_from_iter(params_vec.iter().map(|p| p.as_ref())))?; let mut mistakes = Vec::new(); while let Some(row) = rows.next()? { let created_at_str: String = row.get(2).map_err(|e| anyhow::anyhow!("Failed to get created_at: {}", e))?; let updated_at_str: String = row.get(10).map_err(|e| anyhow::anyhow!("Failed to get updated_at: {}", e))?; let tags_json: String = row.get(7).map_err(|e| anyhow::anyhow!("Failed to get tags: {}", e))?; let current_tags: Vec<String> = serde_json::from_str(&tags_json) .map_err(|e| anyhow::anyhow!("Failed to parse tags JSON: {}", e))?; // 应用层标签过滤 if let Some(filter_tags) = tags_filter { if filter_tags.is_empty() || !filter_tags.iter().any(|ft| current_tags.contains(ft)) { if !filter_tags.is_empty() { // 如果过滤器非空但不匹配,则跳过 continue; } } } let question_images_str: String = row.get(3).map_err(|e| anyhow::anyhow!("Failed to get question_images: {}", e))?; let analysis_images_str: String = row.get(4).map_err(|e| anyhow::anyhow!("Failed to get analysis_images: {}", e))?; let created_at = DateTime::parse_from_rfc3339(&created_at_str) .map_err(|e| anyhow::anyhow!("Failed to parse created_at: {}", e))? .with_timezone(&Utc); let updated_at = DateTime::parse_from_rfc3339(&updated_at_str) .map_err(|e| anyhow::anyhow!("Failed to parse updated_at: {}", e))? .with_timezone(&Utc); let question_images: Vec<String> = serde_json::from_str(&question_images_str) .map_err(|e| anyhow::anyhow!("Failed to parse question_images JSON: {}", e))?; let analysis_images: Vec<String> = serde_json::from_str(&analysis_images_str) .map_err(|e| anyhow::anyhow!("Failed to parse analysis_images JSON: {}", e))?; let item = MistakeItem { id: row.get(0).map_err(|e| anyhow::anyhow!("Failed to get id: {}", e))?, subject: row.get(1).map_err(|e| anyhow::anyhow!("Failed to get subject: {}", e))?, created_at, question_images, analysis_images, user_question: row.get(5).map_err(|e| anyhow::anyhow!("Failed to get user_question: {}", e))?, ocr_text: row.get(6).map_err(|e| anyhow::anyhow!("Failed to get ocr_text: {}", e))?, tags: current_tags, mistake_type: row.get(8).map_err(|e| anyhow::anyhow!("Failed to get mistake_type: {}", e))?, status: row.get(9).map_err(|e| anyhow::anyhow!("Failed to get status: {}", e))?, updated_at, chat_history: vec![], // 列表视图通常不需要完整的聊天记录 mistake_summary: None, // 列表视图不加载总结 user_error_analysis: None, // 列表视图不加载分析 }; mistakes.push(item); } Ok(mistakes) } /// 获取回顾分析列表(复用错题分析的列表模式) pub fn get_review_analyses( &self, subject_filter: Option<&str>, status_filter: Option<&str>, ) -> Result<Vec<ReviewAnalysisItem>> { let mut query = "SELECT id, name, subject, created_at, updated_at, mistake_ids, consolidated_input, user_question, status, tags, analysis_type FROM review_analyses WHERE 1=1".to_string(); let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = Vec::new(); if let Some(s) = subject_filter { query.push_str(" AND subject = ?"); params_vec.push(Box::new(s.to_string())); } if let Some(st) = status_filter { query.push_str(" AND status = ?"); params_vec.push(Box::new(st.to_string())); } query.push_str(" ORDER BY created_at DESC"); let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare(&query)?; let mut rows = stmt.query(rusqlite::params_from_iter(params_vec.iter().map(|p| p.as_ref())))?; let mut analyses = Vec::new(); while let Some(row) = rows.next()? { let created_at_str: String = row.get(3)?; let updated_at_str: String = row.get(4)?; let mistake_ids_json: String = row.get(5)?; let tags_json: String = row.get(9)?; let created_at = DateTime::parse_from_rfc3339(&created_at_str) .map_err(|e| anyhow::anyhow!("Failed to parse created_at: {}", e))? .with_timezone(&Utc); let updated_at = DateTime::parse_from_rfc3339(&updated_at_str) .map_err(|e| anyhow::anyhow!("Failed to parse updated_at: {}", e))? .with_timezone(&Utc); let mistake_ids: Vec<String> = serde_json::from_str(&mistake_ids_json) .map_err(|e| anyhow::anyhow!("Failed to parse mistake_ids JSON: {}", e))?; let tags: Vec<String> = serde_json::from_str(&tags_json) .map_err(|e| anyhow::anyhow!("Failed to parse tags JSON: {}", e))?; let item = ReviewAnalysisItem { id: row.get(0)?, name: row.get(1)?, subject: row.get(2)?, created_at, updated_at, mistake_ids, consolidated_input: row.get(6)?, user_question: row.get(7)?, status: row.get(8)?, tags, analysis_type: row.get(10)?, chat_history: vec![], // 列表视图不需要完整的聊天记录 }; analyses.push(item); } Ok(analyses) } /// 删除错题(同时删除关联的聊天记录,通过FOREIGN KEY CASCADE) pub fn delete_mistake(&self, id: &str) -> Result<bool> { let conn = self.conn.lock().unwrap(); let changes = conn.execute("DELETE FROM mistakes WHERE id = ?1", params![id])?; Ok(changes > 0) } /// 保存设置 pub fn save_setting(&self, key: &str, value: &str) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute( "INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3)", params![key, value, Utc::now().to_rfc3339()], )?; Ok(()) } /// 获取设置 pub fn get_setting(&self, key: &str) -> Result<Option<String>> { let conn = self.conn.lock().unwrap(); conn.query_row( "SELECT value FROM settings WHERE key = ?1", params![key], |row| row.get(0), ).optional().map_err(Into::into) } /// 获取统计信息 pub fn get_statistics(&self) -> Result<Statistics> { let conn = self.conn.lock().unwrap(); // 获取错题总数 let total_mistakes: i32 = conn.query_row( "SELECT COUNT(*) FROM mistakes", [], |row| row.get(0), )?; // 获取回顾分析总数(暂时为0,等实现回顾功能时更新) let total_reviews: i32 = 0; // 获取各科目统计 let mut subject_stats = std::collections::HashMap::new(); let mut stmt_subjects = conn.prepare("SELECT subject, COUNT(*) as count FROM mistakes GROUP BY subject")?; let subject_iter = stmt_subjects.query_map([], |row| { Ok((row.get::<_, String>(0)?, row.get::<_, i32>(1)?)) })?; for subject_result in subject_iter { let (subject, count) = subject_result?; subject_stats.insert(subject, count); } // 获取各题目类型统计 let mut type_stats = std::collections::HashMap::new(); let mut stmt_types = conn.prepare("SELECT mistake_type, COUNT(*) as count FROM mistakes GROUP BY mistake_type")?; let type_iter = stmt_types.query_map([], |row| { Ok((row.get::<_, String>(0)?, row.get::<_, i32>(1)?)) })?; for type_result in type_iter { let (mistake_type, count) = type_result?; type_stats.insert(mistake_type, count); } // 获取标签统计 let mut tag_stats = std::collections::HashMap::new(); let mut stmt_tags = conn.prepare("SELECT tags FROM mistakes WHERE tags IS NOT NULL AND tags != ''")?; let tag_iter = stmt_tags.query_map([], |row| { Ok(row.get::<_, String>(0)?) })?; for tag_result in tag_iter { let tags_json = tag_result?; if let Ok(tags) = serde_json::from_str::<Vec<String>>(&tags_json) { for tag in tags { *tag_stats.entry(tag).or_insert(0) += 1; } } } // 获取最近的错题 let mut recent_mistakes = Vec::new(); let mut stmt_recent = conn.prepare( "SELECT id, subject, user_question, tags, created_at FROM mistakes ORDER BY created_at DESC LIMIT 5" )?; let recent_iter = stmt_recent.query_map([], |row| { Ok(serde_json::json!({ "id": row.get::<_, String>(0)?, "subject": row.get::<_, String>(1)?, "user_question": row.get::<_, String>(2)?, "tags": serde_json::from_str::<Vec<String>>(&row.get::<_, String>(3)?).unwrap_or_default(), "created_at": row.get::<_, String>(4)? })) })?; for recent_result in recent_iter { recent_mistakes.push(recent_result?); } Ok(Statistics { total_mistakes, total_reviews, subject_stats, type_stats, tag_stats, recent_mistakes, }) } // TODO: 实现 review_sessions 和 review_chat_messages 表的相关操作 /// 保存回顾分析会话 pub fn save_review_session(&self, session: &crate::models::ReviewSession) -> Result<()> { let conn = self.conn.lock().unwrap(); let tx = conn.unchecked_transaction()?; // 保存会话基本信息 tx.execute( "INSERT OR REPLACE INTO review_sessions (id, subject, mistake_ids, analysis_summary, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", params![ session.id, session.subject, serde_json::to_string(&session.mistake_ids)?, session.analysis_summary, session.created_at.to_rfc3339(), session.updated_at.to_rfc3339() ], )?; // 删除旧的聊天记录 tx.execute("DELETE FROM review_chat_messages WHERE session_id = ?1", params![session.id])?; // 保存聊天记录 for msg in &session.chat_history { tx.execute( "INSERT INTO review_chat_messages (id, session_id, role, content, timestamp) VALUES (?1, ?2, ?3, ?4, ?5)", params![ msg.id, msg.session_id, msg.role, msg.content, msg.timestamp.to_rfc3339() ], )?; } tx.commit()?; Ok(()) } /// 根据ID获取回顾分析会话 pub fn get_review_session_by_id(&self, id: &str) -> Result<Option<crate::models::ReviewSession>> { let conn = self.conn.lock().unwrap(); let session_result = conn.query_row( "SELECT id, subject, mistake_ids, analysis_summary, created_at, updated_at FROM review_sessions WHERE id = ?1", params![id], |row| { let created_at_str: String = row.get(4)?; let updated_at_str: String = row.get(5)?; let mistake_ids_str: String = row.get(2)?; let created_at = DateTime::parse_from_rfc3339(&created_at_str) .map_err(|_| rusqlite::Error::InvalidColumnType(4, "created_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let updated_at = DateTime::parse_from_rfc3339(&updated_at_str) .map_err(|_| rusqlite::Error::InvalidColumnType(5, "updated_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let mistake_ids: Vec<String> = serde_json::from_str(&mistake_ids_str) .map_err(|_| rusqlite::Error::InvalidColumnType(2, "mistake_ids".to_string(), rusqlite::types::Type::Text))?; Ok(crate::models::ReviewSession { id: row.get(0)?, subject: row.get(1)?, mistake_ids, analysis_summary: row.get(3)?, created_at, updated_at, chat_history: vec![], // 稍后填充 }) } ).optional()?; if let Some(mut session) = session_result { // 获取聊天记录 let mut chat_stmt = conn.prepare( "SELECT id, session_id, role, content, timestamp FROM review_chat_messages WHERE session_id = ?1 ORDER BY timestamp ASC" )?; let chat_iter = chat_stmt.query_map(params![id], |row| { let timestamp_str: String = row.get(4)?; let timestamp = DateTime::parse_from_rfc3339(&timestamp_str) .map_err(|_| rusqlite::Error::InvalidColumnType(4, "timestamp".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); Ok(crate::models::ReviewChatMessage { id: row.get(0)?, session_id: row.get(1)?, role: row.get(2)?, content: row.get(3)?, timestamp, }) })?; for msg_result in chat_iter { session.chat_history.push(msg_result?); } Ok(Some(session)) } else { Ok(None) } } /// 获取回顾分析会话列表 pub fn get_review_sessions(&self, subject_filter: Option<&str>) -> Result<Vec<crate::models::ReviewSession>> { let conn = self.conn.lock().unwrap(); let mut query = "SELECT id, subject, mistake_ids, analysis_summary, created_at, updated_at FROM review_sessions WHERE 1=1".to_string(); let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = Vec::new(); if let Some(subject) = subject_filter { query.push_str(" AND subject = ?"); params_vec.push(Box::new(subject.to_string())); } query.push_str(" ORDER BY created_at DESC"); let mut stmt = conn.prepare(&query)?; let mut rows = stmt.query(rusqlite::params_from_iter(params_vec.iter().map(|p| p.as_ref())))?; let mut sessions = Vec::new(); while let Some(row) = rows.next()? { let created_at_str: String = row.get(4)?; let updated_at_str: String = row.get(5)?; let mistake_ids_str: String = row.get(2)?; let created_at = DateTime::parse_from_rfc3339(&created_at_str) .map_err(|e| anyhow::anyhow!("Failed to parse created_at: {}", e))? .with_timezone(&Utc); let updated_at = DateTime::parse_from_rfc3339(&updated_at_str) .map_err(|e| anyhow::anyhow!("Failed to parse updated_at: {}", e))? .with_timezone(&Utc); let mistake_ids: Vec<String> = serde_json::from_str(&mistake_ids_str) .map_err(|e| anyhow::anyhow!("Failed to parse mistake_ids JSON: {}", e))?; let session = crate::models::ReviewSession { id: row.get(0)?, subject: row.get(1)?, mistake_ids, analysis_summary: row.get(3)?, created_at, updated_at, chat_history: vec![], // 列表视图不需要完整聊天记录 }; sessions.push(session); } Ok(sessions) } /// 删除回顾分析会话 pub fn delete_review_session(&self, id: &str) -> Result<bool> { let conn = self.conn.lock().unwrap(); let changes = conn.execute("DELETE FROM review_sessions WHERE id = ?1", params![id])?; Ok(changes > 0) } /// 删除回顾分析(统一回顾分析功能) pub fn delete_review_analysis(&self, id: &str) -> Result<bool> { let conn = self.conn.lock().unwrap(); // 由于设置了 ON DELETE CASCADE,删除主记录时会自动删除关联的聊天消息 let changes = conn.execute("DELETE FROM review_analyses WHERE id = ?1", params![id])?; Ok(changes > 0) } /// 添加回顾分析聊天消息 pub fn add_review_chat_message(&self, message: &crate::models::ReviewChatMessage) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute( "INSERT INTO review_chat_messages (id, session_id, role, content, timestamp) VALUES (?1, ?2, ?3, ?4, ?5)", params![ message.id, message.session_id, message.role, message.content, message.timestamp.to_rfc3339() ], )?; // 更新会话的更新时间 conn.execute( "UPDATE review_sessions SET updated_at = ?1 WHERE id = ?2", params![Utc::now().to_rfc3339(), message.session_id], )?; Ok(()) } // 科目配置管理方法 /// 保存科目配置 pub fn save_subject_config(&self, config: &SubjectConfig) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute( "INSERT OR REPLACE INTO subject_configs (id, subject_name, display_name, description, is_enabled, prompts, mistake_types, default_tags, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", params![ config.id, config.subject_name, config.display_name, config.description, config.is_enabled as i32, serde_json::to_string(&config.prompts)?, serde_json::to_string(&config.mistake_types)?, serde_json::to_string(&config.default_tags)?, config.created_at.to_rfc3339(), config.updated_at.to_rfc3339(), ], )?; Ok(()) } /// 根据ID获取科目配置 pub fn get_subject_config_by_id(&self, id: &str) -> Result<Option<SubjectConfig>> { let conn = self.conn.lock().unwrap(); conn.query_row( "SELECT id, subject_name, display_name, description, is_enabled, prompts, mistake_types, default_tags, created_at, updated_at FROM subject_configs WHERE id = ?1", params![id], |row| { let created_at_str: String = row.get(8)?; let updated_at_str: String = row.get(9)?; let prompts_str: String = row.get(5)?; let mistake_types_str: String = row.get(6)?; let default_tags_str: String = row.get(7)?; let created_at = DateTime::parse_from_rfc3339(&created_at_str) .map_err(|_| rusqlite::Error::InvalidColumnType(8, "created_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let updated_at = DateTime::parse_from_rfc3339(&updated_at_str) .map_err(|_| rusqlite::Error::InvalidColumnType(9, "updated_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let prompts: SubjectPrompts = self.parse_subject_prompts(&prompts_str)?; let mistake_types: Vec<String> = serde_json::from_str(&mistake_types_str) .map_err(|_| rusqlite::Error::InvalidColumnType(6, "mistake_types".to_string(), rusqlite::types::Type::Text))?; let default_tags: Vec<String> = serde_json::from_str(&default_tags_str) .map_err(|_| rusqlite::Error::InvalidColumnType(7, "default_tags".to_string(), rusqlite::types::Type::Text))?; Ok(SubjectConfig { id: row.get(0)?, subject_name: row.get(1)?, display_name: row.get(2)?, description: row.get(3)?, is_enabled: row.get::<_, i32>(4)? != 0, prompts, mistake_types, default_tags, created_at, updated_at, }) } ).optional().map_err(Into::into) } /// 根据科目名称获取科目配置 pub fn get_subject_config_by_name(&self, subject_name: &str) -> Result<Option<SubjectConfig>> { let conn = self.conn.lock().unwrap(); conn.query_row( "SELECT id, subject_name, display_name, description, is_enabled, prompts, mistake_types, default_tags, created_at, updated_at FROM subject_configs WHERE subject_name = ?1", params![subject_name], |row| { let created_at_str: String = row.get(8)?; let updated_at_str: String = row.get(9)?; let prompts_str: String = row.get(5)?; let mistake_types_str: String = row.get(6)?; let default_tags_str: String = row.get(7)?; let created_at = DateTime::parse_from_rfc3339(&created_at_str) .map_err(|_| rusqlite::Error::InvalidColumnType(8, "created_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let updated_at = DateTime::parse_from_rfc3339(&updated_at_str) .map_err(|_| rusqlite::Error::InvalidColumnType(9, "updated_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let prompts: SubjectPrompts = self.parse_subject_prompts(&prompts_str)?; let mistake_types: Vec<String> = serde_json::from_str(&mistake_types_str) .map_err(|_| rusqlite::Error::InvalidColumnType(6, "mistake_types".to_string(), rusqlite::types::Type::Text))?; let default_tags: Vec<String> = serde_json::from_str(&default_tags_str) .map_err(|_| rusqlite::Error::InvalidColumnType(7, "default_tags".to_string(), rusqlite::types::Type::Text))?; Ok(SubjectConfig { id: row.get(0)?, subject_name: row.get(1)?, display_name: row.get(2)?, description: row.get(3)?, is_enabled: row.get::<_, i32>(4)? != 0, prompts, mistake_types, default_tags, created_at, updated_at, }) } ).optional().map_err(Into::into) } /// 获取所有科目配置 pub fn get_all_subject_configs(&self, enabled_only: bool) -> Result<Vec<SubjectConfig>> { let conn = self.conn.lock().unwrap(); let query = if enabled_only { "SELECT id, subject_name, display_name, description, is_enabled, prompts, mistake_types, default_tags, created_at, updated_at FROM subject_configs WHERE is_enabled = 1 ORDER BY display_name" } else { "SELECT id, subject_name, display_name, description, is_enabled, prompts, mistake_types, default_tags, created_at, updated_at FROM subject_configs ORDER BY display_name" }; let mut stmt = conn.prepare(query)?; let mut rows = stmt.query([])?; let mut configs = Vec::new(); while let Some(row) = rows.next()? { let created_at_str: String = row.get(8)?; let updated_at_str: String = row.get(9)?; let prompts_str: String = row.get(5)?; let mistake_types_str: String = row.get(6)?; let default_tags_str: String = row.get(7)?; let created_at = DateTime::parse_from_rfc3339(&created_at_str) .map_err(|e| anyhow::anyhow!("Failed to parse created_at: {}", e))? .with_timezone(&Utc); let updated_at = DateTime::parse_from_rfc3339(&updated_at_str) .map_err(|e| anyhow::anyhow!("Failed to parse updated_at: {}", e))? .with_timezone(&Utc); let prompts: SubjectPrompts = self.parse_subject_prompts(&prompts_str) .map_err(|e| anyhow::anyhow!("Failed to parse prompts JSON: {:?}", e))?; let mistake_types: Vec<String> = serde_json::from_str(&mistake_types_str) .map_err(|e| anyhow::anyhow!("Failed to parse mistake_types JSON: {}", e))?; let default_tags: Vec<String> = serde_json::from_str(&default_tags_str) .map_err(|e| anyhow::anyhow!("Failed to parse default_tags JSON: {}", e))?; let config = SubjectConfig { id: row.get(0)?, subject_name: row.get(1)?, display_name: row.get(2)?, description: row.get(3)?, is_enabled: row.get::<_, i32>(4)? != 0, prompts, mistake_types, default_tags, created_at, updated_at, }; configs.push(config); } Ok(configs) } /// 删除科目配置 pub fn delete_subject_config(&self, id: &str) -> Result<bool> { let conn = self.conn.lock().unwrap(); let changes = conn.execute("DELETE FROM subject_configs WHERE id = ?1", params![id])?; Ok(changes > 0) } /// 初始化默认科目配置 pub fn initialize_default_subject_configs(&self) -> Result<()> { let default_subjects = vec![ ("数学", "Mathematics", "数学错题分析和讲解", self.get_math_prompts()), ("物理", "Physics", "物理概念和计算题目分析", self.get_physics_prompts()), ("化学", "Chemistry", "化学反应和实验题目分析", self.get_chemistry_prompts()), ("英语", "English", "英语语法和阅读理解分析", self.get_english_prompts()), ("语文", "Chinese", "语文阅读理解和写作分析", self.get_chinese_prompts()), ("生物", "Biology", "生物概念和实验题目分析", self.get_biology_prompts()), ("历史", "History", "历史事件和知识点分析", self.get_history_prompts()), ("地理", "Geography", "地理概念和区域分析", self.get_geography_prompts()), ("政治", "Politics", "政治理论和时事分析", self.get_politics_prompts()), ]; for (subject_name, _english_name, description, prompts) in default_subjects { // 检查是否已存在 if self.get_subject_config_by_name(subject_name)?.is_none() { let config = SubjectConfig { id: uuid::Uuid::new_v4().to_string(), subject_name: subject_name.to_string(), display_name: subject_name.to_string(), description: description.to_string(), is_enabled: true, prompts, mistake_types: vec![ "计算错误".to_string(), "概念理解".to_string(), "方法应用".to_string(), "知识遗忘".to_string(), "审题不清".to_string(), ], default_tags: vec![ "基础知识".to_string(), "重点难点".to_string(), "易错点".to_string(), ], created_at: Utc::now(), updated_at: Utc::now(), }; self.save_subject_config(&config)?; } } Ok(()) } // 数学科目的专业提示词 fn get_math_prompts(&self) -> SubjectPrompts { SubjectPrompts { analysis_prompt: "你是一个数学教学专家。请根据提供的{subject}题目信息,详细解答学生的问题。解答要清晰、准确,包含必要的步骤和原理解释。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道错题,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要准确、详细,包含必要的公式推导和计算步骤。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,不要使用LaTeX格式\n2. 数学公式用普通文字描述,如:λ = 2 的几何重数\n3. 矩阵用文字描述,如:矩阵A减去2I等于...\n4. 避免使用\\left、\\begin{array}、\\frac等LaTeX命令\n5. 保持文本简洁易读".to_string(), classification_prompt: "请分析这道{subject}题目的类型(如选择题、填空题、计算题、证明题等),并生成相关的{subject}标签(如代数、几何、函数、导数、概率等)。".to_string(), consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的数学概念或公式。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案、公式或解释,tags字段应包含相关的数学知识点标签如代数、几何、函数等。".to_string(), } } // 物理科目的专业提示词 fn get_physics_prompts(&self) -> SubjectPrompts { SubjectPrompts { analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含物理原理、公式推导和计算过程,注重物理概念的理解。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含相关的物理定律、公式应用和现象解释。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,不要使用LaTeX格式\n2. 物理公式用普通文字描述,如:F等于m乘以a\n3. 物理量用文字描述,如:速度v等于20米每秒\n4. 避免使用\\frac、\\sqrt等LaTeX命令\n5. 保持文本简洁易读".to_string(), classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如力学、电学、光学、热学、原子物理等)。".to_string(), consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的物理原理或定律概念。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的物理知识点标签。".to_string(), } } // 化学科目的专业提示词 fn get_chemistry_prompts(&self) -> SubjectPrompts { SubjectPrompts { analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含化学原理、方程式和计算过程,注重化学反应机理的理解。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含相关的化学反应、化学方程式和实验原理。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,不要使用LaTeX格式\n2. 化学方程式用普通文字描述,如:2H2加O2反应生成2H2O\n3. 分子式用普通文字,如:H2O、NaCl\n4. 避免使用\\rightarrow、\\text等LaTeX命令\n5. 保持文本简洁易读".to_string(), classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如有机化学、无机化学、物理化学、分析化学等)。".to_string(), consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的化学反应或概念。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的化学知识点标签。".to_string(), } } // 英语科目的专业提示词 fn get_english_prompts(&self) -> SubjectPrompts { SubjectPrompts { analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含语法解释、词汇分析和例句说明。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含语法规则、词汇用法和语言表达技巧。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,包括题目、选项、文章等\n2. 保持英文单词和句子的完整性\n3. 注意大小写和标点符号\n4. 保持段落和换行结构\n5. 保持文本简洁易读".to_string(), classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如语法、词汇、阅读理解、写作、听力等)。".to_string(), consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的语法规则或词汇概念。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的英语知识点标签。".to_string(), } } // 语文科目的专业提示词 fn get_chinese_prompts(&self) -> SubjectPrompts { SubjectPrompts { analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含文本分析、语言表达和写作技巧。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含文学理解、语言运用和表达技巧。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,包括文章、诗词、题目等\n2. 保持古诗词的格式和断句\n3. 注意繁体字和异体字的识别\n4. 保持标点符号的准确性\n5. 保持文本简洁易读".to_string(), classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如阅读理解、写作、古诗词、文言文等)。".to_string(), consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的文学知识或语言表达概念。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的语文知识点标签。".to_string(), } } // 生物科目的专业提示词 fn get_biology_prompts(&self) -> SubjectPrompts { SubjectPrompts { analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含生物概念、生理过程和实验原理。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含相关的生物原理、生命过程和实验方法。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,不要使用LaTeX格式\n2. 生物化学公式用普通文字描述,如:葡萄糖C6H12O6\n3. 基因型用普通文字,如:AA、Aa、aa\n4. 避免使用LaTeX命令\n5. 保持文本简洁易读".to_string(), classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如细胞生物学、遗传学、生态学、进化论等)。".to_string(), consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的生物概念或生命过程。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的生物知识点标签。".to_string(), } } // 历史科目的专业提示词 fn get_history_prompts(&self) -> SubjectPrompts { SubjectPrompts { analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含历史背景、事件分析和影响评价。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含历史事件、人物分析和时代背景。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,包括题目、史料、时间等\n2. 注意历史人名和地名的准确性\n3. 保持时间表述的完整性\n4. 注意朝代和年号的正确识别\n5. 保持文本简洁易读".to_string(), classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如古代史、近代史、现代史、政治史、经济史等)。".to_string(), consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的历史事件或人物概念。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的历史知识点标签。".to_string(), } } // 地理科目的专业提示词 fn get_geography_prompts(&self) -> SubjectPrompts { SubjectPrompts { analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含地理概念、空间分析和区域特征。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含地理原理、空间关系和区域分析。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,包括题目、地名、数据等\n2. 注意地名和专业术语的准确性\n3. 保持经纬度、海拔等数据的完整性\n4. 注意图表和统计数据的正确识别\n5. 保持文本简洁易读".to_string(), classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如自然地理、人文地理、区域地理、地图分析等)。".to_string(), consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的地理概念或区域特征。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的地理知识点标签。".to_string(), } } // 政治科目的专业提示词 fn get_politics_prompts(&self) -> SubjectPrompts { SubjectPrompts { analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含政治理论、政策分析和思想原理。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含政治原理、政策解读和思想分析。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,包括题目、理论、政策等\n2. 注意政治术语和概念的准确性\n3. 保持理论表述的完整性\n4. 注意政策名称和法规条文的正确识别\n5. 保持文本简洁易读".to_string(), classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如马克思主义、政治制度、经济政策、哲学原理等)。".to_string(), consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(), anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的政治理论或制度概念。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的政治知识点标签。".to_string(), } } /// 保存模型分配配置 pub fn save_model_assignments(&self, assignments: &crate::models::ModelAssignments) -> Result<()> { let assignments_json = serde_json::to_string(assignments)?; self.save_setting("model_assignments", &assignments_json) } /// 获取模型分配配置 pub fn get_model_assignments(&self) -> Result<Option<crate::models::ModelAssignments>> { match self.get_setting("model_assignments")? { Some(json_str) => { let assignments: crate::models::ModelAssignments = serde_json::from_str(&json_str)?; Ok(Some(assignments)) } None => Ok(None) } } /// 保存API配置列表 pub fn save_api_configs(&self, configs: &[crate::llm_manager::ApiConfig]) -> Result<()> { let configs_json = serde_json::to_string(configs)?; self.save_setting("api_configs", &configs_json) } /// 获取API配置列表 pub fn get_api_configs(&self) -> Result<Vec<crate::llm_manager::ApiConfig>> { match self.get_setting("api_configs")? { Some(json_str) => { let configs: Vec<crate::llm_manager::ApiConfig> = serde_json::from_str(&json_str)?; Ok(configs) } None => Ok(Vec::new()) } } /// 验证错题的JSON字段格式,防止存储损坏的数据 fn validate_mistake_json_fields(&self, mistake: &MistakeItem) -> Result<()> { // 验证question_images能够正确序列化和反序列化 let question_images_json = serde_json::to_string(&mistake.question_images) .map_err(|e| anyhow::Error::new(e).context("序列化question_images失败"))?; serde_json::from_str::<Vec<String>>(&question_images_json) .map_err(|e| anyhow::Error::new(e).context("验证question_images JSON格式失败"))?; // 验证analysis_images能够正确序列化和反序列化 let analysis_images_json = serde_json::to_string(&mistake.analysis_images) .map_err(|e| anyhow::Error::new(e).context("序列化analysis_images失败"))?; serde_json::from_str::<Vec<String>>(&analysis_images_json) .map_err(|e| anyhow::Error::new(e).context("验证analysis_images JSON格式失败"))?; // 验证tags能够正确序列化和反序列化 let tags_json = serde_json::to_string(&mistake.tags) .map_err(|e| anyhow::Error::new(e).context("序列化tags失败"))?; serde_json::from_str::<Vec<String>>(&tags_json) .map_err(|e| anyhow::Error::new(e).context("验证tags JSON格式失败"))?; // 额外验证:检查图片路径的有效性 for (i, path) in mistake.question_images.iter().enumerate() { if path.is_empty() { return Err(anyhow::Error::msg(format!("question_images[{}] 路径为空", i))); } // 基本路径格式检查 if path.contains("..") || path.starts_with('/') { return Err(anyhow::Error::msg(format!("question_images[{}] 路径格式不安全: {}", i, path))); } } for (i, path) in mistake.analysis_images.iter().enumerate() { if path.is_empty() { return Err(anyhow::Error::msg(format!("analysis_images[{}] 路径为空", i))); } // 基本路径格式检查 if path.contains("..") || path.starts_with('/') { return Err(anyhow::Error::msg(format!("analysis_images[{}] 路径格式不安全: {}", i, path))); } } println!("错题JSON字段验证通过: question_images={}, analysis_images={}, tags={}", mistake.question_images.len(), mistake.analysis_images.len(), mistake.tags.len()); Ok(()) } /// 解析科目提示词,自动处理缺失的anki_generation_prompt字段(向后兼容) fn parse_subject_prompts(&self, prompts_str: &str) -> rusqlite::Result<SubjectPrompts> { // 尝试直接解析现有格式 if let Ok(prompts) = serde_json::from_str::<SubjectPrompts>(prompts_str) { return Ok(prompts); } // 如果解析失败,可能是因为缺少新字段,尝试解析为旧格式 #[derive(serde::Deserialize)] struct LegacySubjectPrompts { analysis_prompt: String, review_prompt: String, chat_prompt: String, ocr_prompt: String, classification_prompt: String, consolidated_review_prompt: String, } match serde_json::from_str::<LegacySubjectPrompts>(prompts_str) { Ok(legacy) => { // 转换为新格式,添加默认的anki_generation_prompt Ok(SubjectPrompts { analysis_prompt: legacy.analysis_prompt, review_prompt: legacy.review_prompt, chat_prompt: legacy.chat_prompt, ocr_prompt: legacy.ocr_prompt, classification_prompt: legacy.classification_prompt, consolidated_review_prompt: legacy.consolidated_review_prompt, anki_generation_prompt: "请根据以下学习内容,生成适合制作Anki卡片的问题和答案对。请以JSON数组格式返回结果,每个对象必须包含 front(字符串),back(字符串),tags(字符串数组)三个字段。".to_string(), }) }, Err(_) => { Err(rusqlite::Error::InvalidColumnType(5, "prompts".to_string(), rusqlite::types::Type::Text)) } } } // =================== Anki Enhancement Functions =================== /// 插入文档任务 pub fn insert_document_task(&self, task: &DocumentTask) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute( "INSERT INTO document_tasks (id, document_id, original_document_name, segment_index, content_segment, status, created_at, updated_at, error_message, subject_name, anki_generation_options_json) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", params![ task.id, task.document_id, task.original_document_name, task.segment_index, task.content_segment, task.status.to_db_string(), task.created_at, task.updated_at, task.error_message, task.subject_name, task.anki_generation_options_json ] )?; Ok(()) } /// 更新文档任务状态 pub fn update_document_task_status(&self, task_id: &str, status: TaskStatus, error_message: Option<String>) -> Result<()> { let conn = self.conn.lock().unwrap(); let updated_at = chrono::Utc::now().to_rfc3339(); conn.execute( "UPDATE document_tasks SET status = ?1, error_message = ?2, updated_at = ?3 WHERE id = ?4", params![ status.to_db_string(), error_message, updated_at, task_id ] )?; Ok(()) } /// 获取单个文档任务 pub fn get_document_task(&self, task_id: &str) -> Result<DocumentTask> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT id, document_id, original_document_name, segment_index, content_segment, status, created_at, updated_at, error_message, subject_name, anki_generation_options_json FROM document_tasks WHERE id = ?1" )?; let task = stmt.query_row(params![task_id], |row| { let status_str: String = row.get(5)?; let status: TaskStatus = serde_json::from_str(&status_str) .map_err(|_| rusqlite::Error::InvalidColumnType(5, "status".to_string(), rusqlite::types::Type::Text))?; Ok(DocumentTask { id: row.get(0)?, document_id: row.get(1)?, original_document_name: row.get(2)?, segment_index: row.get(3)?, content_segment: row.get(4)?, status, created_at: row.get(6)?, updated_at: row.get(7)?, error_message: row.get(8)?, subject_name: row.get(9)?, anki_generation_options_json: row.get(10)?, }) })?; Ok(task) } /// 获取指定文档的所有任务 pub fn get_tasks_for_document(&self, document_id: &str) -> Result<Vec<DocumentTask>> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT id, document_id, original_document_name, segment_index, content_segment, status, created_at, updated_at, error_message, subject_name, anki_generation_options_json FROM document_tasks WHERE document_id = ?1 ORDER BY segment_index" )?; let task_iter = stmt.query_map(params![document_id], |row| { let status_str: String = row.get(5)?; let status: TaskStatus = serde_json::from_str(&status_str) .map_err(|_| rusqlite::Error::InvalidColumnType(5, "status".to_string(), rusqlite::types::Type::Text))?; Ok(DocumentTask { id: row.get(0)?, document_id: row.get(1)?, original_document_name: row.get(2)?, segment_index: row.get(3)?, content_segment: row.get(4)?, status, created_at: row.get(6)?, updated_at: row.get(7)?, error_message: row.get(8)?, subject_name: row.get(9)?, anki_generation_options_json: row.get(10)?, }) })?; let mut tasks = Vec::new(); for task in task_iter { tasks.push(task?); } Ok(tasks) } /// 插入Anki卡片 pub fn insert_anki_card(&self, card: &AnkiCard) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute( "INSERT INTO anki_cards (id, task_id, front, back, text, tags_json, images_json, is_error_card, error_content, card_order_in_task, created_at, updated_at, extra_fields_json, template_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)", params![ card.id, card.task_id, card.front, card.back, card.text, serde_json::to_string(&card.tags)?, serde_json::to_string(&card.images)?, if card.is_error_card { 1 } else { 0 }, card.error_content, 0, // card_order_in_task will be calculated card.created_at, card.updated_at, serde_json::to_string(&card.extra_fields)?, card.template_id ] )?; Ok(()) } /// 获取指定任务的所有卡片 pub fn get_cards_for_task(&self, task_id: &str) -> Result<Vec<AnkiCard>> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT id, task_id, front, back, text, tags_json, images_json, is_error_card, error_content, created_at, updated_at, COALESCE(extra_fields_json, '{}') as extra_fields_json, template_id FROM anki_cards WHERE task_id = ?1 ORDER BY card_order_in_task, created_at" )?; let card_iter = stmt.query_map(params![task_id], |row| { let tags_json: String = row.get(5)?; let tags: Vec<String> = serde_json::from_str(&tags_json).unwrap_or_default(); let images_json: String = row.get(6)?; let images: Vec<String> = serde_json::from_str(&images_json).unwrap_or_default(); let extra_fields_json: String = row.get(11)?; let extra_fields: std::collections::HashMap<String, String> = serde_json::from_str(&extra_fields_json).unwrap_or_default(); Ok(AnkiCard { id: row.get(0)?, task_id: row.get(1)?, front: row.get(2)?, back: row.get(3)?, text: row.get(4)?, tags, images, is_error_card: row.get::<_, i32>(7)? != 0, error_content: row.get(8)?, created_at: row.get(9)?, updated_at: row.get(10)?, extra_fields, template_id: row.get(12)?, }) })?; let mut cards = Vec::new(); for card in card_iter { cards.push(card?); } Ok(cards) } /// 获取指定文档的所有卡片 pub fn get_cards_for_document(&self, document_id: &str) -> Result<Vec<AnkiCard>> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT ac.id, ac.task_id, ac.front, ac.back, ac.text, ac.tags_json, ac.images_json, ac.is_error_card, ac.error_content, ac.created_at, ac.updated_at, COALESCE(ac.extra_fields_json, '{}') as extra_fields_json, ac.template_id FROM anki_cards ac JOIN document_tasks dt ON ac.task_id = dt.id WHERE dt.document_id = ?1 ORDER BY dt.segment_index, ac.card_order_in_task, ac.created_at" )?; let card_iter = stmt.query_map(params![document_id], |row| { let tags_json: String = row.get(5)?; let tags: Vec<String> = serde_json::from_str(&tags_json).unwrap_or_default(); let images_json: String = row.get(6)?; let images: Vec<String> = serde_json::from_str(&images_json).unwrap_or_default(); let extra_fields_json: String = row.get(11)?; let extra_fields: std::collections::HashMap<String, String> = serde_json::from_str(&extra_fields_json).unwrap_or_default(); Ok(AnkiCard { id: row.get(0)?, task_id: row.get(1)?, front: row.get(2)?, back: row.get(3)?, text: row.get(4)?, tags, images, is_error_card: row.get::<_, i32>(7)? != 0, error_content: row.get(8)?, created_at: row.get(9)?, updated_at: row.get(10)?, extra_fields, template_id: row.get(12)?, }) })?; let mut cards = Vec::new(); for card in card_iter { cards.push(card?); } Ok(cards) } /// 根据ID列表获取卡片 pub fn get_cards_by_ids(&self, card_ids: &[String]) -> Result<Vec<AnkiCard>> { if card_ids.is_empty() { return Ok(Vec::new()); } let conn = self.conn.lock().unwrap(); let placeholders: Vec<&str> = card_ids.iter().map(|_| "?").collect(); let sql = format!( "SELECT id, task_id, front, back, text, tags_json, images_json, is_error_card, error_content, created_at, updated_at, COALESCE(extra_fields_json, '{{}}') as extra_fields_json, template_id FROM anki_cards WHERE id IN ({}) ORDER BY created_at", placeholders.join(",") ); let mut stmt = conn.prepare(&sql)?; let card_iter = stmt.query_map(rusqlite::params_from_iter(card_ids), |row| { let tags_json: String = row.get(5)?; let tags: Vec<String> = serde_json::from_str(&tags_json).unwrap_or_default(); let images_json: String = row.get(6)?; let images: Vec<String> = serde_json::from_str(&images_json).unwrap_or_default(); let extra_fields_json: String = row.get(11)?; let extra_fields: std::collections::HashMap<String, String> = serde_json::from_str(&extra_fields_json).unwrap_or_default(); Ok(AnkiCard { id: row.get(0)?, task_id: row.get(1)?, front: row.get(2)?, back: row.get(3)?, text: row.get(4)?, tags, images, is_error_card: row.get::<_, i32>(7)? != 0, error_content: row.get(8)?, created_at: row.get(9)?, updated_at: row.get(10)?, extra_fields, template_id: row.get(12)?, }) })?; let mut cards = Vec::new(); for card in card_iter { cards.push(card?); } Ok(cards) } /// 更新Anki卡片 pub fn update_anki_card(&self, card: &AnkiCard) -> Result<()> { let conn = self.conn.lock().unwrap(); let updated_at = chrono::Utc::now().to_rfc3339(); conn.execute( "UPDATE anki_cards SET front = ?1, back = ?2, tags_json = ?3, images_json = ?4, is_error_card = ?5, error_content = ?6, updated_at = ?7 WHERE id = ?8", params![ card.front, card.back, serde_json::to_string(&card.tags)?, serde_json::to_string(&card.images)?, if card.is_error_card { 1 } else { 0 }, card.error_content, updated_at, card.id ] )?; Ok(()) } /// 删除Anki卡片 pub fn delete_anki_card(&self, card_id: &str) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute("DELETE FROM anki_cards WHERE id = ?1", params![card_id])?; Ok(()) } /// 删除文档任务及其所有卡片 pub fn delete_document_task(&self, task_id: &str) -> Result<()> { let conn = self.conn.lock().unwrap(); // 由于设置了ON DELETE CASCADE,删除任务会自动删除关联的卡片 conn.execute("DELETE FROM document_tasks WHERE id = ?1", params![task_id])?; Ok(()) } /// 删除整个文档会话(所有任务和卡片) pub fn delete_document_session(&self, document_id: &str) -> Result<()> { let conn = self.conn.lock().unwrap(); // 由于设置了ON DELETE CASCADE,删除任务会自动删除关联的卡片 conn.execute("DELETE FROM document_tasks WHERE document_id = ?1", params![document_id])?; Ok(()) } // ==================== RAG配置管理 ==================== /// 获取RAG配置 pub fn get_rag_configuration(&self) -> Result<Option<crate::models::RagConfiguration>> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT id, chunk_size, chunk_overlap, chunking_strategy, min_chunk_size, default_top_k, default_rerank_enabled, created_at, updated_at FROM rag_configurations WHERE id = 'default'" )?; let result = stmt.query_row([], |row| { let created_at_str: String = row.get(7)?; let updated_at_str: String = row.get(8)?; let created_at = DateTime::parse_from_rfc3339(&created_at_str) .map_err(|_| rusqlite::Error::InvalidColumnType(7, "created_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let updated_at = DateTime::parse_from_rfc3339(&updated_at_str) .map_err(|_| rusqlite::Error::InvalidColumnType(8, "updated_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); Ok(crate::models::RagConfiguration { id: row.get(0)?, chunk_size: row.get(1)?, chunk_overlap: row.get(2)?, chunking_strategy: row.get(3)?, min_chunk_size: row.get(4)?, default_top_k: row.get(5)?, default_rerank_enabled: row.get::<_, i32>(6)? != 0, created_at, updated_at, }) }).optional()?; Ok(result) } /// 更新RAG配置 pub fn update_rag_configuration(&self, config: &crate::models::RagConfigRequest) -> Result<()> { let conn = self.conn.lock().unwrap(); let now = Utc::now().to_rfc3339(); conn.execute( "UPDATE rag_configurations SET chunk_size = ?1, chunk_overlap = ?2, chunking_strategy = ?3, min_chunk_size = ?4, default_top_k = ?5, default_rerank_enabled = ?6, updated_at = ?7 WHERE id = 'default'", params![ config.chunk_size, config.chunk_overlap, config.chunking_strategy, config.min_chunk_size, config.default_top_k, if config.default_rerank_enabled { 1 } else { 0 }, now ], )?; Ok(()) } /// 重置RAG配置为默认值 pub fn reset_rag_configuration(&self) -> Result<()> { let conn = self.conn.lock().unwrap(); let now = Utc::now().to_rfc3339(); conn.execute( "UPDATE rag_configurations SET chunk_size = 512, chunk_overlap = 50, chunking_strategy = 'fixed_size', min_chunk_size = 20, default_top_k = 5, default_rerank_enabled = 0, updated_at = ?1 WHERE id = 'default'", params![now], )?; Ok(()) } // ==================== RAG分库管理CRUD操作 ==================== /// 创建新的分库 pub fn create_sub_library(&self, request: &CreateSubLibraryRequest) -> Result<SubLibrary> { let conn = self.conn.lock().unwrap(); let id = uuid::Uuid::new_v4().to_string(); let now = Utc::now(); let now_str = now.to_rfc3339(); // 检查名称是否已存在 let exists: bool = conn.query_row( "SELECT EXISTS(SELECT 1 FROM rag_sub_libraries WHERE name = ?1)", params![request.name], |row| row.get(0) )?; if exists { return Err(anyhow::anyhow!("分库名称 '{}' 已存在", request.name)); } conn.execute( "INSERT INTO rag_sub_libraries (id, name, description, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5)", params![id, request.name, request.description, now_str, now_str], )?; Ok(SubLibrary { id, name: request.name.clone(), description: request.description.clone(), created_at: now, updated_at: now, document_count: 0, chunk_count: 0, }) } /// 获取所有分库列表 pub fn list_sub_libraries(&self) -> Result<Vec<SubLibrary>> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT sl.id, sl.name, sl.description, sl.created_at, sl.updated_at, COUNT(DISTINCT rd.id) as document_count, COUNT(DISTINCT rdc.id) as chunk_count FROM rag_sub_libraries sl LEFT JOIN rag_documents rd ON sl.id = rd.sub_library_id LEFT JOIN rag_document_chunks rdc ON rd.id = rdc.document_id GROUP BY sl.id, sl.name, sl.description, sl.created_at, sl.updated_at ORDER BY sl.name" )?; let library_iter = stmt.query_map([], |row| { let created_at = DateTime::parse_from_rfc3339(&row.get::<_, String>(3)?) .map_err(|_| rusqlite::Error::InvalidColumnType(3, "created_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let updated_at = DateTime::parse_from_rfc3339(&row.get::<_, String>(4)?) .map_err(|_| rusqlite::Error::InvalidColumnType(4, "updated_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); Ok(SubLibrary { id: row.get(0)?, name: row.get(1)?, description: row.get(2)?, created_at, updated_at, document_count: row.get::<_, i64>(5)? as usize, chunk_count: row.get::<_, i64>(6)? as usize, }) })?; let mut libraries = Vec::new(); for library in library_iter { libraries.push(library?); } Ok(libraries) } /// 根据ID获取分库详情 pub fn get_sub_library_by_id(&self, id: &str) -> Result<Option<SubLibrary>> { let conn = self.conn.lock().unwrap(); let result = conn.query_row( "SELECT sl.id, sl.name, sl.description, sl.created_at, sl.updated_at, COUNT(DISTINCT rd.id) as document_count, COUNT(DISTINCT rdc.id) as chunk_count FROM rag_sub_libraries sl LEFT JOIN rag_documents rd ON sl.id = rd.sub_library_id LEFT JOIN rag_document_chunks rdc ON rd.id = rdc.document_id WHERE sl.id = ?1 GROUP BY sl.id, sl.name, sl.description, sl.created_at, sl.updated_at", params![id], |row| { let created_at = DateTime::parse_from_rfc3339(&row.get::<_, String>(3)?) .map_err(|_| rusqlite::Error::InvalidColumnType(3, "created_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let updated_at = DateTime::parse_from_rfc3339(&row.get::<_, String>(4)?) .map_err(|_| rusqlite::Error::InvalidColumnType(4, "updated_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); Ok(SubLibrary { id: row.get(0)?, name: row.get(1)?, description: row.get(2)?, created_at, updated_at, document_count: row.get::<_, i64>(5)? as usize, chunk_count: row.get::<_, i64>(6)? as usize, }) } ).optional()?; Ok(result) } /// 根据名称获取分库详情 pub fn get_sub_library_by_name(&self, name: &str) -> Result<Option<SubLibrary>> { let conn = self.conn.lock().unwrap(); let result = conn.query_row( "SELECT sl.id, sl.name, sl.description, sl.created_at, sl.updated_at, COUNT(DISTINCT rd.id) as document_count, COUNT(DISTINCT rdc.id) as chunk_count FROM rag_sub_libraries sl LEFT JOIN rag_documents rd ON sl.id = rd.sub_library_id LEFT JOIN rag_document_chunks rdc ON rd.id = rdc.document_id WHERE sl.name = ?1 GROUP BY sl.id, sl.name, sl.description, sl.created_at, sl.updated_at", params![name], |row| { let created_at = DateTime::parse_from_rfc3339(&row.get::<_, String>(3)?) .map_err(|_| rusqlite::Error::InvalidColumnType(3, "created_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); let updated_at = DateTime::parse_from_rfc3339(&row.get::<_, String>(4)?) .map_err(|_| rusqlite::Error::InvalidColumnType(4, "updated_at".to_string(), rusqlite::types::Type::Text))? .with_timezone(&Utc); Ok(SubLibrary { id: row.get(0)?, name: row.get(1)?, description: row.get(2)?, created_at, updated_at, document_count: row.get::<_, i64>(5)? as usize, chunk_count: row.get::<_, i64>(6)? as usize, }) } ).optional()?; Ok(result) } /// 更新分库信息 pub fn update_sub_library(&self, id: &str, request: &UpdateSubLibraryRequest) -> Result<SubLibrary> { let conn = self.conn.lock().unwrap(); let now = Utc::now().to_rfc3339(); // 检查分库是否存在 let exists: bool = conn.query_row( "SELECT EXISTS(SELECT 1 FROM rag_sub_libraries WHERE id = ?1)", params![id], |row| row.get(0) )?; if !exists { return Err(anyhow::anyhow!("分库ID '{}' 不存在", id)); } // 如果更新名称,检查新名称是否已存在 if let Some(new_name) = &request.name { let name_exists: bool = conn.query_row( "SELECT EXISTS(SELECT 1 FROM rag_sub_libraries WHERE name = ?1 AND id != ?2)", params![new_name, id], |row| row.get(0) )?; if name_exists { return Err(anyhow::anyhow!("分库名称 '{}' 已存在", new_name)); } } // 构建动态更新SQL let mut updates = Vec::new(); let mut params_vec = Vec::new(); if let Some(name) = &request.name { updates.push("name = ?"); params_vec.push(name.as_str()); } if let Some(description) = &request.description { updates.push("description = ?"); params_vec.push(description.as_str()); } updates.push("updated_at = ?"); params_vec.push(&now); params_vec.push(id); let sql = format!( "UPDATE rag_sub_libraries SET {} WHERE id = ?", updates.join(", ") ); conn.execute(&sql, rusqlite::params_from_iter(params_vec))?; // 释放锁,避免递归锁导致死锁 drop(conn); // 使用单独的只读查询获取更新后的分库信息 self.get_sub_library_by_id(id)? .ok_or_else(|| anyhow::anyhow!("无法获取更新后的分库信息")) } /// 删除分库 pub fn delete_sub_library(&self, id: &str, delete_contained_documents: bool) -> Result<()> { let conn = self.conn.lock().unwrap(); // 检查是否为默认分库 if id == "default" { return Err(anyhow::anyhow!("不能删除默认分库")); } // 检查分库是否存在 let exists: bool = conn.query_row( "SELECT EXISTS(SELECT 1 FROM rag_sub_libraries WHERE id = ?1)", params![id], |row| row.get(0) )?; if !exists { return Err(anyhow::anyhow!("分库ID '{}' 不存在", id)); } let transaction = conn.unchecked_transaction()?; if delete_contained_documents { // 删除分库中的所有文档及其相关数据 // 首先获取分库中的所有文档ID let mut stmt = transaction.prepare( "SELECT id FROM rag_documents WHERE sub_library_id = ?1" )?; let document_ids: Vec<String> = stmt.query_map(params![id], |row| { Ok(row.get::<_, String>(0)?) })?.collect::<Result<Vec<_>, _>>()?; // 删除文档关联的向量和块 for doc_id in document_ids { transaction.execute( "DELETE FROM rag_document_chunks WHERE document_id = ?1", params![doc_id], )?; } // 删除分库中的所有文档 transaction.execute( "DELETE FROM rag_documents WHERE sub_library_id = ?1", params![id], )?; } else { // 将分库中的文档移动到默认分库 transaction.execute( "UPDATE rag_documents SET sub_library_id = 'default' WHERE sub_library_id = ?1", params![id], )?; } // 删除分库本身 transaction.execute( "DELETE FROM rag_sub_libraries WHERE id = ?1", params![id], )?; transaction.commit()?; println!("✅ 成功删除分库: {}", id); Ok(()) } /// 获取指定分库中的文档列表 pub fn get_documents_by_sub_library(&self, sub_library_id: &str, page: Option<usize>, page_size: Option<usize>) -> Result<Vec<serde_json::Value>> { let conn = self.conn.lock().unwrap(); let page = page.unwrap_or(1); let page_size = page_size.unwrap_or(50); let offset = (page - 1) * page_size; let mut stmt = conn.prepare( "SELECT id, file_name, file_path, file_size, total_chunks, sub_library_id, created_at, updated_at FROM rag_documents WHERE sub_library_id = ?1 ORDER BY created_at DESC LIMIT ?2 OFFSET ?3" )?; let rows = stmt.query_map(params![sub_library_id, page_size, offset], |row| { Ok(serde_json::json!({ "id": row.get::<_, String>(0)?, "file_name": row.get::<_, String>(1)?, "file_path": row.get::<_, Option<String>>(2)?, "file_size": row.get::<_, Option<i64>>(3)?, "total_chunks": row.get::<_, i32>(4)?, "sub_library_id": row.get::<_, String>(5)?, "created_at": row.get::<_, String>(6)?, "updated_at": row.get::<_, String>(7)? })) })?; let mut documents = Vec::new(); for row in rows { documents.push(row?); } Ok(documents) } /// 将文档移动到指定分库 pub fn move_document_to_sub_library(&self, document_id: &str, target_sub_library_id: &str) -> Result<()> { let conn = self.conn.lock().unwrap(); // 检查目标分库是否存在 let library_exists: bool = conn.query_row( "SELECT EXISTS(SELECT 1 FROM rag_sub_libraries WHERE id = ?1)", params![target_sub_library_id], |row| row.get(0) )?; if !library_exists { return Err(anyhow::anyhow!("目标分库ID '{}' 不存在", target_sub_library_id)); } // 检查文档是否存在 let document_exists: bool = conn.query_row( "SELECT EXISTS(SELECT 1 FROM rag_documents WHERE id = ?1)", params![document_id], |row| row.get(0) )?; if !document_exists { return Err(anyhow::anyhow!("文档ID '{}' 不存在", document_id)); } // 更新文档的分库归属 let updated_at = Utc::now().to_rfc3339(); conn.execute( "UPDATE rag_documents SET sub_library_id = ?1, updated_at = ?2 WHERE id = ?3", params![target_sub_library_id, updated_at, document_id], )?; println!("✅ 成功将文档 {} 移动到分库 {}", document_id, target_sub_library_id); Ok(()) } // =================== Migration Functions =================== /// 版本8到版本9的数据库迁移:添加图片遮罩卡表 fn migrate_v8_to_v9(&self, conn: &rusqlite::Connection) -> Result<()> { println!("正在迁移数据库版本8到版本9:添加图片遮罩卡支持..."); conn.execute_batch( "CREATE TABLE IF NOT EXISTS image_occlusion_cards ( id TEXT PRIMARY KEY, task_id TEXT NOT NULL, image_path TEXT NOT NULL, image_base64 TEXT, image_width INTEGER NOT NULL, image_height INTEGER NOT NULL, masks_json TEXT NOT NULL, -- JSON格式存储遮罩数组 title TEXT NOT NULL, description TEXT, tags_json TEXT NOT NULL DEFAULT '[]', -- JSON格式存储标签数组 subject TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) ); CREATE INDEX IF NOT EXISTS idx_image_occlusion_cards_task_id ON image_occlusion_cards(task_id); CREATE INDEX IF NOT EXISTS idx_image_occlusion_cards_subject ON image_occlusion_cards(subject); CREATE INDEX IF NOT EXISTS idx_image_occlusion_cards_created_at ON image_occlusion_cards(created_at);" )?; println!("✅ 数据库版本8到版本9迁移完成"); Ok(()) } fn migrate_v9_to_v10(&self, conn: &rusqlite::Connection) -> Result<()> { println!("正在迁移数据库版本9到版本10:为anki_cards表添加text字段支持Cloze模板..."); // 添加text字段到anki_cards表 conn.execute( "ALTER TABLE anki_cards ADD COLUMN text TEXT;", [], )?; // 添加索引以优化查询性能 conn.execute( "CREATE INDEX IF NOT EXISTS idx_anki_cards_text ON anki_cards(text);", [], )?; println!("✅ 数据库版本9到版本10迁移完成"); Ok(()) } // =================== Image Occlusion Functions =================== /// 保存图片遮罩卡到数据库 pub fn save_image_occlusion_card(&self, card: &crate::models::ImageOcclusionCard) -> Result<()> { let conn = self.conn.lock().unwrap(); let masks_json = serde_json::to_string(&card.masks) .map_err(|e| anyhow::anyhow!("序列化遮罩数据失败: {}", e))?; let tags_json = serde_json::to_string(&card.tags) .map_err(|e| anyhow::anyhow!("序列化标签数据失败: {}", e))?; conn.execute( "INSERT INTO image_occlusion_cards (id, task_id, image_path, image_base64, image_width, image_height, masks_json, title, description, tags_json, subject, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)", params![ card.id, card.task_id, card.image_path, card.image_base64, card.image_width, card.image_height, masks_json, card.title, card.description, tags_json, card.subject, card.created_at, card.updated_at ] )?; Ok(()) } /// 获取所有图片遮罩卡 pub fn get_all_image_occlusion_cards(&self) -> Result<Vec<crate::models::ImageOcclusionCard>> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT id, task_id, image_path, image_base64, image_width, image_height, masks_json, title, description, tags_json, subject, created_at, updated_at FROM image_occlusion_cards ORDER BY created_at DESC" )?; let card_iter = stmt.query_map([], |row| { let masks_json: String = row.get(6)?; let tags_json: String = row.get(9)?; let masks: Vec<crate::models::OcclusionMask> = serde_json::from_str(&masks_json) .map_err(|e| rusqlite::Error::InvalidColumnType(6, format!("masks_json: {}", e), rusqlite::types::Type::Text))?; let tags: Vec<String> = serde_json::from_str(&tags_json) .map_err(|e| rusqlite::Error::InvalidColumnType(9, format!("tags_json: {}", e), rusqlite::types::Type::Text))?; Ok(crate::models::ImageOcclusionCard { id: row.get(0)?, task_id: row.get(1)?, image_path: row.get(2)?, image_base64: row.get(3)?, image_width: row.get(4)?, image_height: row.get(5)?, masks, title: row.get(7)?, description: row.get(8)?, tags, subject: row.get(10)?, created_at: row.get(11)?, updated_at: row.get(12)?, }) })?; let mut cards = Vec::new(); for card_result in card_iter { cards.push(card_result?); } Ok(cards) } /// 根据ID获取图片遮罩卡 pub fn get_image_occlusion_card_by_id(&self, card_id: &str) -> Result<Option<crate::models::ImageOcclusionCard>> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT id, task_id, image_path, image_base64, image_width, image_height, masks_json, title, description, tags_json, subject, created_at, updated_at FROM image_occlusion_cards WHERE id = ?1" )?; let card = stmt.query_row(params![card_id], |row| { let masks_json: String = row.get(6)?; let tags_json: String = row.get(9)?; let masks: Vec<crate::models::OcclusionMask> = serde_json::from_str(&masks_json) .map_err(|e| rusqlite::Error::InvalidColumnType(6, format!("masks_json: {}", e), rusqlite::types::Type::Text))?; let tags: Vec<String> = serde_json::from_str(&tags_json) .map_err(|e| rusqlite::Error::InvalidColumnType(9, format!("tags_json: {}", e), rusqlite::types::Type::Text))?; Ok(crate::models::ImageOcclusionCard { id: row.get(0)?, task_id: row.get(1)?, image_path: row.get(2)?, image_base64: row.get(3)?, image_width: row.get(4)?, image_height: row.get(5)?, masks, title: row.get(7)?, description: row.get(8)?, tags, subject: row.get(10)?, created_at: row.get(11)?, updated_at: row.get(12)?, }) }).optional()?; Ok(card) } /// 更新图片遮罩卡 pub fn update_image_occlusion_card(&self, card: &crate::models::ImageOcclusionCard) -> Result<()> { let conn = self.conn.lock().unwrap(); let masks_json = serde_json::to_string(&card.masks) .map_err(|e| anyhow::anyhow!("序列化遮罩数据失败: {}", e))?; let tags_json = serde_json::to_string(&card.tags) .map_err(|e| anyhow::anyhow!("序列化标签数据失败: {}", e))?; conn.execute( "UPDATE image_occlusion_cards SET task_id = ?2, image_path = ?3, image_base64 = ?4, image_width = ?5, image_height = ?6, masks_json = ?7, title = ?8, description = ?9, tags_json = ?10, subject = ?11, updated_at = ?12 WHERE id = ?1", params![ card.id, card.task_id, card.image_path, card.image_base64, card.image_width, card.image_height, masks_json, card.title, card.description, tags_json, card.subject, card.updated_at ] )?; Ok(()) } /// 删除图片遮罩卡 pub fn delete_image_occlusion_card(&self, card_id: &str) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute( "DELETE FROM image_occlusion_cards WHERE id = ?1", params![card_id] )?; Ok(()) } /// 设置默认模板ID pub fn set_default_template(&self, template_id: &str) -> Result<()> { let conn = self.conn.lock().unwrap(); let now = Utc::now().to_rfc3339(); conn.execute( "INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES ('default_template_id', ?1, ?2)", params![template_id, now] )?; Ok(()) } /// 获取默认模板ID pub fn get_default_template(&self) -> Result<Option<String>> { let conn = self.conn.lock().unwrap(); match conn.query_row( "SELECT value FROM settings WHERE key = 'default_template_id'", [], |row| row.get::<_, String>(0) ) { Ok(template_id) => Ok(Some(template_id)), Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None), Err(e) => Err(e.into()), } } }
145,648
database
rs
en
rust
code
{"qsc_code_num_words": 16079, "qsc_code_num_chars": 145648.0, "qsc_code_mean_word_length": 4.77473723, "qsc_code_frac_words_unique": 0.0641209, "qsc_code_frac_chars_top_2grams": 0.02321129, "qsc_code_frac_chars_top_3grams": 0.01862634, "qsc_code_frac_chars_top_4grams": 0.01187918, "qsc_code_frac_chars_dupe_5grams": 0.72528102, "qsc_code_frac_chars_dupe_6grams": 0.68938299, "qsc_code_frac_chars_dupe_7grams": 0.66339729, "qsc_code_frac_chars_dupe_8grams": 0.6385969, "qsc_code_frac_chars_dupe_9grams": 0.61181665, "qsc_code_frac_chars_dupe_10grams": 0.59177054, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0148575, "qsc_code_frac_chars_whitespace": 0.31006262, "qsc_code_size_file_byte": 145648.0, "qsc_code_num_lines": 3067.0, "qsc_code_num_chars_line_max": 550.0, "qsc_code_num_chars_line_mean": 47.48875122, "qsc_code_frac_chars_alphabet": 0.74868641, "qsc_code_frac_chars_comments": 0.02861007, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.51862235, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.04004806, "qsc_code_frac_chars_string_length": 0.21105307, "qsc_code_frac_chars_long_word_length": 0.09272623, "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.00032605, "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/anki_connect_service.rs
use serde::{Deserialize, Serialize}; use std::collections::HashMap; use crate::models::AnkiCard; use std::net::TcpStream; use std::time::Duration; const ANKI_CONNECT_URL: &str = "http://127.0.0.1:8765"; #[derive(Serialize)] struct AnkiConnectRequest { action: String, version: u32, #[serde(skip_serializing_if = "Option::is_none")] params: Option<serde_json::Value>, } #[derive(Deserialize)] struct AnkiConnectResponse { result: Option<serde_json::Value>, error: Option<String>, } #[derive(Serialize)] struct Note { #[serde(rename = "deckName")] deck_name: String, #[serde(rename = "modelName")] model_name: String, fields: HashMap<String, String>, tags: Vec<String>, } /// 检查AnkiConnect是否可用 pub async fn check_anki_connect_availability() -> Result<bool, String> { println!("🔍 正在检查AnkiConnect连接到: {}", ANKI_CONNECT_URL); // 首先检查端口8765是否开放 println!("🔍 第0步:检查端口8765是否开放..."); match TcpStream::connect_timeout(&"127.0.0.1:8765".parse().unwrap(), Duration::from_secs(5)) { Ok(_) => { println!("✅ 端口8765可访问"); } Err(e) => { println!("❌ 端口8765无法访问: {}", e); return Err(format!("端口8765无法访问: {} \n\n这通常意味着:\n1. Anki桌面程序未运行\n2. AnkiConnect插件未安装或未启用\n3. 端口被其他程序占用\n\n解决方法:\n1. 启动Anki桌面程序\n2. 安装AnkiConnect插件(代码:2055492159)\n3. 重启Anki以激活插件", e)); } } // 首先尝试简单的GET请求检查服务是否运行 let client = reqwest::Client::builder() .timeout(std::time::Duration::from_secs(10)) .tcp_keepalive(Some(std::time::Duration::from_secs(30))) .connect_timeout(std::time::Duration::from_secs(5)) .build() .map_err(|e| format!("创建HTTP客户端失败: {}", e))?; println!("🔍 第一步:检查AnkiConnect服务是否响应..."); match client.get(ANKI_CONNECT_URL).send().await { Ok(response) => { println!("✅ AnkiConnect服务响应状态: {}", response.status()); let text = response.text().await.unwrap_or_else(|_| "无法读取响应".to_string()); println!("📥 服务响应内容: {}", text); // 检查响应内容是否包含AnkiConnect信息 if text.contains("AnkiConnect") || text.contains("apiVersion") { println!("✅ AnkiConnect服务确认运行正常"); } else { println!("⚠️ 服务响应异常,内容: {}", text); } } Err(e) => { println!("❌ AnkiConnect服务无响应: {}", e); return Err(format!("AnkiConnect服务未运行或无法访问: {} \n\n请确保:\n1. Anki桌面程序正在运行\n2. AnkiConnect插件已安装(代码:2055492159)\n3. 重启Anki以激活插件\n4. 检查端口8765是否被占用", e)); } } // 如果基础连接成功,再尝试API请求 println!("🔍 第二步:测试AnkiConnect API..."); let request = AnkiConnectRequest { action: "version".to_string(), version: 6, params: None, }; println!("📤 发送API请求: {}", serde_json::to_string(&request).unwrap_or_else(|_| "序列化失败".to_string())); match client .post(ANKI_CONNECT_URL) .header("Content-Type", "application/json") .header("Accept", "application/json") .header("User-Agent", "ai-mistake-manager/1.0") .json(&request) .timeout(std::time::Duration::from_secs(15)) .send() .await { Ok(response) => { let status_code = response.status(); println!("📥 收到响应状态: {}", status_code); if status_code.is_success() { let response_text = response.text().await .map_err(|e| format!("读取响应内容失败: {}", e))?; println!("📥 响应内容: {}", response_text); match serde_json::from_str::<AnkiConnectResponse>(&response_text) { Ok(anki_response) => { if anki_response.error.is_none() { println!("✅ AnkiConnect版本检查成功"); Ok(true) } else { Err(format!("AnkiConnect错误: {}", anki_response.error.unwrap_or_default())) } } Err(e) => Err(format!("解析AnkiConnect响应失败: {} - 响应内容: {}", e, response_text)), } } else { let error_text = response.text().await.unwrap_or_else(|_| "无法读取错误内容".to_string()); Err(format!("AnkiConnect HTTP错误: {} - 内容: {}", status_code, error_text)) } } Err(e) => { println!("❌ AnkiConnect连接错误详情: {:?}", e); if e.is_timeout() { Err("AnkiConnect连接超时(5秒),请确保Anki桌面程序正在运行并启用了AnkiConnect插件".to_string()) } else if e.is_connect() { Err("无法连接到AnkiConnect服务器,请确保:1)Anki正在运行 2)AnkiConnect插件已安装并启用 3)端口8765未被占用".to_string()) } else if e.to_string().contains("connection closed") { Err("连接被AnkiConnect服务器关闭,可能原因:1)AnkiConnect版本过旧 2)请求格式不兼容 3)需要重启Anki".to_string()) } else { Err(format!("AnkiConnect连接失败: {}", e)) } } } } /// 获取所有牌组名称 pub async fn get_deck_names() -> Result<Vec<String>, String> { let request = AnkiConnectRequest { action: "deckNames".to_string(), version: 6, params: None, }; let client = reqwest::Client::new(); match client .post(ANKI_CONNECT_URL) .json(&request) .timeout(std::time::Duration::from_secs(5)) .send() .await { Ok(response) => { if response.status().is_success() { match response.json::<AnkiConnectResponse>().await { Ok(anki_response) => { if let Some(error) = anki_response.error { Err(format!("AnkiConnect错误: {}", error)) } else if let Some(result) = anki_response.result { match serde_json::from_value::<Vec<String>>(result) { Ok(deck_names) => Ok(deck_names), Err(e) => Err(format!("解析牌组列表失败: {}", e)), } } else { Err("AnkiConnect返回空结果".to_string()) } } Err(e) => Err(format!("解析AnkiConnect响应失败: {}", e)), } } else { Err(format!("AnkiConnect HTTP错误: {}", response.status())) } } Err(e) => Err(format!("请求牌组列表失败: {}", e)), } } /// 获取所有笔记类型名称 pub async fn get_model_names() -> Result<Vec<String>, String> { let request = AnkiConnectRequest { action: "modelNames".to_string(), version: 6, params: None, }; let client = reqwest::Client::new(); match client .post(ANKI_CONNECT_URL) .json(&request) .timeout(std::time::Duration::from_secs(5)) .send() .await { Ok(response) => { if response.status().is_success() { match response.json::<AnkiConnectResponse>().await { Ok(anki_response) => { if let Some(error) = anki_response.error { Err(format!("AnkiConnect错误: {}", error)) } else if let Some(result) = anki_response.result { match serde_json::from_value::<Vec<String>>(result) { Ok(model_names) => Ok(model_names), Err(e) => Err(format!("解析笔记类型列表失败: {}", e)), } } else { Err("AnkiConnect返回空结果".to_string()) } } Err(e) => Err(format!("解析AnkiConnect响应失败: {}", e)), } } else { Err(format!("AnkiConnect HTTP错误: {}", response.status())) } } Err(e) => Err(format!("请求笔记类型列表失败: {}", e)), } } /// 将AnkiCard列表添加到Anki pub async fn add_notes_to_anki( cards: Vec<AnkiCard>, deck_name: String, note_type: String, ) -> Result<Vec<Option<u64>>, String> { // 首先检查AnkiConnect可用性 check_anki_connect_availability().await?; // 构建notes数组 let notes: Vec<Note> = cards .into_iter() .map(|card| { let mut fields = HashMap::new(); // 根据笔记类型决定字段映射 match note_type.as_str() { "Basic" => { fields.insert("Front".to_string(), card.front); fields.insert("Back".to_string(), card.back); } "Basic (and reversed card)" => { fields.insert("Front".to_string(), card.front); fields.insert("Back".to_string(), card.back); } "Basic (optional reversed card)" => { fields.insert("Front".to_string(), card.front); fields.insert("Back".to_string(), card.back); } "Cloze" => { // 对于Cloze类型,需要将front和back合并 let cloze_text = if card.back.is_empty() { card.front } else { format!("{}\n\n{}", card.front, card.back) }; fields.insert("Text".to_string(), cloze_text); } _ => { // 对于其他类型,尝试使用Front/Back字段,如果失败则使用第一个和第二个字段 fields.insert("Front".to_string(), card.front); fields.insert("Back".to_string(), card.back); } } Note { deck_name: deck_name.clone(), model_name: note_type.clone(), fields, tags: card.tags, } }) .collect(); let params = serde_json::json!({ "notes": notes }); let request = AnkiConnectRequest { action: "addNotes".to_string(), version: 6, params: Some(params), }; let client = reqwest::Client::new(); match client .post(ANKI_CONNECT_URL) .json(&request) .timeout(std::time::Duration::from_secs(30)) .send() .await { Ok(response) => { if response.status().is_success() { match response.json::<AnkiConnectResponse>().await { Ok(anki_response) => { if let Some(error) = anki_response.error { Err(format!("AnkiConnect错误: {}", error)) } else if let Some(result) = anki_response.result { match serde_json::from_value::<Vec<Option<u64>>>(result) { Ok(note_ids) => Ok(note_ids), Err(e) => Err(format!("解析笔记ID列表失败: {}", e)), } } else { Err("AnkiConnect返回空结果".to_string()) } } Err(e) => Err(format!("解析AnkiConnect响应失败: {}", e)), } } else { Err(format!("AnkiConnect HTTP错误: {}", response.status())) } } Err(e) => Err(format!("添加笔记到Anki失败: {}", e)), } } /// 创建牌组(如果不存在) pub async fn create_deck_if_not_exists(deck_name: &str) -> Result<(), String> { let params = serde_json::json!({ "deck": deck_name }); let request = AnkiConnectRequest { action: "createDeck".to_string(), version: 6, params: Some(params), }; let client = reqwest::Client::new(); match client .post(ANKI_CONNECT_URL) .json(&request) .timeout(std::time::Duration::from_secs(10)) .send() .await { Ok(response) => { if response.status().is_success() { match response.json::<AnkiConnectResponse>().await { Ok(anki_response) => { if let Some(error) = anki_response.error { // 如果牌组已存在,这不算错误 if error.contains("already exists") { Ok(()) } else { Err(format!("创建牌组时出错: {}", error)) } } else { Ok(()) } } Err(e) => Err(format!("解析AnkiConnect响应失败: {}", e)), } } else { Err(format!("AnkiConnect HTTP错误: {}", response.status())) } } Err(e) => Err(format!("创建牌组失败: {}", e)), } }
12,770
anki_connect_service
rs
en
rust
code
{"qsc_code_num_words": 1125, "qsc_code_num_chars": 12770.0, "qsc_code_mean_word_length": 5.26577778, "qsc_code_frac_words_unique": 0.22044444, "qsc_code_frac_chars_top_2grams": 0.03798109, "qsc_code_frac_chars_top_3grams": 0.01417961, "qsc_code_frac_chars_top_4grams": 0.02633356, "qsc_code_frac_chars_dupe_5grams": 0.44361918, "qsc_code_frac_chars_dupe_6grams": 0.41120864, "qsc_code_frac_chars_dupe_7grams": 0.39736664, "qsc_code_frac_chars_dupe_8grams": 0.37525321, "qsc_code_frac_chars_dupe_9grams": 0.36833221, "qsc_code_frac_chars_dupe_10grams": 0.34807562, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01424071, "qsc_code_frac_chars_whitespace": 0.37862177, "qsc_code_size_file_byte": 12770.0, "qsc_code_num_lines": 362.0, "qsc_code_num_chars_line_max": 196.0, "qsc_code_num_chars_line_mean": 35.27624309, "qsc_code_frac_chars_alphabet": 0.73018273, "qsc_code_frac_chars_comments": 0.02505873, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.41455696, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00632911, "qsc_code_frac_chars_string_length": 0.1321179, "qsc_code_frac_chars_long_word_length": 0.02682515, "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/vector_store.rs
use crate::models::{ DocumentChunk, DocumentChunkWithEmbedding, RetrievedChunk, VectorStoreStats, AppError }; use crate::database::Database; use std::sync::Arc; use serde_json::Value; use rusqlite::params; type Result<T> = std::result::Result<T, AppError>; /// 向量存储抽象接口 pub trait VectorStore { /// 添加文档块和对应的向量 async fn add_chunks(&self, chunks: Vec<DocumentChunkWithEmbedding>) -> Result<()>; /// 搜索相似的文档块 async fn search_similar_chunks(&self, query_embedding: Vec<f32>, top_k: usize) -> Result<Vec<RetrievedChunk>>; /// 在指定分库中搜索相似的文档块 async fn search_similar_chunks_in_libraries(&self, query_embedding: Vec<f32>, top_k: usize, sub_library_ids: Option<Vec<String>>) -> Result<Vec<RetrievedChunk>>; /// 根据文档ID删除所有相关块 async fn delete_chunks_by_document_id(&self, document_id: &str) -> Result<()>; /// 获取统计信息 async fn get_stats(&self) -> Result<VectorStoreStats>; /// 清空所有向量数据 async fn clear_all(&self) -> Result<()>; } /// SQLite向量存储实现 (基础版本,使用余弦相似度) pub struct SqliteVectorStore { database: Arc<Database>, } impl SqliteVectorStore { pub fn new(database: Arc<Database>) -> Result<Self> { let store = Self { database }; store.initialize_tables()?; Ok(store) } /// 初始化向量存储相关表 fn initialize_tables(&self) -> Result<()> { let conn = self.database.conn().lock() .map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?; // 分库表 conn.execute( "CREATE TABLE IF NOT EXISTS rag_sub_libraries ( id TEXT PRIMARY KEY, name TEXT NOT NULL UNIQUE, description TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL )", [], ).map_err(|e| AppError::database(format!("创建分库表失败: {}", e)))?; // 检查并创建默认分库 let default_library_exists: bool = conn.query_row( "SELECT EXISTS(SELECT 1 FROM rag_sub_libraries WHERE name = 'default')", [], |row| row.get(0) ).unwrap_or(false); if !default_library_exists { let now = chrono::Utc::now().to_rfc3339(); conn.execute( "INSERT INTO rag_sub_libraries (id, name, description, created_at, updated_at) VALUES ('default', 'default', '默认知识库', ?, ?)", params![now, now], ).map_err(|e| AppError::database(format!("创建默认分库失败: {}", e)))?; } // 文档表(增加分库外键) conn.execute( "CREATE TABLE IF NOT EXISTS rag_documents ( id TEXT PRIMARY KEY, file_name TEXT NOT NULL, file_path TEXT, file_size INTEGER, content_type TEXT, total_chunks INTEGER DEFAULT 0, sub_library_id TEXT NOT NULL DEFAULT 'default', created_at TEXT NOT NULL, updated_at TEXT NOT NULL, FOREIGN KEY (sub_library_id) REFERENCES rag_sub_libraries (id) ON DELETE SET DEFAULT )", [], ).map_err(|e| AppError::database(format!("创建文档表失败: {}", e)))?; // 检查现有文档表是否有sub_library_id列 let has_sub_library_column: bool = conn.prepare("SELECT sub_library_id FROM rag_documents LIMIT 1") .is_ok(); if !has_sub_library_column { conn.execute( "ALTER TABLE rag_documents ADD COLUMN sub_library_id TEXT NOT NULL DEFAULT 'default'", [] ).map_err(|e| AppError::database(format!("添加分库列失败: {}", e)))?; } // 文档块表 conn.execute( "CREATE TABLE IF NOT EXISTS rag_document_chunks ( id TEXT PRIMARY KEY, document_id TEXT NOT NULL, chunk_index INTEGER NOT NULL, text TEXT NOT NULL, metadata TEXT NOT NULL, -- JSON格式的元数据 created_at TEXT NOT NULL, FOREIGN KEY (document_id) REFERENCES rag_documents (id) ON DELETE CASCADE )", [], ).map_err(|e| AppError::database(format!("创建文档块表失败: {}", e)))?; // 向量表(优化版本,存储为BLOB) conn.execute( "CREATE TABLE IF NOT EXISTS rag_vectors ( chunk_id TEXT PRIMARY KEY, embedding BLOB NOT NULL, -- 二进制格式的向量数据 dimension INTEGER NOT NULL, created_at TEXT NOT NULL, FOREIGN KEY (chunk_id) REFERENCES rag_document_chunks (id) ON DELETE CASCADE )", [], ).map_err(|e| AppError::database(format!("创建向量表失败: {}", e)))?; // 创建索引以提高查询性能 let indexes = vec![ "CREATE INDEX IF NOT EXISTS idx_rag_chunks_document_id ON rag_document_chunks(document_id)", "CREATE INDEX IF NOT EXISTS idx_rag_chunks_index ON rag_document_chunks(chunk_index)", "CREATE INDEX IF NOT EXISTS idx_rag_vectors_dimension ON rag_vectors(dimension)", "CREATE INDEX IF NOT EXISTS idx_rag_documents_sub_library ON rag_documents(sub_library_id)", "CREATE INDEX IF NOT EXISTS idx_rag_sub_libraries_name ON rag_sub_libraries(name)", ]; for index_sql in indexes { conn.execute(index_sql, []) .map_err(|e| AppError::database(format!("创建索引失败: {}", e)))?; } println!("✅ RAG向量存储表初始化完成"); Ok(()) } /// 将向量序列化为BLOB fn serialize_vector_to_blob(vector: &[f32]) -> Result<Vec<u8>> { let mut blob = Vec::with_capacity(vector.len() * 4); for &value in vector { blob.extend_from_slice(&value.to_le_bytes()); } Ok(blob) } /// 从BLOB反序列化向量 fn deserialize_vector_from_blob(blob: &[u8]) -> Result<Vec<f32>> { if blob.len() % 4 != 0 { return Err(AppError::database("向量BLOB大小不正确".to_string())); } let mut vector = Vec::with_capacity(blob.len() / 4); for chunk in blob.chunks_exact(4) { let bytes: [u8; 4] = chunk.try_into() .map_err(|_| AppError::database("向量BLOB格式错误".to_string()))?; vector.push(f32::from_le_bytes(bytes)); } Ok(vector) } /// 计算余弦相似度 fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 { if a.len() != b.len() { return 0.0; } let dot_product: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum(); let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt(); let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt(); if norm_a == 0.0 || norm_b == 0.0 { 0.0 } else { dot_product / (norm_a * norm_b) } } } impl VectorStore for SqliteVectorStore { async fn add_chunks(&self, chunks: Vec<DocumentChunkWithEmbedding>) -> Result<()> { let conn = self.database.conn().lock() .map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?; let transaction = conn.unchecked_transaction() .map_err(|e| AppError::database(format!("开始事务失败: {}", e)))?; let chunks_len = chunks.len(); for chunk_with_embedding in chunks { let chunk = &chunk_with_embedding.chunk; let embedding = &chunk_with_embedding.embedding; // 插入文档块 let metadata_json = serde_json::to_string(&chunk.metadata) .map_err(|e| AppError::database(format!("序列化元数据失败: {}", e)))?; transaction.execute( "INSERT OR REPLACE INTO rag_document_chunks (id, document_id, chunk_index, text, metadata, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", params![ chunk.id, chunk.document_id, chunk.chunk_index, chunk.text, metadata_json, chrono::Utc::now().to_rfc3339() ], ).map_err(|e| AppError::database(format!("插入文档块失败: {}", e)))?; // 将向量转换为BLOB let embedding_blob = Self::serialize_vector_to_blob(embedding)?; // 插入向量到rag_vectors表 transaction.execute( "INSERT OR REPLACE INTO rag_vectors (chunk_id, embedding, dimension, created_at) VALUES (?1, ?2, ?3, ?4)", params![ chunk.id, embedding_blob, embedding.len() as i32, chrono::Utc::now().to_rfc3339() ], ).map_err(|e| AppError::database(format!("插入向量失败: {}", e)))?; } transaction.commit() .map_err(|e| AppError::database(format!("提交事务失败: {}", e)))?; println!("✅ 成功添加 {} 个文档块到向量存储", chunks_len); Ok(()) } async fn search_similar_chunks(&self, query_embedding: Vec<f32>, top_k: usize) -> Result<Vec<RetrievedChunk>> { let conn = self.database.conn().lock() .map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?; // 基础SQLite实现:获取所有向量,在应用层计算相似度 let mut stmt = conn.prepare( "SELECT v.chunk_id, v.embedding, c.document_id, c.chunk_index, c.text, c.metadata FROM rag_vectors v JOIN rag_document_chunks c ON v.chunk_id = c.id WHERE v.dimension = ?" ).map_err(|e| AppError::database(format!("准备查询语句失败: {}", e)))?; let query_dim = query_embedding.len() as i32; let rows = stmt.query_map(params![query_dim], |row| { let chunk_id: String = row.get(0)?; let embedding_blob: Vec<u8> = row.get(1)?; let document_id: String = row.get(2)?; let chunk_index: usize = row.get(3)?; let text: String = row.get(4)?; let metadata_json: String = row.get(5)?; Ok((chunk_id, embedding_blob, document_id, chunk_index, text, metadata_json)) }).map_err(|e| AppError::database(format!("执行查询失败: {}", e)))?; let mut candidates = Vec::new(); for row in rows { let (chunk_id, embedding_blob, document_id, chunk_index, text, metadata_json) = row .map_err(|e| AppError::database(format!("读取查询结果失败: {}", e)))?; // 反序列化向量 let stored_embedding = Self::deserialize_vector_from_blob(&embedding_blob)?; // 计算余弦相似度 let similarity = Self::cosine_similarity(&query_embedding, &stored_embedding); // 解析元数据 let metadata: std::collections::HashMap<String, String> = serde_json::from_str(&metadata_json) .map_err(|e| AppError::database(format!("解析元数据失败: {}", e)))?; candidates.push(RetrievedChunk { chunk: DocumentChunk { id: chunk_id, document_id, chunk_index, text, metadata, }, score: similarity, }); } // 按相似度排序并返回前top_k个结果 candidates.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal)); candidates.truncate(top_k); println!("✅ 检索到 {} 个相似文档块", candidates.len()); Ok(candidates) } async fn search_similar_chunks_in_libraries(&self, query_embedding: Vec<f32>, top_k: usize, sub_library_ids: Option<Vec<String>>) -> Result<Vec<RetrievedChunk>> { let conn = self.database.conn().lock() .map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?; // 构建SQL查询,根据是否有分库ID过滤 // 构建SQL查询,根据是否有分库ID过滤 let (sql, params): (String, Vec<rusqlite::types::Value>) = if let Some(ref library_ids) = sub_library_ids { if library_ids.is_empty() { return Ok(Vec::new()); // 如果提供了空的分库ID列表,返回空结果 } let placeholders = library_ids.iter().map(|_| "?").collect::<Vec<_>>().join(","); let sql = format!( "SELECT v.chunk_id, v.embedding, c.document_id, c.chunk_index, c.text, c.metadata FROM rag_vectors v JOIN rag_document_chunks c ON v.chunk_id = c.id JOIN rag_documents d ON c.document_id = d.id WHERE v.dimension = ? AND d.sub_library_id IN ({})", placeholders ); let mut params = vec![rusqlite::types::Value::Integer(query_embedding.len() as i64)]; for lib_id in library_ids.iter() { params.push(rusqlite::types::Value::Text(lib_id.clone())); } (sql, params) } else { // 如果没有指定分库ID,查询所有分库 let sql = "SELECT v.chunk_id, v.embedding, c.document_id, c.chunk_index, c.text, c.metadata FROM rag_vectors v JOIN rag_document_chunks c ON v.chunk_id = c.id WHERE v.dimension = ?".to_string(); let params = vec![rusqlite::types::Value::Integer(query_embedding.len() as i64)]; (sql, params) }; let mut stmt = conn.prepare(&sql) .map_err(|e| AppError::database(format!("准备查询语句失败: {}", e)))?; let rows = stmt.query_map(rusqlite::params_from_iter(params), |row| { let chunk_id: String = row.get(0)?; let embedding_blob: Vec<u8> = row.get(1)?; let document_id: String = row.get(2)?; let chunk_index: usize = row.get(3)?; let text: String = row.get(4)?; let metadata_json: String = row.get(5)?; Ok((chunk_id, embedding_blob, document_id, chunk_index, text, metadata_json)) }).map_err(|e| AppError::database(format!("执行查询失败: {}", e)))?; let mut candidates = Vec::new(); for row in rows { let (chunk_id, embedding_blob, document_id, chunk_index, text, metadata_json) = row .map_err(|e| AppError::database(format!("读取查询结果失败: {}", e)))?; // 反序列化向量 let stored_embedding = Self::deserialize_vector_from_blob(&embedding_blob)?; // 计算余弦相似度 let similarity = Self::cosine_similarity(&query_embedding, &stored_embedding); // 解析元数据 let metadata: std::collections::HashMap<String, String> = serde_json::from_str(&metadata_json) .map_err(|e| AppError::database(format!("解析元数据失败: {}", e)))?; candidates.push(RetrievedChunk { chunk: DocumentChunk { id: chunk_id, document_id, chunk_index, text, metadata, }, score: similarity, }); } // 按相似度排序并返回前top_k个结果 candidates.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal)); candidates.truncate(top_k); let library_filter_msg = if let Some(ref lib_ids) = sub_library_ids { format!(" (过滤分库: {:?})", lib_ids) } else { " (所有分库)".to_string() }; println!("✅ 检索到 {} 个相似文档块{}", candidates.len(), library_filter_msg); Ok(candidates) } async fn delete_chunks_by_document_id(&self, document_id: &str) -> Result<()> { let conn = self.database.conn().lock() .map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?; let transaction = conn.unchecked_transaction() .map_err(|e| AppError::database(format!("开始事务失败: {}", e)))?; // VSS已移除,直接删除相关记录 // 删除向量(通过外键级联删除) transaction.execute( "DELETE FROM rag_document_chunks WHERE document_id = ?1", params![document_id], ).map_err(|e| AppError::database(format!("删除文档块失败: {}", e)))?; // 删除文档记录 transaction.execute( "DELETE FROM rag_documents WHERE id = ?1", params![document_id], ).map_err(|e| AppError::database(format!("删除文档记录失败: {}", e)))?; transaction.commit() .map_err(|e| AppError::database(format!("提交删除事务失败: {}", e)))?; println!("✅ 成功删除文档 {} 的所有块和VSS索引", document_id); Ok(()) } async fn get_stats(&self) -> Result<VectorStoreStats> { let conn = self.database.conn().lock() .map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?; let total_documents: usize = conn.query_row( "SELECT COUNT(*) FROM rag_documents", [], |row| row.get(0), ).map_err(|e| AppError::database(format!("查询文档数失败: {}", e)))?; let total_chunks: usize = conn.query_row( "SELECT COUNT(*) FROM rag_document_chunks", [], |row| row.get(0), ).map_err(|e| AppError::database(format!("查询块数失败: {}", e)))?; // 计算存储大小(估算) let storage_size_bytes: u64 = conn.query_row( "SELECT COALESCE(SUM(LENGTH(text) + LENGTH(embedding)), 0) FROM rag_document_chunks c LEFT JOIN rag_vectors v ON c.id = v.chunk_id", [], |row| row.get::<_, i64>(0).map(|s| s as u64), ).unwrap_or(0); Ok(VectorStoreStats { total_documents, total_chunks, storage_size_bytes, }) } async fn clear_all(&self) -> Result<()> { let conn = self.database.conn().lock() .map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?; let transaction = conn.unchecked_transaction() .map_err(|e| AppError::database(format!("开始事务失败: {}", e)))?; // 清空VSS索引 transaction.execute("DELETE FROM vss_chunks", []) .map_err(|e| AppError::database(format!("清空VSS索引失败: {}", e)))?; transaction.execute("DELETE FROM rag_vectors", []) .map_err(|e| AppError::database(format!("清空向量表失败: {}", e)))?; transaction.execute("DELETE FROM rag_document_chunks", []) .map_err(|e| AppError::database(format!("清空文档块表失败: {}", e)))?; transaction.execute("DELETE FROM rag_documents", []) .map_err(|e| AppError::database(format!("清空文档表失败: {}", e)))?; transaction.commit() .map_err(|e| AppError::database(format!("提交清空事务失败: {}", e)))?; println!("✅ 成功清空所有向量存储数据和VSS索引"); Ok(()) } } /// 文档管理相关方法 impl SqliteVectorStore { /// 添加文档记录 pub fn add_document_record(&self, document_id: &str, file_name: &str, file_path: Option<&str>, file_size: Option<u64>) -> Result<()> { self.add_document_record_with_library(document_id, file_name, file_path, file_size, "default") } /// 添加文档记录到指定分库 pub fn add_document_record_with_library(&self, document_id: &str, file_name: &str, file_path: Option<&str>, file_size: Option<u64>, sub_library_id: &str) -> Result<()> { let conn = self.database.conn().lock() .map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?; conn.execute( "INSERT OR REPLACE INTO rag_documents (id, file_name, file_path, file_size, sub_library_id, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", params![ document_id, file_name, file_path, file_size.map(|s| s as i64), sub_library_id, chrono::Utc::now().to_rfc3339(), chrono::Utc::now().to_rfc3339() ], ).map_err(|e| AppError::database(format!("添加文档记录失败: {}", e)))?; Ok(()) } /// 更新文档的块数统计 pub fn update_document_chunk_count(&self, document_id: &str, chunk_count: usize) -> Result<()> { let conn = self.database.conn().lock() .map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?; conn.execute( "UPDATE rag_documents SET total_chunks = ?1, updated_at = ?2 WHERE id = ?3", params![ chunk_count as i32, chrono::Utc::now().to_rfc3339(), document_id ], ).map_err(|e| AppError::database(format!("更新文档块数失败: {}", e)))?; Ok(()) } /// 获取所有文档列表 pub fn get_all_documents(&self) -> Result<Vec<Value>> { let conn = self.database.conn().lock() .map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?; let mut stmt = conn.prepare( "SELECT id, file_name, file_path, file_size, total_chunks, created_at, updated_at FROM rag_documents ORDER BY created_at DESC" ).map_err(|e| AppError::database(format!("准备查询语句失败: {}", e)))?; let rows = stmt.query_map([], |row| { Ok(serde_json::json!({ "id": row.get::<_, String>(0)?, "file_name": row.get::<_, String>(1)?, "file_path": row.get::<_, Option<String>>(2)?, "file_size": row.get::<_, Option<i64>>(3)?, "total_chunks": row.get::<_, i32>(4)?, "created_at": row.get::<_, String>(5)?, "updated_at": row.get::<_, String>(6)? })) }).map_err(|e| AppError::database(format!("查询文档列表失败: {}", e)))?; let mut documents = Vec::new(); for row in rows { documents.push(row.map_err(|e| AppError::database(format!("读取文档行失败: {}", e)))?); } Ok(documents) } }
22,135
vector_store
rs
en
rust
code
{"qsc_code_num_words": 2396, "qsc_code_num_chars": 22135.0, "qsc_code_mean_word_length": 4.67153589, "qsc_code_frac_words_unique": 0.13313856, "qsc_code_frac_chars_top_2grams": 0.07004378, "qsc_code_frac_chars_top_3grams": 0.02939337, "qsc_code_frac_chars_top_4grams": 0.06298579, "qsc_code_frac_chars_dupe_5grams": 0.59010096, "qsc_code_frac_chars_dupe_6grams": 0.57178594, "qsc_code_frac_chars_dupe_7grams": 0.52863397, "qsc_code_frac_chars_dupe_8grams": 0.46546949, "qsc_code_frac_chars_dupe_9grams": 0.4151702, "qsc_code_frac_chars_dupe_10grams": 0.38854641, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01009417, "qsc_code_frac_chars_whitespace": 0.33313756, "qsc_code_size_file_byte": 22135.0, "qsc_code_num_lines": 563.0, "qsc_code_num_chars_line_max": 174.0, "qsc_code_num_chars_line_mean": 39.31616341, "qsc_code_frac_chars_alphabet": 0.74778132, "qsc_code_frac_chars_comments": 0.0320759, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.39285714, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00952381, "qsc_code_frac_chars_string_length": 0.08746383, "qsc_code_frac_chars_long_word_length": 0.01138803, "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}
0015/esp_rlottie
rlottie/src/lottie/rapidjson/encodings.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_ENCODINGS_H_ #define RAPIDJSON_ENCODINGS_H_ #include "rapidjson.h" #if defined(_MSC_VER) && !defined(__clang__) RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(4244) // conversion from 'type1' to 'type2', possible loss of data RAPIDJSON_DIAG_OFF(4702) // unreachable code #elif defined(__GNUC__) RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(effc++) RAPIDJSON_DIAG_OFF(overflow) #endif RAPIDJSON_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////////// // Encoding /*! \class rapidjson::Encoding \brief Concept for encoding of Unicode characters. \code concept Encoding { typename Ch; //! Type of character. A "character" is actually a code unit in unicode's definition. enum { supportUnicode = 1 }; // or 0 if not supporting unicode //! \brief Encode a Unicode codepoint to an output stream. //! \param os Output stream. //! \param codepoint An unicode codepoint, ranging from 0x0 to 0x10FFFF inclusively. template<typename OutputStream> static void Encode(OutputStream& os, unsigned codepoint); //! \brief Decode a Unicode codepoint from an input stream. //! \param is Input stream. //! \param codepoint Output of the unicode codepoint. //! \return true if a valid codepoint can be decoded from the stream. template <typename InputStream> static bool Decode(InputStream& is, unsigned* codepoint); //! \brief Validate one Unicode codepoint from an encoded stream. //! \param is Input stream to obtain codepoint. //! \param os Output for copying one codepoint. //! \return true if it is valid. //! \note This function just validating and copying the codepoint without actually decode it. template <typename InputStream, typename OutputStream> static bool Validate(InputStream& is, OutputStream& os); // The following functions are deal with byte streams. //! Take a character from input byte stream, skip BOM if exist. template <typename InputByteStream> static CharType TakeBOM(InputByteStream& is); //! Take a character from input byte stream. template <typename InputByteStream> static Ch Take(InputByteStream& is); //! Put BOM to output byte stream. template <typename OutputByteStream> static void PutBOM(OutputByteStream& os); //! Put a character to output byte stream. template <typename OutputByteStream> static void Put(OutputByteStream& os, Ch c); }; \endcode */ /////////////////////////////////////////////////////////////////////////////// // UTF8 //! UTF-8 encoding. /*! http://en.wikipedia.org/wiki/UTF-8 http://tools.ietf.org/html/rfc3629 \tparam CharType Code unit for storing 8-bit UTF-8 data. Default is char. \note implements Encoding concept */ template<typename CharType = char> struct UTF8 { typedef CharType Ch; enum { supportUnicode = 1 }; template<typename OutputStream> static void Encode(OutputStream& os, unsigned codepoint) { if (codepoint <= 0x7F) os.Put(static_cast<Ch>(codepoint & 0xFF)); else if (codepoint <= 0x7FF) { os.Put(static_cast<Ch>(0xC0 | ((codepoint >> 6) & 0xFF))); os.Put(static_cast<Ch>(0x80 | ((codepoint & 0x3F)))); } else if (codepoint <= 0xFFFF) { os.Put(static_cast<Ch>(0xE0 | ((codepoint >> 12) & 0xFF))); os.Put(static_cast<Ch>(0x80 | ((codepoint >> 6) & 0x3F))); os.Put(static_cast<Ch>(0x80 | (codepoint & 0x3F))); } else { RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); os.Put(static_cast<Ch>(0xF0 | ((codepoint >> 18) & 0xFF))); os.Put(static_cast<Ch>(0x80 | ((codepoint >> 12) & 0x3F))); os.Put(static_cast<Ch>(0x80 | ((codepoint >> 6) & 0x3F))); os.Put(static_cast<Ch>(0x80 | (codepoint & 0x3F))); } } template<typename OutputStream> static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { if (codepoint <= 0x7F) PutUnsafe(os, static_cast<Ch>(codepoint & 0xFF)); else if (codepoint <= 0x7FF) { PutUnsafe(os, static_cast<Ch>(0xC0 | ((codepoint >> 6) & 0xFF))); PutUnsafe(os, static_cast<Ch>(0x80 | ((codepoint & 0x3F)))); } else if (codepoint <= 0xFFFF) { PutUnsafe(os, static_cast<Ch>(0xE0 | ((codepoint >> 12) & 0xFF))); PutUnsafe(os, static_cast<Ch>(0x80 | ((codepoint >> 6) & 0x3F))); PutUnsafe(os, static_cast<Ch>(0x80 | (codepoint & 0x3F))); } else { RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); PutUnsafe(os, static_cast<Ch>(0xF0 | ((codepoint >> 18) & 0xFF))); PutUnsafe(os, static_cast<Ch>(0x80 | ((codepoint >> 12) & 0x3F))); PutUnsafe(os, static_cast<Ch>(0x80 | ((codepoint >> 6) & 0x3F))); PutUnsafe(os, static_cast<Ch>(0x80 | (codepoint & 0x3F))); } } template <typename InputStream> static bool Decode(InputStream& is, unsigned* codepoint) { #define RAPIDJSON_COPY() c = is.Take(); *codepoint = (*codepoint << 6) | (static_cast<unsigned char>(c) & 0x3Fu) #define RAPIDJSON_TRANS(mask) result &= ((GetRange(static_cast<unsigned char>(c)) & mask) != 0) #define RAPIDJSON_TAIL() RAPIDJSON_COPY(); RAPIDJSON_TRANS(0x70) typename InputStream::Ch c = is.Take(); if (!(c & 0x80)) { *codepoint = static_cast<unsigned char>(c); return true; } unsigned char type = GetRange(static_cast<unsigned char>(c)); if (type >= 32) { *codepoint = 0; } else { *codepoint = (0xFFu >> type) & static_cast<unsigned char>(c); } bool result = true; switch (type) { case 2: RAPIDJSON_TAIL(); return result; case 3: RAPIDJSON_TAIL(); RAPIDJSON_TAIL(); return result; case 4: RAPIDJSON_COPY(); RAPIDJSON_TRANS(0x50); RAPIDJSON_TAIL(); return result; case 5: RAPIDJSON_COPY(); RAPIDJSON_TRANS(0x10); RAPIDJSON_TAIL(); RAPIDJSON_TAIL(); return result; case 6: RAPIDJSON_TAIL(); RAPIDJSON_TAIL(); RAPIDJSON_TAIL(); return result; case 10: RAPIDJSON_COPY(); RAPIDJSON_TRANS(0x20); RAPIDJSON_TAIL(); return result; case 11: RAPIDJSON_COPY(); RAPIDJSON_TRANS(0x60); RAPIDJSON_TAIL(); RAPIDJSON_TAIL(); return result; default: return false; } #undef RAPIDJSON_COPY #undef RAPIDJSON_TRANS #undef RAPIDJSON_TAIL } template <typename InputStream, typename OutputStream> static bool Validate(InputStream& is, OutputStream& os) { #define RAPIDJSON_COPY() os.Put(c = is.Take()) #define RAPIDJSON_TRANS(mask) result &= ((GetRange(static_cast<unsigned char>(c)) & mask) != 0) #define RAPIDJSON_TAIL() RAPIDJSON_COPY(); RAPIDJSON_TRANS(0x70) Ch c; RAPIDJSON_COPY(); if (!(c & 0x80)) return true; bool result = true; switch (GetRange(static_cast<unsigned char>(c))) { case 2: RAPIDJSON_TAIL(); return result; case 3: RAPIDJSON_TAIL(); RAPIDJSON_TAIL(); return result; case 4: RAPIDJSON_COPY(); RAPIDJSON_TRANS(0x50); RAPIDJSON_TAIL(); return result; case 5: RAPIDJSON_COPY(); RAPIDJSON_TRANS(0x10); RAPIDJSON_TAIL(); RAPIDJSON_TAIL(); return result; case 6: RAPIDJSON_TAIL(); RAPIDJSON_TAIL(); RAPIDJSON_TAIL(); return result; case 10: RAPIDJSON_COPY(); RAPIDJSON_TRANS(0x20); RAPIDJSON_TAIL(); return result; case 11: RAPIDJSON_COPY(); RAPIDJSON_TRANS(0x60); RAPIDJSON_TAIL(); RAPIDJSON_TAIL(); return result; default: return false; } #undef RAPIDJSON_COPY #undef RAPIDJSON_TRANS #undef RAPIDJSON_TAIL } static unsigned char GetRange(unsigned char c) { // Referring to DFA of http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ // With new mapping 1 -> 0x10, 7 -> 0x20, 9 -> 0x40, such that AND operation can test multiple types. static const unsigned char type[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10, 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, }; return type[c]; } template <typename InputByteStream> static CharType TakeBOM(InputByteStream& is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); typename InputByteStream::Ch c = Take(is); if (static_cast<unsigned char>(c) != 0xEFu) return c; c = is.Take(); if (static_cast<unsigned char>(c) != 0xBBu) return c; c = is.Take(); if (static_cast<unsigned char>(c) != 0xBFu) return c; c = is.Take(); return c; } template <typename InputByteStream> static Ch Take(InputByteStream& is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); return static_cast<Ch>(is.Take()); } template <typename OutputByteStream> static void PutBOM(OutputByteStream& os) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); os.Put(static_cast<typename OutputByteStream::Ch>(0xEFu)); os.Put(static_cast<typename OutputByteStream::Ch>(0xBBu)); os.Put(static_cast<typename OutputByteStream::Ch>(0xBFu)); } template <typename OutputByteStream> static void Put(OutputByteStream& os, Ch c) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); os.Put(static_cast<typename OutputByteStream::Ch>(c)); } }; /////////////////////////////////////////////////////////////////////////////// // UTF16 //! UTF-16 encoding. /*! http://en.wikipedia.org/wiki/UTF-16 http://tools.ietf.org/html/rfc2781 \tparam CharType Type for storing 16-bit UTF-16 data. Default is wchar_t. C++11 may use char16_t instead. \note implements Encoding concept \note For in-memory access, no need to concern endianness. The code units and code points are represented by CPU's endianness. For streaming, use UTF16LE and UTF16BE, which handle endianness. */ template<typename CharType = wchar_t> struct UTF16 { typedef CharType Ch; RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 2); enum { supportUnicode = 1 }; template<typename OutputStream> static void Encode(OutputStream& os, unsigned codepoint) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2); if (codepoint <= 0xFFFF) { RAPIDJSON_ASSERT(codepoint < 0xD800 || codepoint > 0xDFFF); // Code point itself cannot be surrogate pair os.Put(static_cast<typename OutputStream::Ch>(codepoint)); } else { RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); unsigned v = codepoint - 0x10000; os.Put(static_cast<typename OutputStream::Ch>((v >> 10) | 0xD800)); os.Put(static_cast<typename OutputStream::Ch>((v & 0x3FF) | 0xDC00)); } } template<typename OutputStream> static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2); if (codepoint <= 0xFFFF) { RAPIDJSON_ASSERT(codepoint < 0xD800 || codepoint > 0xDFFF); // Code point itself cannot be surrogate pair PutUnsafe(os, static_cast<typename OutputStream::Ch>(codepoint)); } else { RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); unsigned v = codepoint - 0x10000; PutUnsafe(os, static_cast<typename OutputStream::Ch>((v >> 10) | 0xD800)); PutUnsafe(os, static_cast<typename OutputStream::Ch>((v & 0x3FF) | 0xDC00)); } } template <typename InputStream> static bool Decode(InputStream& is, unsigned* codepoint) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 2); typename InputStream::Ch c = is.Take(); if (c < 0xD800 || c > 0xDFFF) { *codepoint = static_cast<unsigned>(c); return true; } else if (c <= 0xDBFF) { *codepoint = (static_cast<unsigned>(c) & 0x3FF) << 10; c = is.Take(); *codepoint |= (static_cast<unsigned>(c) & 0x3FF); *codepoint += 0x10000; return c >= 0xDC00 && c <= 0xDFFF; } return false; } template <typename InputStream, typename OutputStream> static bool Validate(InputStream& is, OutputStream& os) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 2); RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2); typename InputStream::Ch c; os.Put(static_cast<typename OutputStream::Ch>(c = is.Take())); if (c < 0xD800 || c > 0xDFFF) return true; else if (c <= 0xDBFF) { os.Put(c = is.Take()); return c >= 0xDC00 && c <= 0xDFFF; } return false; } }; //! UTF-16 little endian encoding. template<typename CharType = wchar_t> struct UTF16LE : UTF16<CharType> { template <typename InputByteStream> static CharType TakeBOM(InputByteStream& is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); CharType c = Take(is); return static_cast<uint16_t>(c) == 0xFEFFu ? Take(is) : c; } template <typename InputByteStream> static CharType Take(InputByteStream& is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); unsigned c = static_cast<uint8_t>(is.Take()); c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 8; return static_cast<CharType>(c); } template <typename OutputByteStream> static void PutBOM(OutputByteStream& os) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); os.Put(static_cast<typename OutputByteStream::Ch>(0xFFu)); os.Put(static_cast<typename OutputByteStream::Ch>(0xFEu)); } template <typename OutputByteStream> static void Put(OutputByteStream& os, CharType c) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); os.Put(static_cast<typename OutputByteStream::Ch>(static_cast<unsigned>(c) & 0xFFu)); os.Put(static_cast<typename OutputByteStream::Ch>((static_cast<unsigned>(c) >> 8) & 0xFFu)); } }; //! UTF-16 big endian encoding. template<typename CharType = wchar_t> struct UTF16BE : UTF16<CharType> { template <typename InputByteStream> static CharType TakeBOM(InputByteStream& is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); CharType c = Take(is); return static_cast<uint16_t>(c) == 0xFEFFu ? Take(is) : c; } template <typename InputByteStream> static CharType Take(InputByteStream& is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); unsigned c = static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 8; c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())); return static_cast<CharType>(c); } template <typename OutputByteStream> static void PutBOM(OutputByteStream& os) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); os.Put(static_cast<typename OutputByteStream::Ch>(0xFEu)); os.Put(static_cast<typename OutputByteStream::Ch>(0xFFu)); } template <typename OutputByteStream> static void Put(OutputByteStream& os, CharType c) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); os.Put(static_cast<typename OutputByteStream::Ch>((static_cast<unsigned>(c) >> 8) & 0xFFu)); os.Put(static_cast<typename OutputByteStream::Ch>(static_cast<unsigned>(c) & 0xFFu)); } }; /////////////////////////////////////////////////////////////////////////////// // UTF32 //! UTF-32 encoding. /*! http://en.wikipedia.org/wiki/UTF-32 \tparam CharType Type for storing 32-bit UTF-32 data. Default is unsigned. C++11 may use char32_t instead. \note implements Encoding concept \note For in-memory access, no need to concern endianness. The code units and code points are represented by CPU's endianness. For streaming, use UTF32LE and UTF32BE, which handle endianness. */ template<typename CharType = unsigned> struct UTF32 { typedef CharType Ch; RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 4); enum { supportUnicode = 1 }; template<typename OutputStream> static void Encode(OutputStream& os, unsigned codepoint) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 4); RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); os.Put(codepoint); } template<typename OutputStream> static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 4); RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); PutUnsafe(os, codepoint); } template <typename InputStream> static bool Decode(InputStream& is, unsigned* codepoint) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 4); Ch c = is.Take(); *codepoint = c; return c <= 0x10FFFF; } template <typename InputStream, typename OutputStream> static bool Validate(InputStream& is, OutputStream& os) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 4); Ch c; os.Put(c = is.Take()); return c <= 0x10FFFF; } }; //! UTF-32 little endian enocoding. template<typename CharType = unsigned> struct UTF32LE : UTF32<CharType> { template <typename InputByteStream> static CharType TakeBOM(InputByteStream& is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); CharType c = Take(is); return static_cast<uint32_t>(c) == 0x0000FEFFu ? Take(is) : c; } template <typename InputByteStream> static CharType Take(InputByteStream& is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); unsigned c = static_cast<uint8_t>(is.Take()); c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 8; c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 16; c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 24; return static_cast<CharType>(c); } template <typename OutputByteStream> static void PutBOM(OutputByteStream& os) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); os.Put(static_cast<typename OutputByteStream::Ch>(0xFFu)); os.Put(static_cast<typename OutputByteStream::Ch>(0xFEu)); os.Put(static_cast<typename OutputByteStream::Ch>(0x00u)); os.Put(static_cast<typename OutputByteStream::Ch>(0x00u)); } template <typename OutputByteStream> static void Put(OutputByteStream& os, CharType c) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); os.Put(static_cast<typename OutputByteStream::Ch>(c & 0xFFu)); os.Put(static_cast<typename OutputByteStream::Ch>((c >> 8) & 0xFFu)); os.Put(static_cast<typename OutputByteStream::Ch>((c >> 16) & 0xFFu)); os.Put(static_cast<typename OutputByteStream::Ch>((c >> 24) & 0xFFu)); } }; //! UTF-32 big endian encoding. template<typename CharType = unsigned> struct UTF32BE : UTF32<CharType> { template <typename InputByteStream> static CharType TakeBOM(InputByteStream& is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); CharType c = Take(is); return static_cast<uint32_t>(c) == 0x0000FEFFu ? Take(is) : c; } template <typename InputByteStream> static CharType Take(InputByteStream& is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); unsigned c = static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 24; c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 16; c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 8; c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())); return static_cast<CharType>(c); } template <typename OutputByteStream> static void PutBOM(OutputByteStream& os) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); os.Put(static_cast<typename OutputByteStream::Ch>(0x00u)); os.Put(static_cast<typename OutputByteStream::Ch>(0x00u)); os.Put(static_cast<typename OutputByteStream::Ch>(0xFEu)); os.Put(static_cast<typename OutputByteStream::Ch>(0xFFu)); } template <typename OutputByteStream> static void Put(OutputByteStream& os, CharType c) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); os.Put(static_cast<typename OutputByteStream::Ch>((c >> 24) & 0xFFu)); os.Put(static_cast<typename OutputByteStream::Ch>((c >> 16) & 0xFFu)); os.Put(static_cast<typename OutputByteStream::Ch>((c >> 8) & 0xFFu)); os.Put(static_cast<typename OutputByteStream::Ch>(c & 0xFFu)); } }; /////////////////////////////////////////////////////////////////////////////// // ASCII //! ASCII encoding. /*! http://en.wikipedia.org/wiki/ASCII \tparam CharType Code unit for storing 7-bit ASCII data. Default is char. \note implements Encoding concept */ template<typename CharType = char> struct ASCII { typedef CharType Ch; enum { supportUnicode = 0 }; template<typename OutputStream> static void Encode(OutputStream& os, unsigned codepoint) { RAPIDJSON_ASSERT(codepoint <= 0x7F); os.Put(static_cast<Ch>(codepoint & 0xFF)); } template<typename OutputStream> static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { RAPIDJSON_ASSERT(codepoint <= 0x7F); PutUnsafe(os, static_cast<Ch>(codepoint & 0xFF)); } template <typename InputStream> static bool Decode(InputStream& is, unsigned* codepoint) { uint8_t c = static_cast<uint8_t>(is.Take()); *codepoint = c; return c <= 0X7F; } template <typename InputStream, typename OutputStream> static bool Validate(InputStream& is, OutputStream& os) { uint8_t c = static_cast<uint8_t>(is.Take()); os.Put(static_cast<typename OutputStream::Ch>(c)); return c <= 0x7F; } template <typename InputByteStream> static CharType TakeBOM(InputByteStream& is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); uint8_t c = static_cast<uint8_t>(Take(is)); return static_cast<Ch>(c); } template <typename InputByteStream> static Ch Take(InputByteStream& is) { RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); return static_cast<Ch>(is.Take()); } template <typename OutputByteStream> static void PutBOM(OutputByteStream& os) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); (void)os; } template <typename OutputByteStream> static void Put(OutputByteStream& os, Ch c) { RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); os.Put(static_cast<typename OutputByteStream::Ch>(c)); } }; /////////////////////////////////////////////////////////////////////////////// // AutoUTF //! Runtime-specified UTF encoding type of a stream. enum UTFType { kUTF8 = 0, //!< UTF-8. kUTF16LE = 1, //!< UTF-16 little endian. kUTF16BE = 2, //!< UTF-16 big endian. kUTF32LE = 3, //!< UTF-32 little endian. kUTF32BE = 4 //!< UTF-32 big endian. }; //! Dynamically select encoding according to stream's runtime-specified UTF encoding type. /*! \note This class can be used with AutoUTFInputtStream and AutoUTFOutputStream, which provides GetType(). */ template<typename CharType> struct AutoUTF { typedef CharType Ch; enum { supportUnicode = 1 }; #define RAPIDJSON_ENCODINGS_FUNC(x) UTF8<Ch>::x, UTF16LE<Ch>::x, UTF16BE<Ch>::x, UTF32LE<Ch>::x, UTF32BE<Ch>::x template<typename OutputStream> static RAPIDJSON_FORCEINLINE void Encode(OutputStream& os, unsigned codepoint) { typedef void (*EncodeFunc)(OutputStream&, unsigned); static const EncodeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Encode) }; (*f[os.GetType()])(os, codepoint); } template<typename OutputStream> static RAPIDJSON_FORCEINLINE void EncodeUnsafe(OutputStream& os, unsigned codepoint) { typedef void (*EncodeFunc)(OutputStream&, unsigned); static const EncodeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(EncodeUnsafe) }; (*f[os.GetType()])(os, codepoint); } template <typename InputStream> static RAPIDJSON_FORCEINLINE bool Decode(InputStream& is, unsigned* codepoint) { typedef bool (*DecodeFunc)(InputStream&, unsigned*); static const DecodeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Decode) }; return (*f[is.GetType()])(is, codepoint); } template <typename InputStream, typename OutputStream> static RAPIDJSON_FORCEINLINE bool Validate(InputStream& is, OutputStream& os) { typedef bool (*ValidateFunc)(InputStream&, OutputStream&); static const ValidateFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Validate) }; return (*f[is.GetType()])(is, os); } #undef RAPIDJSON_ENCODINGS_FUNC }; /////////////////////////////////////////////////////////////////////////////// // Transcoder //! Encoding conversion. template<typename SourceEncoding, typename TargetEncoding> struct Transcoder { //! Take one Unicode codepoint from source encoding, convert it to target encoding and put it to the output stream. template<typename InputStream, typename OutputStream> static RAPIDJSON_FORCEINLINE bool Transcode(InputStream& is, OutputStream& os) { unsigned codepoint; if (!SourceEncoding::Decode(is, &codepoint)) return false; TargetEncoding::Encode(os, codepoint); return true; } template<typename InputStream, typename OutputStream> static RAPIDJSON_FORCEINLINE bool TranscodeUnsafe(InputStream& is, OutputStream& os) { unsigned codepoint; if (!SourceEncoding::Decode(is, &codepoint)) return false; TargetEncoding::EncodeUnsafe(os, codepoint); return true; } //! Validate one Unicode codepoint from an encoded stream. template<typename InputStream, typename OutputStream> static RAPIDJSON_FORCEINLINE bool Validate(InputStream& is, OutputStream& os) { return Transcode(is, os); // Since source/target encoding is different, must transcode. } }; // Forward declaration. template<typename Stream> inline void PutUnsafe(Stream& stream, typename Stream::Ch c); //! Specialization of Transcoder with same source and target encoding. template<typename Encoding> struct Transcoder<Encoding, Encoding> { template<typename InputStream, typename OutputStream> static RAPIDJSON_FORCEINLINE bool Transcode(InputStream& is, OutputStream& os) { os.Put(is.Take()); // Just copy one code unit. This semantic is different from primary template class. return true; } template<typename InputStream, typename OutputStream> static RAPIDJSON_FORCEINLINE bool TranscodeUnsafe(InputStream& is, OutputStream& os) { PutUnsafe(os, is.Take()); // Just copy one code unit. This semantic is different from primary template class. return true; } template<typename InputStream, typename OutputStream> static RAPIDJSON_FORCEINLINE bool Validate(InputStream& is, OutputStream& os) { return Encoding::Validate(is, os); // source/target encoding are the same } }; RAPIDJSON_NAMESPACE_END #if defined(__GNUC__) || (defined(_MSC_VER) && !defined(__clang__)) RAPIDJSON_DIAG_POP #endif #endif // RAPIDJSON_ENCODINGS_H_
29,281
encodings
h
en
c
code
{"qsc_code_num_words": 3459, "qsc_code_num_chars": 29281.0, "qsc_code_mean_word_length": 5.40098294, "qsc_code_frac_words_unique": 0.10176352, "qsc_code_frac_chars_top_2grams": 0.01359597, "qsc_code_frac_chars_top_3grams": 0.02023338, "qsc_code_frac_chars_top_4grams": 0.02676373, "qsc_code_frac_chars_dupe_5grams": 0.80805053, "qsc_code_frac_chars_dupe_6grams": 0.7797345, "qsc_code_frac_chars_dupe_7grams": 0.74017771, "qsc_code_frac_chars_dupe_8grams": 0.69751633, "qsc_code_frac_chars_dupe_9grams": 0.65308853, "qsc_code_frac_chars_dupe_10grams": 0.6300182, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.04132803, "qsc_code_frac_chars_whitespace": 0.20999966, "qsc_code_size_file_byte": 29281.0, "qsc_code_num_lines": 716.0, "qsc_code_num_chars_line_max": 131.0, "qsc_code_num_chars_line_mean": 40.8952514, "qsc_code_frac_chars_alphabet": 0.76629777, "qsc_code_frac_chars_comments": 0.20491103, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.638, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00047249, "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.03157081, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.09, "qsc_codec_frac_lines_func_ratio": 0.13, "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.154, "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": 1, "qsc_code_frac_chars_dupe_6grams": 1, "qsc_code_frac_chars_dupe_7grams": 1, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 1, "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/allocators.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_ALLOCATORS_H_ #define RAPIDJSON_ALLOCATORS_H_ #include "rapidjson.h" RAPIDJSON_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////////// // Allocator /*! \class rapidjson::Allocator \brief Concept for allocating, resizing and freeing memory block. Note that Malloc() and Realloc() are non-static but Free() is static. So if an allocator need to support Free(), it needs to put its pointer in the header of memory block. \code concept Allocator { static const bool kNeedFree; //!< Whether this allocator needs to call Free(). // Allocate a memory block. // \param size of the memory block in bytes. // \returns pointer to the memory block. void* Malloc(size_t size); // Resize a memory block. // \param originalPtr The pointer to current memory block. Null pointer is permitted. // \param originalSize The current size in bytes. (Design issue: since some allocator may not book-keep this, explicitly pass to it can save memory.) // \param newSize the new size in bytes. void* Realloc(void* originalPtr, size_t originalSize, size_t newSize); // Free a memory block. // \param pointer to the memory block. Null pointer is permitted. static void Free(void *ptr); }; \endcode */ /*! \def RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY \ingroup RAPIDJSON_CONFIG \brief User-defined kDefaultChunkCapacity definition. User can define this as any \c size that is a power of 2. */ #ifndef RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY #define RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY (64 * 1024) #endif /////////////////////////////////////////////////////////////////////////////// // CrtAllocator //! C-runtime library allocator. /*! This class is just wrapper for standard C library memory routines. \note implements Allocator concept */ class CrtAllocator { public: static const bool kNeedFree = true; void* Malloc(size_t size) { if (size) // behavior of malloc(0) is implementation defined. return RAPIDJSON_MALLOC(size); else return NULL; // standardize to returning NULL. } void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) { (void)originalSize; if (newSize == 0) { RAPIDJSON_FREE(originalPtr); return NULL; } return RAPIDJSON_REALLOC(originalPtr, newSize); } static void Free(void *ptr) { RAPIDJSON_FREE(ptr); } }; /////////////////////////////////////////////////////////////////////////////// // MemoryPoolAllocator //! Default memory allocator used by the parser and DOM. /*! This allocator allocate memory blocks from pre-allocated memory chunks. It does not free memory blocks. And Realloc() only allocate new memory. The memory chunks are allocated by BaseAllocator, which is CrtAllocator by default. User may also supply a buffer as the first chunk. If the user-buffer is full then additional chunks are allocated by BaseAllocator. The user-buffer is not deallocated by this allocator. \tparam BaseAllocator the allocator type for allocating memory chunks. Default is CrtAllocator. \note implements Allocator concept */ template <typename BaseAllocator = CrtAllocator> class MemoryPoolAllocator { public: static const bool kNeedFree = false; //!< Tell users that no need to call Free() with this allocator. (concept Allocator) //! Constructor with chunkSize. /*! \param chunkSize The size of memory chunk. The default is kDefaultChunkSize. \param baseAllocator The allocator for allocating memory chunks. */ MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) : chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(0), baseAllocator_(baseAllocator), ownBaseAllocator_(0) { } //! Constructor with user-supplied buffer. /*! The user buffer will be used firstly. When it is full, memory pool allocates new chunk with chunk size. The user buffer will not be deallocated when this allocator is destructed. \param buffer User supplied buffer. \param size Size of the buffer in bytes. It must at least larger than sizeof(ChunkHeader). \param chunkSize The size of memory chunk. The default is kDefaultChunkSize. \param baseAllocator The allocator for allocating memory chunks. */ MemoryPoolAllocator(void *buffer, size_t size, size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) : chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(buffer), baseAllocator_(baseAllocator), ownBaseAllocator_(0) { RAPIDJSON_ASSERT(buffer != 0); RAPIDJSON_ASSERT(size > sizeof(ChunkHeader)); chunkHead_ = reinterpret_cast<ChunkHeader*>(buffer); chunkHead_->capacity = size - sizeof(ChunkHeader); chunkHead_->size = 0; chunkHead_->next = 0; } //! Destructor. /*! This deallocates all memory chunks, excluding the user-supplied buffer. */ ~MemoryPoolAllocator() { Clear(); RAPIDJSON_DELETE(ownBaseAllocator_); } //! Deallocates all memory chunks, excluding the user-supplied buffer. void Clear() { while (chunkHead_ && chunkHead_ != userBuffer_) { ChunkHeader* next = chunkHead_->next; baseAllocator_->Free(chunkHead_); chunkHead_ = next; } if (chunkHead_ && chunkHead_ == userBuffer_) chunkHead_->size = 0; // Clear user buffer } //! Computes the total capacity of allocated memory chunks. /*! \return total capacity in bytes. */ size_t Capacity() const { size_t capacity = 0; for (ChunkHeader* c = chunkHead_; c != 0; c = c->next) capacity += c->capacity; return capacity; } //! Computes the memory blocks allocated. /*! \return total used bytes. */ size_t Size() const { size_t size = 0; for (ChunkHeader* c = chunkHead_; c != 0; c = c->next) size += c->size; return size; } //! Allocates a memory block. (concept Allocator) void* Malloc(size_t size) { if (!size) return NULL; size = RAPIDJSON_ALIGN(size); if (chunkHead_ == 0 || chunkHead_->size + size > chunkHead_->capacity) if (!AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size)) return NULL; void *buffer = reinterpret_cast<char *>(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size; chunkHead_->size += size; return buffer; } //! Resizes a memory block (concept Allocator) void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) { if (originalPtr == 0) return Malloc(newSize); if (newSize == 0) return NULL; originalSize = RAPIDJSON_ALIGN(originalSize); newSize = RAPIDJSON_ALIGN(newSize); // Do not shrink if new size is smaller than original if (originalSize >= newSize) return originalPtr; // Simply expand it if it is the last allocation and there is sufficient space if (originalPtr == reinterpret_cast<char *>(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size - originalSize) { size_t increment = static_cast<size_t>(newSize - originalSize); if (chunkHead_->size + increment <= chunkHead_->capacity) { chunkHead_->size += increment; return originalPtr; } } // Realloc process: allocate and copy memory, do not free original buffer. if (void* newBuffer = Malloc(newSize)) { if (originalSize) std::memcpy(newBuffer, originalPtr, originalSize); return newBuffer; } else return NULL; } //! Frees a memory block (concept Allocator) static void Free(void *ptr) { (void)ptr; } // Do nothing private: //! Copy constructor is not permitted. MemoryPoolAllocator(const MemoryPoolAllocator& rhs) /* = delete */; //! Copy assignment operator is not permitted. MemoryPoolAllocator& operator=(const MemoryPoolAllocator& rhs) /* = delete */; //! Creates a new chunk. /*! \param capacity Capacity of the chunk in bytes. \return true if success. */ bool AddChunk(size_t capacity) { if (!baseAllocator_) ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator)(); if (ChunkHeader* chunk = reinterpret_cast<ChunkHeader*>(baseAllocator_->Malloc(RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + capacity))) { chunk->capacity = capacity; chunk->size = 0; chunk->next = chunkHead_; chunkHead_ = chunk; return true; } else return false; } static const int kDefaultChunkCapacity = RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY; //!< Default chunk capacity. //! Chunk header for perpending to each chunk. /*! Chunks are stored as a singly linked list. */ struct ChunkHeader { size_t capacity; //!< Capacity of the chunk in bytes (excluding the header itself). size_t size; //!< Current size of allocated memory in bytes. ChunkHeader *next; //!< Next chunk in the linked list. }; ChunkHeader *chunkHead_; //!< Head of the chunk linked-list. Only the head chunk serves allocation. size_t chunk_capacity_; //!< The minimum capacity of chunk when they are allocated. void *userBuffer_; //!< User supplied buffer. BaseAllocator* baseAllocator_; //!< base allocator for allocating memory chunks. BaseAllocator* ownBaseAllocator_; //!< base allocator created by this object. }; RAPIDJSON_NAMESPACE_END #endif // RAPIDJSON_ENCODINGS_H_
10,695
allocators
h
en
c
code
{"qsc_code_num_words": 1198, "qsc_code_num_chars": 10695.0, "qsc_code_mean_word_length": 5.72287145, "qsc_code_frac_words_unique": 0.23622705, "qsc_code_frac_chars_top_2grams": 0.01604434, "qsc_code_frac_chars_top_3grams": 0.00918903, "qsc_code_frac_chars_top_4grams": 0.01750292, "qsc_code_frac_chars_dupe_5grams": 0.24270712, "qsc_code_frac_chars_dupe_6grams": 0.17605018, "qsc_code_frac_chars_dupe_7grams": 0.15825554, "qsc_code_frac_chars_dupe_8grams": 0.14133606, "qsc_code_frac_chars_dupe_9grams": 0.14133606, "qsc_code_frac_chars_dupe_10grams": 0.125, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00418565, "qsc_code_frac_chars_whitespace": 0.24048621, "qsc_code_size_file_byte": 10695.0, "qsc_code_num_lines": 284.0, "qsc_code_num_chars_line_max": 154.0, "qsc_code_num_chars_line_mean": 37.6584507, "qsc_code_frac_chars_alphabet": 0.8398375, "qsc_code_frac_chars_comments": 0.51818607, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.16129032, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00213468, "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.01612903, "qsc_codec_frac_lines_func_ratio": 0.10483871, "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.23387097, "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/stream.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. #include "rapidjson.h" #ifndef RAPIDJSON_STREAM_H_ #define RAPIDJSON_STREAM_H_ #include "encodings.h" RAPIDJSON_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////////// // Stream /*! \class rapidjson::Stream \brief Concept for reading and writing characters. For read-only stream, no need to implement PutBegin(), Put(), Flush() and PutEnd(). For write-only stream, only need to implement Put() and Flush(). \code concept Stream { typename Ch; //!< Character type of the stream. //! Read the current character from stream without moving the read cursor. Ch Peek() const; //! Read the current character from stream and moving the read cursor to next character. Ch Take(); //! Get the current read cursor. //! \return Number of characters read from start. size_t Tell(); //! Begin writing operation at the current read pointer. //! \return The begin writer pointer. Ch* PutBegin(); //! Write a character. void Put(Ch c); //! Flush the buffer. void Flush(); //! End the writing operation. //! \param begin The begin write pointer returned by PutBegin(). //! \return Number of characters written. size_t PutEnd(Ch* begin); } \endcode */ //! Provides additional information for stream. /*! By using traits pattern, this type provides a default configuration for stream. For custom stream, this type can be specialized for other configuration. See TEST(Reader, CustomStringStream) in readertest.cpp for example. */ template<typename Stream> struct StreamTraits { //! Whether to make local copy of stream for optimization during parsing. /*! By default, for safety, streams do not use local copy optimization. Stream that can be copied fast should specialize this, like StreamTraits<StringStream>. */ enum { copyOptimization = 0 }; }; //! Reserve n characters for writing to a stream. template<typename Stream> inline void PutReserve(Stream& stream, size_t count) { (void)stream; (void)count; } //! Write character to a stream, presuming buffer is reserved. template<typename Stream> inline void PutUnsafe(Stream& stream, typename Stream::Ch c) { stream.Put(c); } //! Put N copies of a character to a stream. template<typename Stream, typename Ch> inline void PutN(Stream& stream, Ch c, size_t n) { PutReserve(stream, n); for (size_t i = 0; i < n; i++) PutUnsafe(stream, c); } /////////////////////////////////////////////////////////////////////////////// // GenericStreamWrapper //! A Stream Wrapper /*! \tThis string stream is a wrapper for any stream by just forwarding any \treceived message to the origin stream. \note implements Stream concept */ #if defined(_MSC_VER) && _MSC_VER <= 1800 RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(4702) // unreachable code RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated #endif template <typename InputStream, typename Encoding = UTF8<> > class GenericStreamWrapper { public: typedef typename Encoding::Ch Ch; GenericStreamWrapper(InputStream& is): is_(is) {} Ch Peek() const { return is_.Peek(); } Ch Take() { return is_.Take(); } size_t Tell() { return is_.Tell(); } Ch* PutBegin() { return is_.PutBegin(); } void Put(Ch ch) { is_.Put(ch); } void Flush() { is_.Flush(); } size_t PutEnd(Ch* ch) { return is_.PutEnd(ch); } // wrapper for MemoryStream const Ch* Peek4() const { return is_.Peek4(); } // wrapper for AutoUTFInputStream UTFType GetType() const { return is_.GetType(); } bool HasBOM() const { return is_.HasBOM(); } protected: InputStream& is_; }; #if defined(_MSC_VER) && _MSC_VER <= 1800 RAPIDJSON_DIAG_POP #endif /////////////////////////////////////////////////////////////////////////////// // StringStream //! Read-only string stream. /*! \note implements Stream concept */ template <typename Encoding> struct GenericStringStream { typedef typename Encoding::Ch Ch; GenericStringStream(const Ch *src) : src_(src), head_(src) {} Ch Peek() const { return *src_; } Ch Take() { return *src_++; } size_t Tell() const { return static_cast<size_t>(src_ - head_); } 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; } const Ch* src_; //!< Current read position. const Ch* head_; //!< Original head of the string. }; template <typename Encoding> struct StreamTraits<GenericStringStream<Encoding> > { enum { copyOptimization = 1 }; }; //! String stream with UTF8 encoding. typedef GenericStringStream<UTF8<> > StringStream; /////////////////////////////////////////////////////////////////////////////// // InsituStringStream //! A read-write string stream. /*! This string stream is particularly designed for in-situ parsing. \note implements Stream concept */ template <typename Encoding> struct GenericInsituStringStream { typedef typename Encoding::Ch Ch; GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {} // Read Ch Peek() { return *src_; } Ch Take() { return *src_++; } size_t Tell() { return static_cast<size_t>(src_ - head_); } // Write void Put(Ch c) { RAPIDJSON_ASSERT(dst_ != 0); *dst_++ = c; } Ch* PutBegin() { return dst_ = src_; } size_t PutEnd(Ch* begin) { return static_cast<size_t>(dst_ - begin); } void Flush() {} Ch* Push(size_t count) { Ch* begin = dst_; dst_ += count; return begin; } void Pop(size_t count) { dst_ -= count; } Ch* src_; Ch* dst_; Ch* head_; }; template <typename Encoding> struct StreamTraits<GenericInsituStringStream<Encoding> > { enum { copyOptimization = 1 }; }; //! Insitu string stream with UTF8 encoding. typedef GenericInsituStringStream<UTF8<> > InsituStringStream; RAPIDJSON_NAMESPACE_END #endif // RAPIDJSON_STREAM_H_
6,753
stream
h
en
c
code
{"qsc_code_num_words": 831, "qsc_code_num_chars": 6753.0, "qsc_code_mean_word_length": 5.23947052, "qsc_code_frac_words_unique": 0.28760529, "qsc_code_frac_chars_top_2grams": 0.01837391, "qsc_code_frac_chars_top_3grams": 0.00826826, "qsc_code_frac_chars_top_4grams": 0.01194304, "qsc_code_frac_chars_dupe_5grams": 0.19912724, "qsc_code_frac_chars_dupe_6grams": 0.11713367, "qsc_code_frac_chars_dupe_7grams": 0.07165825, "qsc_code_frac_chars_dupe_8grams": 0.05879651, "qsc_code_frac_chars_dupe_9grams": 0.03261369, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0067617, "qsc_code_frac_chars_whitespace": 0.18969347, "qsc_code_size_file_byte": 6753.0, "qsc_code_num_lines": 223.0, "qsc_code_num_chars_line_max": 96.0, "qsc_code_num_chars_line_mean": 30.28251121, "qsc_code_frac_chars_alphabet": 0.78892544, "qsc_code_frac_chars_comments": 0.52672886, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.25842697, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0068836, "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.05617978, "qsc_codec_frac_lines_func_ratio": 0.35955056, "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.39325843, "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/memorybuffer.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_MEMORYBUFFER_H_ #define RAPIDJSON_MEMORYBUFFER_H_ #include "stream.h" #include "internal/stack.h" RAPIDJSON_NAMESPACE_BEGIN //! Represents an in-memory output byte stream. /*! This class is mainly for being wrapped by EncodedOutputStream or AutoUTFOutputStream. It is similar to FileWriteBuffer but the destination is an in-memory buffer instead of a file. Differences between MemoryBuffer and StringBuffer: 1. StringBuffer has Encoding but MemoryBuffer is only a byte buffer. 2. StringBuffer::GetString() returns a null-terminated string. MemoryBuffer::GetBuffer() returns a buffer without terminator. \tparam Allocator type for allocating memory buffer. \note implements Stream concept */ template <typename Allocator = CrtAllocator> struct GenericMemoryBuffer { typedef char Ch; // byte GenericMemoryBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} void Put(Ch c) { *stack_.template Push<Ch>() = c; } void Flush() {} void Clear() { stack_.Clear(); } void ShrinkToFit() { stack_.ShrinkToFit(); } Ch* Push(size_t count) { return stack_.template Push<Ch>(count); } void Pop(size_t count) { stack_.template Pop<Ch>(count); } const Ch* GetBuffer() const { return stack_.template Bottom<Ch>(); } size_t GetSize() const { return stack_.GetSize(); } static const size_t kDefaultCapacity = 256; mutable internal::Stack<Allocator> stack_; }; typedef GenericMemoryBuffer<> MemoryBuffer; //! Implement specialized version of PutN() with memset() for better performance. template<> inline void PutN(MemoryBuffer& memoryBuffer, char c, size_t n) { std::memset(memoryBuffer.stack_.Push<char>(n), c, n * sizeof(c)); } RAPIDJSON_NAMESPACE_END #endif // RAPIDJSON_MEMORYBUFFER_H_
2,560
memorybuffer
h
en
c
code
{"qsc_code_num_words": 333, "qsc_code_num_chars": 2560.0, "qsc_code_mean_word_length": 5.58858859, "qsc_code_frac_words_unique": 0.5015015, "qsc_code_frac_chars_top_2grams": 0.03224073, "qsc_code_frac_chars_top_3grams": 0.0354648, "qsc_code_frac_chars_top_4grams": 0.01719506, "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.00565238, "qsc_code_frac_chars_whitespace": 0.17070313, "qsc_code_size_file_byte": 2560.0, "qsc_code_num_lines": 70.0, "qsc_code_num_chars_line_max": 130.0, "qsc_code_num_chars_line_mean": 36.57142857, "qsc_code_frac_chars_alphabet": 0.87093735, "qsc_code_frac_chars_comments": 0.55898437, "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.02125775, "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.34482759, "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.4137931, "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/filereadstream.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_FILEREADSTREAM_H_ #define RAPIDJSON_FILEREADSTREAM_H_ #include "stream.h" #include <cstdio> #ifdef __clang__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(padded) RAPIDJSON_DIAG_OFF(unreachable-code) RAPIDJSON_DIAG_OFF(missing-noreturn) #endif RAPIDJSON_NAMESPACE_BEGIN //! File byte stream for input using fread(). /*! \note implements Stream concept */ class FileReadStream { public: typedef char Ch; //!< Character type (byte). //! Constructor. /*! \param fp File pointer opened for read. \param buffer user-supplied buffer. \param bufferSize size of buffer in bytes. Must >=4 bytes. */ FileReadStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { RAPIDJSON_ASSERT(fp_ != 0); RAPIDJSON_ASSERT(bufferSize >= 4); Read(); } Ch Peek() const { return *current_; } Ch Take() { Ch c = *current_; Read(); return c; } size_t Tell() const { return count_ + static_cast<size_t>(current_ - buffer_); } // 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; } // For encoding detection only. const Ch* Peek4() const { return (current_ + 4 - !eof_ <= bufferLast_) ? current_ : 0; } private: void Read() { if (current_ < bufferLast_) ++current_; else if (!eof_) { count_ += readCount_; readCount_ = std::fread(buffer_, 1, bufferSize_, fp_); bufferLast_ = buffer_ + readCount_ - 1; current_ = buffer_; if (readCount_ < bufferSize_) { buffer_[readCount_] = '\0'; ++bufferLast_; eof_ = true; } } } std::FILE* fp_; Ch *buffer_; size_t bufferSize_; Ch *bufferLast_; Ch *current_; size_t readCount_; size_t count_; //!< Number of characters read bool eof_; }; RAPIDJSON_NAMESPACE_END #ifdef __clang__ RAPIDJSON_DIAG_POP #endif #endif // RAPIDJSON_FILESTREAM_H_
3,001
filereadstream
h
en
c
code
{"qsc_code_num_words": 361, "qsc_code_num_chars": 3001.0, "qsc_code_mean_word_length": 5.21052632, "qsc_code_frac_words_unique": 0.45152355, "qsc_code_frac_chars_top_2grams": 0.01860712, "qsc_code_frac_chars_top_3grams": 0.04253057, "qsc_code_frac_chars_top_4grams": 0.01701223, "qsc_code_frac_chars_dupe_5grams": 0.02870813, "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.00873744, "qsc_code_frac_chars_whitespace": 0.23725425, "qsc_code_size_file_byte": 3001.0, "qsc_code_num_lines": 99.0, "qsc_code_num_chars_line_max": 196.0, "qsc_code_num_chars_line_mean": 30.31313131, "qsc_code_frac_chars_alphabet": 0.81301879, "qsc_code_frac_chars_comments": 0.37487504, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0862069, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00533049, "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.10344828, "qsc_codec_frac_lines_func_ratio": 0.17241379, "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.22413793, "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/cursorstreamwrapper.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_CURSORSTREAMWRAPPER_H_ #define RAPIDJSON_CURSORSTREAMWRAPPER_H_ #include "stream.h" #if defined(__GNUC__) RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(effc++) #endif #if defined(_MSC_VER) && _MSC_VER <= 1800 RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(4702) // unreachable code RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated #endif RAPIDJSON_NAMESPACE_BEGIN //! Cursor stream wrapper for counting line and column number if error exists. /*! \tparam InputStream Any stream that implements Stream Concept */ template <typename InputStream, typename Encoding = UTF8<> > class CursorStreamWrapper : public GenericStreamWrapper<InputStream, Encoding> { public: typedef typename Encoding::Ch Ch; CursorStreamWrapper(InputStream& is): GenericStreamWrapper<InputStream, Encoding>(is), line_(1), col_(0) {} // counting line and column number Ch Take() { Ch ch = this->is_.Take(); if(ch == '\n') { line_ ++; col_ = 0; } else { col_ ++; } return ch; } //! Get the error line number, if error exists. size_t GetLine() const { return line_; } //! Get the error column number, if error exists. size_t GetColumn() const { return col_; } private: size_t line_; //!< Current Line size_t col_; //!< Current Column }; #if defined(_MSC_VER) && _MSC_VER <= 1800 RAPIDJSON_DIAG_POP #endif #if defined(__GNUC__) RAPIDJSON_DIAG_POP #endif RAPIDJSON_NAMESPACE_END #endif // RAPIDJSON_CURSORSTREAMWRAPPER_H_
2,281
cursorstreamwrapper
h
en
c
code
{"qsc_code_num_words": 295, "qsc_code_num_chars": 2281.0, "qsc_code_mean_word_length": 5.32542373, "qsc_code_frac_words_unique": 0.48813559, "qsc_code_frac_chars_top_2grams": 0.05792489, "qsc_code_frac_chars_top_3grams": 0.05537874, "qsc_code_frac_chars_top_4grams": 0.03628262, "qsc_code_frac_chars_dupe_5grams": 0.18395926, "qsc_code_frac_chars_dupe_6grams": 0.11266709, "qsc_code_frac_chars_dupe_7grams": 0.04837683, "qsc_code_frac_chars_dupe_8grams": 0.04837683, "qsc_code_frac_chars_dupe_9grams": 0.04837683, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0141844, "qsc_code_frac_chars_whitespace": 0.19640509, "qsc_code_size_file_byte": 2281.0, "qsc_code_num_lines": 78.0, "qsc_code_num_chars_line_max": 93.0, "qsc_code_num_chars_line_mean": 29.24358974, "qsc_code_frac_chars_alphabet": 0.84288052, "qsc_code_frac_chars_comments": 0.49890399, "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.00874891, "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.23076923, "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.30769231, "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/istreamwrapper.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_ISTREAMWRAPPER_H_ #define RAPIDJSON_ISTREAMWRAPPER_H_ #include "stream.h" #include <iosfwd> #include <ios> #ifdef __clang__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(padded) #elif defined(_MSC_VER) RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(4351) // new behavior: elements of array 'array' will be default initialized #endif RAPIDJSON_NAMESPACE_BEGIN //! Wrapper of \c std::basic_istream into RapidJSON's Stream concept. /*! The classes can be wrapped including but not limited to: - \c std::istringstream - \c std::stringstream - \c std::wistringstream - \c std::wstringstream - \c std::ifstream - \c std::fstream - \c std::wifstream - \c std::wfstream \tparam StreamType Class derived from \c std::basic_istream. */ template <typename StreamType> class BasicIStreamWrapper { public: typedef typename StreamType::char_type Ch; //! Constructor. /*! \param stream stream opened for read. */ BasicIStreamWrapper(StreamType &stream) : stream_(stream), buffer_(peekBuffer_), bufferSize_(4), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { Read(); } //! Constructor. /*! \param stream stream opened for read. \param buffer user-supplied buffer. \param bufferSize size of buffer in bytes. Must >=4 bytes. */ BasicIStreamWrapper(StreamType &stream, char* buffer, size_t bufferSize) : stream_(stream), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { RAPIDJSON_ASSERT(bufferSize >= 4); Read(); } Ch Peek() const { return *current_; } Ch Take() { Ch c = *current_; Read(); return c; } size_t Tell() const { return count_ + static_cast<size_t>(current_ - buffer_); } // 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; } // For encoding detection only. const Ch* Peek4() const { return (current_ + 4 - !eof_ <= bufferLast_) ? current_ : 0; } private: BasicIStreamWrapper(); BasicIStreamWrapper(const BasicIStreamWrapper&); BasicIStreamWrapper& operator=(const BasicIStreamWrapper&); void Read() { if (current_ < bufferLast_) ++current_; else if (!eof_) { count_ += readCount_; readCount_ = bufferSize_; bufferLast_ = buffer_ + readCount_ - 1; current_ = buffer_; if (!stream_.read(buffer_, static_cast<std::streamsize>(bufferSize_))) { readCount_ = static_cast<size_t>(stream_.gcount()); *(bufferLast_ = buffer_ + readCount_) = '\0'; eof_ = true; } } } StreamType &stream_; Ch peekBuffer_[4], *buffer_; size_t bufferSize_; Ch *bufferLast_; Ch *current_; size_t readCount_; size_t count_; //!< Number of characters read bool eof_; }; typedef BasicIStreamWrapper<std::istream> IStreamWrapper; typedef BasicIStreamWrapper<std::wistream> WIStreamWrapper; #if defined(__clang__) || defined(_MSC_VER) RAPIDJSON_DIAG_POP #endif RAPIDJSON_NAMESPACE_END #endif // RAPIDJSON_ISTREAMWRAPPER_H_
4,082
istreamwrapper
h
en
c
code
{"qsc_code_num_words": 472, "qsc_code_num_chars": 4082.0, "qsc_code_mean_word_length": 5.61016949, "qsc_code_frac_words_unique": 0.41101695, "qsc_code_frac_chars_top_2grams": 0.01510574, "qsc_code_frac_chars_top_3grams": 0.03021148, "qsc_code_frac_chars_top_4grams": 0.01208459, "qsc_code_frac_chars_dupe_5grams": 0.12726586, "qsc_code_frac_chars_dupe_6grams": 0.09214502, "qsc_code_frac_chars_dupe_7grams": 0.06722054, "qsc_code_frac_chars_dupe_8grams": 0.03625378, "qsc_code_frac_chars_dupe_9grams": 0.03625378, "qsc_code_frac_chars_dupe_10grams": 0.03625378, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00844542, "qsc_code_frac_chars_whitespace": 0.21680549, "qsc_code_size_file_byte": 4082.0, "qsc_code_num_lines": 128.0, "qsc_code_num_chars_line_max": 214.0, "qsc_code_num_chars_line_mean": 31.890625, "qsc_code_frac_chars_alphabet": 0.81983109, "qsc_code_frac_chars_comments": 0.38290054, "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.00396983, "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.07462687, "qsc_codec_frac_lines_func_ratio": 0.19402985, "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.25373134, "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/reader.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_READER_H_ #define RAPIDJSON_READER_H_ /*! \file reader.h */ #include "allocators.h" #include "stream.h" #include "encodedstream.h" #include "internal/clzll.h" #include "internal/meta.h" #include "internal/stack.h" #include "internal/strtod.h" #include <limits> #if defined(RAPIDJSON_SIMD) && defined(_MSC_VER) #include <intrin.h> #pragma intrinsic(_BitScanForward) #endif #ifdef RAPIDJSON_SSE42 #include <nmmintrin.h> #elif defined(RAPIDJSON_SSE2) #include <emmintrin.h> #elif defined(RAPIDJSON_NEON) #include <arm_neon.h> #endif #ifdef __clang__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(old-style-cast) RAPIDJSON_DIAG_OFF(padded) RAPIDJSON_DIAG_OFF(switch-enum) #elif defined(_MSC_VER) RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant RAPIDJSON_DIAG_OFF(4702) // unreachable code #endif #ifdef __GNUC__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(effc++) #endif //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN #define RAPIDJSON_NOTHING /* deliberately empty */ #ifndef RAPIDJSON_PARSE_ERROR_EARLY_RETURN #define RAPIDJSON_PARSE_ERROR_EARLY_RETURN(value) \ RAPIDJSON_MULTILINEMACRO_BEGIN \ if (RAPIDJSON_UNLIKELY(HasParseError())) { return value; } \ RAPIDJSON_MULTILINEMACRO_END #endif #define RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID \ RAPIDJSON_PARSE_ERROR_EARLY_RETURN(RAPIDJSON_NOTHING) //!@endcond /*! \def RAPIDJSON_PARSE_ERROR_NORETURN \ingroup RAPIDJSON_ERRORS \brief Macro to indicate a parse error. \param parseErrorCode \ref rapidjson::ParseErrorCode of the error \param offset position of the error in JSON input (\c size_t) This macros can be used as a customization point for the internal error handling mechanism of RapidJSON. A common usage model is to throw an exception instead of requiring the caller to explicitly check the \ref rapidjson::GenericReader::Parse's return value: \code #define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode,offset) \ throw ParseException(parseErrorCode, #parseErrorCode, offset) #include <stdexcept> // std::runtime_error #include "rapidjson/error/error.h" // rapidjson::ParseResult struct ParseException : std::runtime_error, rapidjson::ParseResult { ParseException(rapidjson::ParseErrorCode code, const char* msg, size_t offset) : std::runtime_error(msg), ParseResult(code, offset) {} }; #include "rapidjson/reader.h" \endcode \see RAPIDJSON_PARSE_ERROR, rapidjson::GenericReader::Parse */ #ifndef RAPIDJSON_PARSE_ERROR_NORETURN #define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset) \ RAPIDJSON_MULTILINEMACRO_BEGIN \ RAPIDJSON_ASSERT(!HasParseError()); /* Error can only be assigned once */ \ SetParseError(parseErrorCode, offset); \ RAPIDJSON_MULTILINEMACRO_END #endif /*! \def RAPIDJSON_PARSE_ERROR \ingroup RAPIDJSON_ERRORS \brief (Internal) macro to indicate and handle a parse error. \param parseErrorCode \ref rapidjson::ParseErrorCode of the error \param offset position of the error in JSON input (\c size_t) Invokes RAPIDJSON_PARSE_ERROR_NORETURN and stops the parsing. \see RAPIDJSON_PARSE_ERROR_NORETURN \hideinitializer */ #ifndef RAPIDJSON_PARSE_ERROR #define RAPIDJSON_PARSE_ERROR(parseErrorCode, offset) \ RAPIDJSON_MULTILINEMACRO_BEGIN \ RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset); \ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; \ RAPIDJSON_MULTILINEMACRO_END #endif #include "error/error.h" // ParseErrorCode, ParseResult RAPIDJSON_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////////// // ParseFlag /*! \def RAPIDJSON_PARSE_DEFAULT_FLAGS \ingroup RAPIDJSON_CONFIG \brief User-defined kParseDefaultFlags definition. User can define this as any \c ParseFlag combinations. */ #ifndef RAPIDJSON_PARSE_DEFAULT_FLAGS #define RAPIDJSON_PARSE_DEFAULT_FLAGS kParseNoFlags #endif //! Combination of parseFlags /*! \see Reader::Parse, Document::Parse, Document::ParseInsitu, Document::ParseStream */ enum ParseFlag { kParseNoFlags = 0, //!< No flags are set. kParseInsituFlag = 1, //!< In-situ(destructive) parsing. kParseValidateEncodingFlag = 2, //!< Validate encoding of JSON strings. kParseIterativeFlag = 4, //!< Iterative(constant complexity in terms of function call stack size) parsing. kParseStopWhenDoneFlag = 8, //!< After parsing a complete JSON root from stream, stop further processing the rest of stream. When this flag is used, parser will not generate kParseErrorDocumentRootNotSingular error. kParseFullPrecisionFlag = 16, //!< Parse number in full precision (but slower). kParseCommentsFlag = 32, //!< Allow one-line (//) and multi-line (/**/) comments. kParseNumbersAsStringsFlag = 64, //!< Parse all numbers (ints/doubles) as strings. kParseTrailingCommasFlag = 128, //!< Allow trailing commas at the end of objects and arrays. kParseNanAndInfFlag = 256, //!< Allow parsing NaN, Inf, Infinity, -Inf and -Infinity as doubles. kParseEscapedApostropheFlag = 512, //!< Allow escaped apostrophe in strings. kParseDefaultFlags = RAPIDJSON_PARSE_DEFAULT_FLAGS //!< Default parse flags. Can be customized by defining RAPIDJSON_PARSE_DEFAULT_FLAGS }; /////////////////////////////////////////////////////////////////////////////// // Handler /*! \class rapidjson::Handler \brief Concept for receiving events from GenericReader upon parsing. The functions return true if no error occurs. If they return false, the event publisher should terminate the process. \code concept Handler { typename Ch; bool Null(); bool Bool(bool b); bool Int(int i); bool Uint(unsigned i); bool Int64(int64_t i); bool Uint64(uint64_t i); bool Double(double d); /// enabled via kParseNumbersAsStringsFlag, string is not null-terminated (use length) bool RawNumber(const Ch* str, SizeType length, bool copy); bool String(const Ch* str, SizeType length, bool copy); bool StartObject(); bool Key(const Ch* str, SizeType length, bool copy); bool EndObject(SizeType memberCount); bool StartArray(); bool EndArray(SizeType elementCount); }; \endcode */ /////////////////////////////////////////////////////////////////////////////// // BaseReaderHandler //! Default implementation of Handler. /*! This can be used as base class of any reader handler. \note implements Handler concept */ template<typename Encoding = UTF8<>, typename Derived = void> struct BaseReaderHandler { typedef typename Encoding::Ch Ch; typedef typename internal::SelectIf<internal::IsSame<Derived, void>, BaseReaderHandler, Derived>::Type Override; bool Default() { return true; } bool Null() { return static_cast<Override&>(*this).Default(); } bool Bool(bool) { return static_cast<Override&>(*this).Default(); } bool Int(int) { return static_cast<Override&>(*this).Default(); } bool Uint(unsigned) { return static_cast<Override&>(*this).Default(); } bool Int64(int64_t) { return static_cast<Override&>(*this).Default(); } bool Uint64(uint64_t) { return static_cast<Override&>(*this).Default(); } bool Double(double) { return static_cast<Override&>(*this).Default(); } /// enabled via kParseNumbersAsStringsFlag, string is not null-terminated (use length) bool RawNumber(const Ch* str, SizeType len, bool copy) { return static_cast<Override&>(*this).String(str, len, copy); } bool String(const Ch*, SizeType, bool) { return static_cast<Override&>(*this).Default(); } bool StartObject() { return static_cast<Override&>(*this).Default(); } bool Key(const Ch* str, SizeType len, bool copy) { return static_cast<Override&>(*this).String(str, len, copy); } bool EndObject(SizeType) { return static_cast<Override&>(*this).Default(); } bool StartArray() { return static_cast<Override&>(*this).Default(); } bool EndArray(SizeType) { return static_cast<Override&>(*this).Default(); } }; /////////////////////////////////////////////////////////////////////////////// // StreamLocalCopy namespace internal { template<typename Stream, int = StreamTraits<Stream>::copyOptimization> class StreamLocalCopy; //! Do copy optimization. template<typename Stream> class StreamLocalCopy<Stream, 1> { public: StreamLocalCopy(Stream& original) : s(original), original_(original) {} ~StreamLocalCopy() { original_ = s; } Stream s; private: StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */; Stream& original_; }; //! Keep reference. template<typename Stream> class StreamLocalCopy<Stream, 0> { public: StreamLocalCopy(Stream& original) : s(original) {} Stream& s; private: StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */; }; } // namespace internal /////////////////////////////////////////////////////////////////////////////// // SkipWhitespace //! Skip the JSON white spaces in a stream. /*! \param is A input stream for skipping white spaces. \note This function has SSE2/SSE4.2 specialization. */ template<typename InputStream> void SkipWhitespace(InputStream& is) { internal::StreamLocalCopy<InputStream> copy(is); InputStream& s(copy.s); typename InputStream::Ch c; while ((c = s.Peek()) == ' ' || c == '\n' || c == '\r' || c == '\t') s.Take(); } inline const char* SkipWhitespace(const char* p, const char* end) { while (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) ++p; return p; } #ifdef RAPIDJSON_SSE42 //! Skip whitespace with SSE 4.2 pcmpistrm instruction, testing 16 8-byte characters at once. inline const char *SkipWhitespace_SIMD(const char* p) { // Fast return for single non-whitespace if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') ++p; else return p; // 16-byte align to the next boundary const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') ++p; else return p; // The rest of string using SIMD static const char whitespace[16] = " \n\r\t"; const __m128i w = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespace[0])); for (;; p += 16) { const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); const int r = _mm_cmpistri(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_LEAST_SIGNIFICANT | _SIDD_NEGATIVE_POLARITY); if (r != 16) // some of characters is non-whitespace return p + r; } } inline const char *SkipWhitespace_SIMD(const char* p, const char* end) { // Fast return for single non-whitespace if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) ++p; else return p; // The middle of string using SIMD static const char whitespace[16] = " \n\r\t"; const __m128i w = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespace[0])); for (; p <= end - 16; p += 16) { const __m128i s = _mm_loadu_si128(reinterpret_cast<const __m128i *>(p)); const int r = _mm_cmpistri(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_LEAST_SIGNIFICANT | _SIDD_NEGATIVE_POLARITY); if (r != 16) // some of characters is non-whitespace return p + r; } return SkipWhitespace(p, end); } #elif defined(RAPIDJSON_SSE2) //! Skip whitespace with SSE2 instructions, testing 16 8-byte characters at once. inline const char *SkipWhitespace_SIMD(const char* p) { // Fast return for single non-whitespace if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') ++p; else return p; // 16-byte align to the next boundary const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') ++p; else return p; // The rest of string #define C16(c) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c } static const char whitespaces[4][16] = { C16(' '), C16('\n'), C16('\r'), C16('\t') }; #undef C16 const __m128i w0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[0][0])); const __m128i w1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[1][0])); const __m128i w2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[2][0])); const __m128i w3 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[3][0])); for (;; p += 16) { const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); __m128i x = _mm_cmpeq_epi8(s, w0); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1)); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2)); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3)); unsigned short r = static_cast<unsigned short>(~_mm_movemask_epi8(x)); if (r != 0) { // some of characters may be non-whitespace #ifdef _MSC_VER // Find the index of first non-whitespace unsigned long offset; _BitScanForward(&offset, r); return p + offset; #else return p + __builtin_ffs(r) - 1; #endif } } } inline const char *SkipWhitespace_SIMD(const char* p, const char* end) { // Fast return for single non-whitespace if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) ++p; else return p; // The rest of string #define C16(c) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c } static const char whitespaces[4][16] = { C16(' '), C16('\n'), C16('\r'), C16('\t') }; #undef C16 const __m128i w0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[0][0])); const __m128i w1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[1][0])); const __m128i w2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[2][0])); const __m128i w3 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[3][0])); for (; p <= end - 16; p += 16) { const __m128i s = _mm_loadu_si128(reinterpret_cast<const __m128i *>(p)); __m128i x = _mm_cmpeq_epi8(s, w0); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1)); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2)); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3)); unsigned short r = static_cast<unsigned short>(~_mm_movemask_epi8(x)); if (r != 0) { // some of characters may be non-whitespace #ifdef _MSC_VER // Find the index of first non-whitespace unsigned long offset; _BitScanForward(&offset, r); return p + offset; #else return p + __builtin_ffs(r) - 1; #endif } } return SkipWhitespace(p, end); } #elif defined(RAPIDJSON_NEON) //! Skip whitespace with ARM Neon instructions, testing 16 8-byte characters at once. inline const char *SkipWhitespace_SIMD(const char* p) { // Fast return for single non-whitespace if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') ++p; else return p; // 16-byte align to the next boundary const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') ++p; else return p; const uint8x16_t w0 = vmovq_n_u8(' '); const uint8x16_t w1 = vmovq_n_u8('\n'); const uint8x16_t w2 = vmovq_n_u8('\r'); const uint8x16_t w3 = vmovq_n_u8('\t'); for (;; p += 16) { const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p)); uint8x16_t x = vceqq_u8(s, w0); x = vorrq_u8(x, vceqq_u8(s, w1)); x = vorrq_u8(x, vceqq_u8(s, w2)); x = vorrq_u8(x, vceqq_u8(s, w3)); x = vmvnq_u8(x); // Negate x = vrev64q_u8(x); // Rev in 64 uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract if (low == 0) { if (high != 0) { uint32_t lz = internal::clzll(high); return p + 8 + (lz >> 3); } } else { uint32_t lz = internal::clzll(low); return p + (lz >> 3); } } } inline const char *SkipWhitespace_SIMD(const char* p, const char* end) { // Fast return for single non-whitespace if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) ++p; else return p; const uint8x16_t w0 = vmovq_n_u8(' '); const uint8x16_t w1 = vmovq_n_u8('\n'); const uint8x16_t w2 = vmovq_n_u8('\r'); const uint8x16_t w3 = vmovq_n_u8('\t'); for (; p <= end - 16; p += 16) { const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p)); uint8x16_t x = vceqq_u8(s, w0); x = vorrq_u8(x, vceqq_u8(s, w1)); x = vorrq_u8(x, vceqq_u8(s, w2)); x = vorrq_u8(x, vceqq_u8(s, w3)); x = vmvnq_u8(x); // Negate x = vrev64q_u8(x); // Rev in 64 uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract if (low == 0) { if (high != 0) { uint32_t lz = internal::clzll(high); return p + 8 + (lz >> 3); } } else { uint32_t lz = internal::clzll(low); return p + (lz >> 3); } } return SkipWhitespace(p, end); } #endif // RAPIDJSON_NEON #ifdef RAPIDJSON_SIMD //! Template function specialization for InsituStringStream template<> inline void SkipWhitespace(InsituStringStream& is) { is.src_ = const_cast<char*>(SkipWhitespace_SIMD(is.src_)); } //! Template function specialization for StringStream template<> inline void SkipWhitespace(StringStream& is) { is.src_ = SkipWhitespace_SIMD(is.src_); } template<> inline void SkipWhitespace(EncodedInputStream<UTF8<>, MemoryStream>& is) { is.is_.src_ = SkipWhitespace_SIMD(is.is_.src_, is.is_.end_); } #endif // RAPIDJSON_SIMD /////////////////////////////////////////////////////////////////////////////// // GenericReader //! SAX-style JSON parser. Use \ref Reader for UTF8 encoding and default allocator. /*! GenericReader parses JSON text from a stream, and send events synchronously to an object implementing Handler concept. It needs to allocate a stack for storing a single decoded string during non-destructive parsing. For in-situ parsing, the decoded string is directly written to the source text string, no temporary buffer is required. A GenericReader object can be reused for parsing multiple JSON text. \tparam SourceEncoding Encoding of the input stream. \tparam TargetEncoding Encoding of the parse output. \tparam StackAllocator Allocator type for stack. */ template <typename SourceEncoding, typename TargetEncoding, typename StackAllocator = CrtAllocator> class GenericReader { public: typedef typename SourceEncoding::Ch Ch; //!< SourceEncoding character type //! Constructor. /*! \param stackAllocator Optional allocator for allocating stack memory. (Only use for non-destructive parsing) \param stackCapacity stack capacity in bytes for storing a single decoded string. (Only use for non-destructive parsing) */ GenericReader(StackAllocator* stackAllocator = 0, size_t stackCapacity = kDefaultStackCapacity) : stack_(stackAllocator, stackCapacity), parseResult_(), state_(IterativeParsingStartState) {} //! Parse JSON text. /*! \tparam parseFlags Combination of \ref ParseFlag. \tparam InputStream Type of input stream, implementing Stream concept. \tparam Handler Type of handler, implementing Handler concept. \param is Input stream to be parsed. \param handler The handler to receive events. \return Whether the parsing is successful. */ template <unsigned parseFlags, typename InputStream, typename Handler> ParseResult Parse(InputStream& is, Handler& handler) { if (parseFlags & kParseIterativeFlag) return IterativeParse<parseFlags>(is, handler); parseResult_.Clear(); ClearStackOnExit scope(*this); SkipWhitespaceAndComments<parseFlags>(is); RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); if (RAPIDJSON_UNLIKELY(is.Peek() == '\0')) { RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentEmpty, is.Tell()); RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); } else { ParseValue<parseFlags>(is, handler); RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); if (!(parseFlags & kParseStopWhenDoneFlag)) { SkipWhitespaceAndComments<parseFlags>(is); RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); if (RAPIDJSON_UNLIKELY(is.Peek() != '\0')) { RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentRootNotSingular, is.Tell()); RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); } } } return parseResult_; } //! Parse JSON text (with \ref kParseDefaultFlags) /*! \tparam InputStream Type of input stream, implementing Stream concept \tparam Handler Type of handler, implementing Handler concept. \param is Input stream to be parsed. \param handler The handler to receive events. \return Whether the parsing is successful. */ template <typename InputStream, typename Handler> ParseResult Parse(InputStream& is, Handler& handler) { return Parse<kParseDefaultFlags>(is, handler); } //! Initialize JSON text token-by-token parsing /*! */ void IterativeParseInit() { parseResult_.Clear(); state_ = IterativeParsingStartState; } //! Parse one token from JSON text /*! \tparam InputStream Type of input stream, implementing Stream concept \tparam Handler Type of handler, implementing Handler concept. \param is Input stream to be parsed. \param handler The handler to receive events. \return Whether the parsing is successful. */ template <unsigned parseFlags, typename InputStream, typename Handler> bool IterativeParseNext(InputStream& is, Handler& handler) { while (RAPIDJSON_LIKELY(is.Peek() != '\0')) { SkipWhitespaceAndComments<parseFlags>(is); Token t = Tokenize(is.Peek()); IterativeParsingState n = Predict(state_, t); IterativeParsingState d = Transit<parseFlags>(state_, t, n, is, handler); // If we've finished or hit an error... if (RAPIDJSON_UNLIKELY(IsIterativeParsingCompleteState(d))) { // Report errors. if (d == IterativeParsingErrorState) { HandleError(state_, is); return false; } // Transition to the finish state. RAPIDJSON_ASSERT(d == IterativeParsingFinishState); state_ = d; // If StopWhenDone is not set... if (!(parseFlags & kParseStopWhenDoneFlag)) { // ... and extra non-whitespace data is found... SkipWhitespaceAndComments<parseFlags>(is); if (is.Peek() != '\0') { // ... this is considered an error. HandleError(state_, is); return false; } } // Success! We are done! return true; } // Transition to the new state. state_ = d; // If we parsed anything other than a delimiter, we invoked the handler, so we can return true now. if (!IsIterativeParsingDelimiterState(n)) return true; } // We reached the end of file. stack_.Clear(); if (state_ != IterativeParsingFinishState) { HandleError(state_, is); return false; } return true; } //! Check if token-by-token parsing JSON text is complete /*! \return Whether the JSON has been fully decoded. */ RAPIDJSON_FORCEINLINE bool IterativeParseComplete() const { return IsIterativeParsingCompleteState(state_); } //! Whether a parse error has occurred in the last parsing. bool HasParseError() const { return parseResult_.IsError(); } //! Get the \ref ParseErrorCode of last parsing. ParseErrorCode GetParseErrorCode() const { return parseResult_.Code(); } //! Get the position of last parsing error in input, 0 otherwise. size_t GetErrorOffset() const { return parseResult_.Offset(); } protected: void SetParseError(ParseErrorCode code, size_t offset) { parseResult_.Set(code, offset); } private: // Prohibit copy constructor & assignment operator. GenericReader(const GenericReader&); GenericReader& operator=(const GenericReader&); void ClearStack() { stack_.Clear(); } // clear stack on any exit from ParseStream, e.g. due to exception struct ClearStackOnExit { explicit ClearStackOnExit(GenericReader& r) : r_(r) {} ~ClearStackOnExit() { r_.ClearStack(); } private: GenericReader& r_; ClearStackOnExit(const ClearStackOnExit&); ClearStackOnExit& operator=(const ClearStackOnExit&); }; template<unsigned parseFlags, typename InputStream> void SkipWhitespaceAndComments(InputStream& is) { SkipWhitespace(is); if (parseFlags & kParseCommentsFlag) { while (RAPIDJSON_UNLIKELY(Consume(is, '/'))) { if (Consume(is, '*')) { while (true) { if (RAPIDJSON_UNLIKELY(is.Peek() == '\0')) RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell()); else if (Consume(is, '*')) { if (Consume(is, '/')) break; } else is.Take(); } } else if (RAPIDJSON_LIKELY(Consume(is, '/'))) while (is.Peek() != '\0' && is.Take() != '\n') {} else RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell()); SkipWhitespace(is); } } } // Parse object: { string : value, ... } template<unsigned parseFlags, typename InputStream, typename Handler> void ParseObject(InputStream& is, Handler& handler) { RAPIDJSON_ASSERT(is.Peek() == '{'); is.Take(); // Skip '{' if (RAPIDJSON_UNLIKELY(!handler.StartObject())) RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); SkipWhitespaceAndComments<parseFlags>(is); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (Consume(is, '}')) { if (RAPIDJSON_UNLIKELY(!handler.EndObject(0))) // empty object RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); return; } for (SizeType memberCount = 0;;) { if (RAPIDJSON_UNLIKELY(is.Peek() != '"')) RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell()); ParseString<parseFlags>(is, handler, true); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; SkipWhitespaceAndComments<parseFlags>(is); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (RAPIDJSON_UNLIKELY(!Consume(is, ':'))) RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell()); SkipWhitespaceAndComments<parseFlags>(is); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; ParseValue<parseFlags>(is, handler); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; SkipWhitespaceAndComments<parseFlags>(is); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; ++memberCount; switch (is.Peek()) { case ',': is.Take(); SkipWhitespaceAndComments<parseFlags>(is); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; break; case '}': is.Take(); if (RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount))) RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); return; default: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell()); break; // This useless break is only for making warning and coverage happy } if (parseFlags & kParseTrailingCommasFlag) { if (is.Peek() == '}') { if (RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount))) RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); is.Take(); return; } } } } // Parse array: [ value, ... ] template<unsigned parseFlags, typename InputStream, typename Handler> void ParseArray(InputStream& is, Handler& handler) { RAPIDJSON_ASSERT(is.Peek() == '['); is.Take(); // Skip '[' if (RAPIDJSON_UNLIKELY(!handler.StartArray())) RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); SkipWhitespaceAndComments<parseFlags>(is); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (Consume(is, ']')) { if (RAPIDJSON_UNLIKELY(!handler.EndArray(0))) // empty array RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); return; } for (SizeType elementCount = 0;;) { ParseValue<parseFlags>(is, handler); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; ++elementCount; SkipWhitespaceAndComments<parseFlags>(is); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (Consume(is, ',')) { SkipWhitespaceAndComments<parseFlags>(is); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; } else if (Consume(is, ']')) { if (RAPIDJSON_UNLIKELY(!handler.EndArray(elementCount))) RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); return; } else RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell()); if (parseFlags & kParseTrailingCommasFlag) { if (is.Peek() == ']') { if (RAPIDJSON_UNLIKELY(!handler.EndArray(elementCount))) RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); is.Take(); return; } } } } template<unsigned parseFlags, typename InputStream, typename Handler> void ParseNull(InputStream& is, Handler& handler) { RAPIDJSON_ASSERT(is.Peek() == 'n'); is.Take(); if (RAPIDJSON_LIKELY(Consume(is, 'u') && Consume(is, 'l') && Consume(is, 'l'))) { if (RAPIDJSON_UNLIKELY(!handler.Null())) RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); } else RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); } template<unsigned parseFlags, typename InputStream, typename Handler> void ParseTrue(InputStream& is, Handler& handler) { RAPIDJSON_ASSERT(is.Peek() == 't'); is.Take(); if (RAPIDJSON_LIKELY(Consume(is, 'r') && Consume(is, 'u') && Consume(is, 'e'))) { if (RAPIDJSON_UNLIKELY(!handler.Bool(true))) RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); } else RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); } template<unsigned parseFlags, typename InputStream, typename Handler> void ParseFalse(InputStream& is, Handler& handler) { RAPIDJSON_ASSERT(is.Peek() == 'f'); is.Take(); if (RAPIDJSON_LIKELY(Consume(is, 'a') && Consume(is, 'l') && Consume(is, 's') && Consume(is, 'e'))) { if (RAPIDJSON_UNLIKELY(!handler.Bool(false))) RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); } else RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); } template<typename InputStream> RAPIDJSON_FORCEINLINE static bool Consume(InputStream& is, typename InputStream::Ch expect) { if (RAPIDJSON_LIKELY(is.Peek() == expect)) { is.Take(); return true; } else return false; } // Helper function to parse four hexadecimal digits in \uXXXX in ParseString(). template<typename InputStream> unsigned ParseHex4(InputStream& is, size_t escapeOffset) { unsigned codepoint = 0; for (int i = 0; i < 4; i++) { Ch c = is.Peek(); codepoint <<= 4; codepoint += static_cast<unsigned>(c); if (c >= '0' && c <= '9') codepoint -= '0'; else if (c >= 'A' && c <= 'F') codepoint -= 'A' - 10; else if (c >= 'a' && c <= 'f') codepoint -= 'a' - 10; else { RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorStringUnicodeEscapeInvalidHex, escapeOffset); RAPIDJSON_PARSE_ERROR_EARLY_RETURN(0); } is.Take(); } return codepoint; } template <typename CharType> class StackStream { public: typedef CharType Ch; StackStream(internal::Stack<StackAllocator>& stack) : stack_(stack), length_(0) {} RAPIDJSON_FORCEINLINE void Put(Ch c) { *stack_.template Push<Ch>() = c; ++length_; } RAPIDJSON_FORCEINLINE void* Push(SizeType count) { length_ += count; return stack_.template Push<Ch>(count); } size_t Length() const { return length_; } Ch* Pop() { return stack_.template Pop<Ch>(length_); } private: StackStream(const StackStream&); StackStream& operator=(const StackStream&); internal::Stack<StackAllocator>& stack_; SizeType length_; }; // Parse string and generate String event. Different code paths for kParseInsituFlag. template<unsigned parseFlags, typename InputStream, typename Handler> void ParseString(InputStream& is, Handler& handler, bool isKey = false) { internal::StreamLocalCopy<InputStream> copy(is); InputStream& s(copy.s); RAPIDJSON_ASSERT(s.Peek() == '\"'); s.Take(); // Skip '\"' bool success = false; if (parseFlags & kParseInsituFlag) { typename InputStream::Ch *head = s.PutBegin(); ParseStringToStream<parseFlags, SourceEncoding, SourceEncoding>(s, s); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; size_t length = s.PutEnd(head) - 1; RAPIDJSON_ASSERT(length <= 0xFFFFFFFF); const typename TargetEncoding::Ch* const str = reinterpret_cast<typename TargetEncoding::Ch*>(head); success = (isKey ? handler.Key(str, SizeType(length), false) : handler.String(str, SizeType(length), false)); } else { StackStream<typename TargetEncoding::Ch> stackStream(stack_); ParseStringToStream<parseFlags, SourceEncoding, TargetEncoding>(s, stackStream); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; SizeType length = static_cast<SizeType>(stackStream.Length()) - 1; const typename TargetEncoding::Ch* const str = stackStream.Pop(); success = (isKey ? handler.Key(str, length, true) : handler.String(str, length, true)); } if (RAPIDJSON_UNLIKELY(!success)) RAPIDJSON_PARSE_ERROR(kParseErrorTermination, s.Tell()); } // Parse string to an output is // This function handles the prefix/suffix double quotes, escaping, and optional encoding validation. template<unsigned parseFlags, typename SEncoding, typename TEncoding, typename InputStream, typename OutputStream> RAPIDJSON_FORCEINLINE void ParseStringToStream(InputStream& is, OutputStream& os) { //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN #define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 static const char escape[256] = { Z16, Z16, 0, 0,'\"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '/', Z16, Z16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, 0, 0,'\b', 0, 0, 0,'\f', 0, 0, 0, 0, 0, 0, 0,'\n', 0, 0, 0,'\r', 0,'\t', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 }; #undef Z16 //!@endcond for (;;) { // Scan and copy string before "\\\"" or < 0x20. This is an optional optimzation. if (!(parseFlags & kParseValidateEncodingFlag)) ScanCopyUnescapedString(is, os); Ch c = is.Peek(); if (RAPIDJSON_UNLIKELY(c == '\\')) { // Escape size_t escapeOffset = is.Tell(); // For invalid escaping, report the initial '\\' as error offset is.Take(); Ch e = is.Peek(); if ((sizeof(Ch) == 1 || unsigned(e) < 256) && RAPIDJSON_LIKELY(escape[static_cast<unsigned char>(e)])) { is.Take(); os.Put(static_cast<typename TEncoding::Ch>(escape[static_cast<unsigned char>(e)])); } else if ((parseFlags & kParseEscapedApostropheFlag) && RAPIDJSON_LIKELY(e == '\'')) { // Allow escaped apostrophe is.Take(); os.Put('\''); } else if (RAPIDJSON_LIKELY(e == 'u')) { // Unicode is.Take(); unsigned codepoint = ParseHex4(is, escapeOffset); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (RAPIDJSON_UNLIKELY(codepoint >= 0xD800 && codepoint <= 0xDFFF)) { // high surrogate, check if followed by valid low surrogate if (RAPIDJSON_LIKELY(codepoint <= 0xDBFF)) { // Handle UTF-16 surrogate pair if (RAPIDJSON_UNLIKELY(!Consume(is, '\\') || !Consume(is, 'u'))) RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, escapeOffset); unsigned codepoint2 = ParseHex4(is, escapeOffset); RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (RAPIDJSON_UNLIKELY(codepoint2 < 0xDC00 || codepoint2 > 0xDFFF)) RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, escapeOffset); codepoint = (((codepoint - 0xD800) << 10) | (codepoint2 - 0xDC00)) + 0x10000; } // single low surrogate else { RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, escapeOffset); } } TEncoding::Encode(os, codepoint); } else RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, escapeOffset); } else if (RAPIDJSON_UNLIKELY(c == '"')) { // Closing double quote is.Take(); os.Put('\0'); // null-terminate the string return; } else if (RAPIDJSON_UNLIKELY(static_cast<unsigned>(c) < 0x20)) { // RFC 4627: unescaped = %x20-21 / %x23-5B / %x5D-10FFFF if (c == '\0') RAPIDJSON_PARSE_ERROR(kParseErrorStringMissQuotationMark, is.Tell()); else RAPIDJSON_PARSE_ERROR(kParseErrorStringInvalidEncoding, is.Tell()); } else { size_t offset = is.Tell(); if (RAPIDJSON_UNLIKELY((parseFlags & kParseValidateEncodingFlag ? !Transcoder<SEncoding, TEncoding>::Validate(is, os) : !Transcoder<SEncoding, TEncoding>::Transcode(is, os)))) RAPIDJSON_PARSE_ERROR(kParseErrorStringInvalidEncoding, offset); } } } template<typename InputStream, typename OutputStream> static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InputStream&, OutputStream&) { // Do nothing for generic version } #if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) // StringStream -> StackStream<char> static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(StringStream& is, StackStream<char>& os) { const char* p = is.src_; // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { is.src_ = p; return; } else os.Put(*p++); // The rest of string using SIMD static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0])); const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0])); const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0])); for (;; p += 16) { const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); const __m128i t1 = _mm_cmpeq_epi8(s, dq); const __m128i t2 = _mm_cmpeq_epi8(s, bs); const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x)); if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped SizeType length; #ifdef _MSC_VER // Find the index of first escaped unsigned long offset; _BitScanForward(&offset, r); length = offset; #else length = static_cast<SizeType>(__builtin_ffs(r) - 1); #endif if (length != 0) { char* q = reinterpret_cast<char*>(os.Push(length)); for (size_t i = 0; i < length; i++) q[i] = p[i]; p += length; } break; } _mm_storeu_si128(reinterpret_cast<__m128i *>(os.Push(16)), s); } is.src_ = p; } // InsituStringStream -> InsituStringStream static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InsituStringStream& is, InsituStringStream& os) { RAPIDJSON_ASSERT(&is == &os); (void)os; if (is.src_ == is.dst_) { SkipUnescapedString(is); return; } char* p = is.src_; char *q = is.dst_; // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { is.src_ = p; is.dst_ = q; return; } else *q++ = *p++; // The rest of string using SIMD static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0])); const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0])); const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0])); for (;; p += 16, q += 16) { const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); const __m128i t1 = _mm_cmpeq_epi8(s, dq); const __m128i t2 = _mm_cmpeq_epi8(s, bs); const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x)); if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped size_t length; #ifdef _MSC_VER // Find the index of first escaped unsigned long offset; _BitScanForward(&offset, r); length = offset; #else length = static_cast<size_t>(__builtin_ffs(r) - 1); #endif for (const char* pend = p + length; p != pend; ) *q++ = *p++; break; } _mm_storeu_si128(reinterpret_cast<__m128i *>(q), s); } is.src_ = p; is.dst_ = q; } // When read/write pointers are the same for insitu stream, just skip unescaped characters static RAPIDJSON_FORCEINLINE void SkipUnescapedString(InsituStringStream& is) { RAPIDJSON_ASSERT(is.src_ == is.dst_); char* p = is.src_; // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); for (; p != nextAligned; p++) if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { is.src_ = is.dst_ = p; return; } // The rest of string using SIMD static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0])); const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0])); const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0])); for (;; p += 16) { const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); const __m128i t1 = _mm_cmpeq_epi8(s, dq); const __m128i t2 = _mm_cmpeq_epi8(s, bs); const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x)); if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped size_t length; #ifdef _MSC_VER // Find the index of first escaped unsigned long offset; _BitScanForward(&offset, r); length = offset; #else length = static_cast<size_t>(__builtin_ffs(r) - 1); #endif p += length; break; } } is.src_ = is.dst_ = p; } #elif defined(RAPIDJSON_NEON) // StringStream -> StackStream<char> static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(StringStream& is, StackStream<char>& os) { const char* p = is.src_; // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { is.src_ = p; return; } else os.Put(*p++); // The rest of string using SIMD const uint8x16_t s0 = vmovq_n_u8('"'); const uint8x16_t s1 = vmovq_n_u8('\\'); const uint8x16_t s2 = vmovq_n_u8('\b'); const uint8x16_t s3 = vmovq_n_u8(32); for (;; p += 16) { const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p)); uint8x16_t x = vceqq_u8(s, s0); x = vorrq_u8(x, vceqq_u8(s, s1)); x = vorrq_u8(x, vceqq_u8(s, s2)); x = vorrq_u8(x, vcltq_u8(s, s3)); x = vrev64q_u8(x); // Rev in 64 uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract SizeType length = 0; bool escaped = false; if (low == 0) { if (high != 0) { uint32_t lz = internal::clzll(high); length = 8 + (lz >> 3); escaped = true; } } else { uint32_t lz = internal::clzll(low); length = lz >> 3; escaped = true; } if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped if (length != 0) { char* q = reinterpret_cast<char*>(os.Push(length)); for (size_t i = 0; i < length; i++) q[i] = p[i]; p += length; } break; } vst1q_u8(reinterpret_cast<uint8_t *>(os.Push(16)), s); } is.src_ = p; } // InsituStringStream -> InsituStringStream static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InsituStringStream& is, InsituStringStream& os) { RAPIDJSON_ASSERT(&is == &os); (void)os; if (is.src_ == is.dst_) { SkipUnescapedString(is); return; } char* p = is.src_; char *q = is.dst_; // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { is.src_ = p; is.dst_ = q; return; } else *q++ = *p++; // The rest of string using SIMD const uint8x16_t s0 = vmovq_n_u8('"'); const uint8x16_t s1 = vmovq_n_u8('\\'); const uint8x16_t s2 = vmovq_n_u8('\b'); const uint8x16_t s3 = vmovq_n_u8(32); for (;; p += 16, q += 16) { const uint8x16_t s = vld1q_u8(reinterpret_cast<uint8_t *>(p)); uint8x16_t x = vceqq_u8(s, s0); x = vorrq_u8(x, vceqq_u8(s, s1)); x = vorrq_u8(x, vceqq_u8(s, s2)); x = vorrq_u8(x, vcltq_u8(s, s3)); x = vrev64q_u8(x); // Rev in 64 uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract SizeType length = 0; bool escaped = false; if (low == 0) { if (high != 0) { uint32_t lz = internal::clzll(high); length = 8 + (lz >> 3); escaped = true; } } else { uint32_t lz = internal::clzll(low); length = lz >> 3; escaped = true; } if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped for (const char* pend = p + length; p != pend; ) { *q++ = *p++; } break; } vst1q_u8(reinterpret_cast<uint8_t *>(q), s); } is.src_ = p; is.dst_ = q; } // When read/write pointers are the same for insitu stream, just skip unescaped characters static RAPIDJSON_FORCEINLINE void SkipUnescapedString(InsituStringStream& is) { RAPIDJSON_ASSERT(is.src_ == is.dst_); char* p = is.src_; // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); for (; p != nextAligned; p++) if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { is.src_ = is.dst_ = p; return; } // The rest of string using SIMD const uint8x16_t s0 = vmovq_n_u8('"'); const uint8x16_t s1 = vmovq_n_u8('\\'); const uint8x16_t s2 = vmovq_n_u8('\b'); const uint8x16_t s3 = vmovq_n_u8(32); for (;; p += 16) { const uint8x16_t s = vld1q_u8(reinterpret_cast<uint8_t *>(p)); uint8x16_t x = vceqq_u8(s, s0); x = vorrq_u8(x, vceqq_u8(s, s1)); x = vorrq_u8(x, vceqq_u8(s, s2)); x = vorrq_u8(x, vcltq_u8(s, s3)); x = vrev64q_u8(x); // Rev in 64 uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract if (low == 0) { if (high != 0) { uint32_t lz = internal::clzll(high); p += 8 + (lz >> 3); break; } } else { uint32_t lz = internal::clzll(low); p += lz >> 3; break; } } is.src_ = is.dst_ = p; } #endif // RAPIDJSON_NEON template<typename InputStream, bool backup, bool pushOnTake> class NumberStream; template<typename InputStream> class NumberStream<InputStream, false, false> { public: typedef typename InputStream::Ch Ch; NumberStream(GenericReader& reader, InputStream& s) : is(s) { (void)reader; } RAPIDJSON_FORCEINLINE Ch Peek() const { return is.Peek(); } RAPIDJSON_FORCEINLINE Ch TakePush() { return is.Take(); } RAPIDJSON_FORCEINLINE Ch Take() { return is.Take(); } RAPIDJSON_FORCEINLINE void Push(char) {} size_t Tell() { return is.Tell(); } size_t Length() { return 0; } const char* Pop() { return 0; } protected: NumberStream& operator=(const NumberStream&); InputStream& is; }; template<typename InputStream> class NumberStream<InputStream, true, false> : public NumberStream<InputStream, false, false> { typedef NumberStream<InputStream, false, false> Base; public: NumberStream(GenericReader& reader, InputStream& is) : Base(reader, is), stackStream(reader.stack_) {} RAPIDJSON_FORCEINLINE Ch TakePush() { stackStream.Put(static_cast<char>(Base::is.Peek())); return Base::is.Take(); } RAPIDJSON_FORCEINLINE void Push(char c) { stackStream.Put(c); } size_t Length() { return stackStream.Length(); } const char* Pop() { stackStream.Put('\0'); return stackStream.Pop(); } private: StackStream<char> stackStream; }; template<typename InputStream> class NumberStream<InputStream, true, true> : public NumberStream<InputStream, true, false> { typedef NumberStream<InputStream, true, false> Base; public: NumberStream(GenericReader& reader, InputStream& is) : Base(reader, is) {} RAPIDJSON_FORCEINLINE Ch Take() { return Base::TakePush(); } }; template<unsigned parseFlags, typename InputStream, typename Handler> void ParseNumber(InputStream& is, Handler& handler) { internal::StreamLocalCopy<InputStream> copy(is); NumberStream<InputStream, ((parseFlags & kParseNumbersAsStringsFlag) != 0) ? ((parseFlags & kParseInsituFlag) == 0) : ((parseFlags & kParseFullPrecisionFlag) != 0), (parseFlags & kParseNumbersAsStringsFlag) != 0 && (parseFlags & kParseInsituFlag) == 0> s(*this, copy.s); size_t startOffset = s.Tell(); double d = 0.0; bool useNanOrInf = false; // Parse minus bool minus = Consume(s, '-'); // Parse int: zero / ( digit1-9 *DIGIT ) unsigned i = 0; uint64_t i64 = 0; bool use64bit = false; int significandDigit = 0; if (RAPIDJSON_UNLIKELY(s.Peek() == '0')) { i = 0; s.TakePush(); } else if (RAPIDJSON_LIKELY(s.Peek() >= '1' && s.Peek() <= '9')) { i = static_cast<unsigned>(s.TakePush() - '0'); if (minus) while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { if (RAPIDJSON_UNLIKELY(i >= 214748364)) { // 2^31 = 2147483648 if (RAPIDJSON_LIKELY(i != 214748364 || s.Peek() > '8')) { i64 = i; use64bit = true; break; } } i = i * 10 + static_cast<unsigned>(s.TakePush() - '0'); significandDigit++; } else while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { if (RAPIDJSON_UNLIKELY(i >= 429496729)) { // 2^32 - 1 = 4294967295 if (RAPIDJSON_LIKELY(i != 429496729 || s.Peek() > '5')) { i64 = i; use64bit = true; break; } } i = i * 10 + static_cast<unsigned>(s.TakePush() - '0'); significandDigit++; } } // Parse NaN or Infinity here else if ((parseFlags & kParseNanAndInfFlag) && RAPIDJSON_LIKELY((s.Peek() == 'I' || s.Peek() == 'N'))) { if (Consume(s, 'N')) { if (Consume(s, 'a') && Consume(s, 'N')) { d = std::numeric_limits<double>::quiet_NaN(); useNanOrInf = true; } } else if (RAPIDJSON_LIKELY(Consume(s, 'I'))) { if (Consume(s, 'n') && Consume(s, 'f')) { d = (minus ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity()); useNanOrInf = true; if (RAPIDJSON_UNLIKELY(s.Peek() == 'i' && !(Consume(s, 'i') && Consume(s, 'n') && Consume(s, 'i') && Consume(s, 't') && Consume(s, 'y')))) { RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); } } } if (RAPIDJSON_UNLIKELY(!useNanOrInf)) { RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); } } else RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); // Parse 64bit int bool useDouble = false; if (use64bit) { if (minus) while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { if (RAPIDJSON_UNLIKELY(i64 >= RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC))) // 2^63 = 9223372036854775808 if (RAPIDJSON_LIKELY(i64 != RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC) || s.Peek() > '8')) { d = static_cast<double>(i64); useDouble = true; break; } i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0'); significandDigit++; } else while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { if (RAPIDJSON_UNLIKELY(i64 >= RAPIDJSON_UINT64_C2(0x19999999, 0x99999999))) // 2^64 - 1 = 18446744073709551615 if (RAPIDJSON_LIKELY(i64 != RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || s.Peek() > '5')) { d = static_cast<double>(i64); useDouble = true; break; } i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0'); significandDigit++; } } // Force double for big integer if (useDouble) { while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { d = d * 10 + (s.TakePush() - '0'); } } // Parse frac = decimal-point 1*DIGIT int expFrac = 0; size_t decimalPosition; if (Consume(s, '.')) { decimalPosition = s.Length(); if (RAPIDJSON_UNLIKELY(!(s.Peek() >= '0' && s.Peek() <= '9'))) RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissFraction, s.Tell()); if (!useDouble) { #if RAPIDJSON_64BIT // Use i64 to store significand in 64-bit architecture if (!use64bit) i64 = i; while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { if (i64 > RAPIDJSON_UINT64_C2(0x1FFFFF, 0xFFFFFFFF)) // 2^53 - 1 for fast path break; else { i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0'); --expFrac; if (i64 != 0) significandDigit++; } } d = static_cast<double>(i64); #else // Use double to store significand in 32-bit architecture d = static_cast<double>(use64bit ? i64 : i); #endif useDouble = true; } while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { if (significandDigit < 17) { d = d * 10.0 + (s.TakePush() - '0'); --expFrac; if (RAPIDJSON_LIKELY(d > 0.0)) significandDigit++; } else s.TakePush(); } } else decimalPosition = s.Length(); // decimal position at the end of integer. // Parse exp = e [ minus / plus ] 1*DIGIT int exp = 0; if (Consume(s, 'e') || Consume(s, 'E')) { if (!useDouble) { d = static_cast<double>(use64bit ? i64 : i); useDouble = true; } bool expMinus = false; if (Consume(s, '+')) ; else if (Consume(s, '-')) expMinus = true; if (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { exp = static_cast<int>(s.Take() - '0'); if (expMinus) { // (exp + expFrac) must not underflow int => we're detecting when -exp gets // dangerously close to INT_MIN (a pessimistic next digit 9 would push it into // underflow territory): // // -(exp * 10 + 9) + expFrac >= INT_MIN // <=> exp <= (expFrac - INT_MIN - 9) / 10 RAPIDJSON_ASSERT(expFrac <= 0); int maxExp = (expFrac + 2147483639) / 10; while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { exp = exp * 10 + static_cast<int>(s.Take() - '0'); if (RAPIDJSON_UNLIKELY(exp > maxExp)) { while (RAPIDJSON_UNLIKELY(s.Peek() >= '0' && s.Peek() <= '9')) // Consume the rest of exponent s.Take(); } } } else { // positive exp int maxExp = 308 - expFrac; while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { exp = exp * 10 + static_cast<int>(s.Take() - '0'); if (RAPIDJSON_UNLIKELY(exp > maxExp)) RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset); } } } else RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissExponent, s.Tell()); if (expMinus) exp = -exp; } // Finish parsing, call event according to the type of number. bool cont = true; if (parseFlags & kParseNumbersAsStringsFlag) { if (parseFlags & kParseInsituFlag) { s.Pop(); // Pop stack no matter if it will be used or not. typename InputStream::Ch* head = is.PutBegin(); const size_t length = s.Tell() - startOffset; RAPIDJSON_ASSERT(length <= 0xFFFFFFFF); // unable to insert the \0 character here, it will erase the comma after this number const typename TargetEncoding::Ch* const str = reinterpret_cast<typename TargetEncoding::Ch*>(head); cont = handler.RawNumber(str, SizeType(length), false); } else { SizeType numCharsToCopy = static_cast<SizeType>(s.Length()); StringStream srcStream(s.Pop()); StackStream<typename TargetEncoding::Ch> dstStream(stack_); while (numCharsToCopy--) { Transcoder<UTF8<>, TargetEncoding>::Transcode(srcStream, dstStream); } dstStream.Put('\0'); const typename TargetEncoding::Ch* str = dstStream.Pop(); const SizeType length = static_cast<SizeType>(dstStream.Length()) - 1; cont = handler.RawNumber(str, SizeType(length), true); } } else { size_t length = s.Length(); const char* decimal = s.Pop(); // Pop stack no matter if it will be used or not. if (useDouble) { int p = exp + expFrac; if (parseFlags & kParseFullPrecisionFlag) d = internal::StrtodFullPrecision(d, p, decimal, length, decimalPosition, exp); else d = internal::StrtodNormalPrecision(d, p); // Use > max, instead of == inf, to fix bogus warning -Wfloat-equal if (d > (std::numeric_limits<double>::max)()) { // Overflow // TODO: internal::StrtodX should report overflow (or underflow) RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset); } cont = handler.Double(minus ? -d : d); } else if (useNanOrInf) { cont = handler.Double(d); } else { if (use64bit) { if (minus) cont = handler.Int64(static_cast<int64_t>(~i64 + 1)); else cont = handler.Uint64(i64); } else { if (minus) cont = handler.Int(static_cast<int32_t>(~i + 1)); else cont = handler.Uint(i); } } } if (RAPIDJSON_UNLIKELY(!cont)) RAPIDJSON_PARSE_ERROR(kParseErrorTermination, startOffset); } // Parse any JSON value template<unsigned parseFlags, typename InputStream, typename Handler> void ParseValue(InputStream& is, Handler& handler) { switch (is.Peek()) { case 'n': ParseNull <parseFlags>(is, handler); break; case 't': ParseTrue <parseFlags>(is, handler); break; case 'f': ParseFalse <parseFlags>(is, handler); break; case '"': ParseString<parseFlags>(is, handler); break; case '{': ParseObject<parseFlags>(is, handler); break; case '[': ParseArray <parseFlags>(is, handler); break; default : ParseNumber<parseFlags>(is, handler); break; } } // Iterative Parsing // States enum IterativeParsingState { IterativeParsingFinishState = 0, // sink states at top IterativeParsingErrorState, // sink states at top IterativeParsingStartState, // Object states IterativeParsingObjectInitialState, IterativeParsingMemberKeyState, IterativeParsingMemberValueState, IterativeParsingObjectFinishState, // Array states IterativeParsingArrayInitialState, IterativeParsingElementState, IterativeParsingArrayFinishState, // Single value state IterativeParsingValueState, // Delimiter states (at bottom) IterativeParsingElementDelimiterState, IterativeParsingMemberDelimiterState, IterativeParsingKeyValueDelimiterState, cIterativeParsingStateCount }; // Tokens enum Token { LeftBracketToken = 0, RightBracketToken, LeftCurlyBracketToken, RightCurlyBracketToken, CommaToken, ColonToken, StringToken, FalseToken, TrueToken, NullToken, NumberToken, kTokenCount }; RAPIDJSON_FORCEINLINE Token Tokenize(Ch c) const { //!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN #define N NumberToken #define N16 N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N // Maps from ASCII to Token static const unsigned char tokenMap[256] = { N16, // 00~0F N16, // 10~1F N, N, StringToken, N, N, N, N, N, N, N, N, N, CommaToken, N, N, N, // 20~2F N, N, N, N, N, N, N, N, N, N, ColonToken, N, N, N, N, N, // 30~3F N16, // 40~4F N, N, N, N, N, N, N, N, N, N, N, LeftBracketToken, N, RightBracketToken, N, N, // 50~5F N, N, N, N, N, N, FalseToken, N, N, N, N, N, N, N, NullToken, N, // 60~6F N, N, N, N, TrueToken, N, N, N, N, N, N, LeftCurlyBracketToken, N, RightCurlyBracketToken, N, N, // 70~7F N16, N16, N16, N16, N16, N16, N16, N16 // 80~FF }; #undef N #undef N16 //!@endcond if (sizeof(Ch) == 1 || static_cast<unsigned>(c) < 256) return static_cast<Token>(tokenMap[static_cast<unsigned char>(c)]); else return NumberToken; } RAPIDJSON_FORCEINLINE IterativeParsingState Predict(IterativeParsingState state, Token token) const { // current state x one lookahead token -> new state static const char G[cIterativeParsingStateCount][kTokenCount] = { // Finish(sink state) { IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState }, // Error(sink state) { IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState }, // Start { IterativeParsingArrayInitialState, // Left bracket IterativeParsingErrorState, // Right bracket IterativeParsingObjectInitialState, // Left curly bracket IterativeParsingErrorState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingErrorState, // Colon IterativeParsingValueState, // String IterativeParsingValueState, // False IterativeParsingValueState, // True IterativeParsingValueState, // Null IterativeParsingValueState // Number }, // ObjectInitial { IterativeParsingErrorState, // Left bracket IterativeParsingErrorState, // Right bracket IterativeParsingErrorState, // Left curly bracket IterativeParsingObjectFinishState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingErrorState, // Colon IterativeParsingMemberKeyState, // String IterativeParsingErrorState, // False IterativeParsingErrorState, // True IterativeParsingErrorState, // Null IterativeParsingErrorState // Number }, // MemberKey { IterativeParsingErrorState, // Left bracket IterativeParsingErrorState, // Right bracket IterativeParsingErrorState, // Left curly bracket IterativeParsingErrorState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingKeyValueDelimiterState, // Colon IterativeParsingErrorState, // String IterativeParsingErrorState, // False IterativeParsingErrorState, // True IterativeParsingErrorState, // Null IterativeParsingErrorState // Number }, // MemberValue { IterativeParsingErrorState, // Left bracket IterativeParsingErrorState, // Right bracket IterativeParsingErrorState, // Left curly bracket IterativeParsingObjectFinishState, // Right curly bracket IterativeParsingMemberDelimiterState, // Comma IterativeParsingErrorState, // Colon IterativeParsingErrorState, // String IterativeParsingErrorState, // False IterativeParsingErrorState, // True IterativeParsingErrorState, // Null IterativeParsingErrorState // Number }, // ObjectFinish(sink state) { IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState }, // ArrayInitial { IterativeParsingArrayInitialState, // Left bracket(push Element state) IterativeParsingArrayFinishState, // Right bracket IterativeParsingObjectInitialState, // Left curly bracket(push Element state) IterativeParsingErrorState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingErrorState, // Colon IterativeParsingElementState, // String IterativeParsingElementState, // False IterativeParsingElementState, // True IterativeParsingElementState, // Null IterativeParsingElementState // Number }, // Element { IterativeParsingErrorState, // Left bracket IterativeParsingArrayFinishState, // Right bracket IterativeParsingErrorState, // Left curly bracket IterativeParsingErrorState, // Right curly bracket IterativeParsingElementDelimiterState, // Comma IterativeParsingErrorState, // Colon IterativeParsingErrorState, // String IterativeParsingErrorState, // False IterativeParsingErrorState, // True IterativeParsingErrorState, // Null IterativeParsingErrorState // Number }, // ArrayFinish(sink state) { IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState }, // Single Value (sink state) { IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState }, // ElementDelimiter { IterativeParsingArrayInitialState, // Left bracket(push Element state) IterativeParsingArrayFinishState, // Right bracket IterativeParsingObjectInitialState, // Left curly bracket(push Element state) IterativeParsingErrorState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingErrorState, // Colon IterativeParsingElementState, // String IterativeParsingElementState, // False IterativeParsingElementState, // True IterativeParsingElementState, // Null IterativeParsingElementState // Number }, // MemberDelimiter { IterativeParsingErrorState, // Left bracket IterativeParsingErrorState, // Right bracket IterativeParsingErrorState, // Left curly bracket IterativeParsingObjectFinishState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingErrorState, // Colon IterativeParsingMemberKeyState, // String IterativeParsingErrorState, // False IterativeParsingErrorState, // True IterativeParsingErrorState, // Null IterativeParsingErrorState // Number }, // KeyValueDelimiter { IterativeParsingArrayInitialState, // Left bracket(push MemberValue state) IterativeParsingErrorState, // Right bracket IterativeParsingObjectInitialState, // Left curly bracket(push MemberValue state) IterativeParsingErrorState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingErrorState, // Colon IterativeParsingMemberValueState, // String IterativeParsingMemberValueState, // False IterativeParsingMemberValueState, // True IterativeParsingMemberValueState, // Null IterativeParsingMemberValueState // Number }, }; // End of G return static_cast<IterativeParsingState>(G[state][token]); } // Make an advance in the token stream and state based on the candidate destination state which was returned by Transit(). // May return a new state on state pop. template <unsigned parseFlags, typename InputStream, typename Handler> RAPIDJSON_FORCEINLINE IterativeParsingState Transit(IterativeParsingState src, Token token, IterativeParsingState dst, InputStream& is, Handler& handler) { (void)token; switch (dst) { case IterativeParsingErrorState: return dst; case IterativeParsingObjectInitialState: case IterativeParsingArrayInitialState: { // Push the state(Element or MemeberValue) if we are nested in another array or value of member. // In this way we can get the correct state on ObjectFinish or ArrayFinish by frame pop. IterativeParsingState n = src; if (src == IterativeParsingArrayInitialState || src == IterativeParsingElementDelimiterState) n = IterativeParsingElementState; else if (src == IterativeParsingKeyValueDelimiterState) n = IterativeParsingMemberValueState; // Push current state. *stack_.template Push<SizeType>(1) = n; // Initialize and push the member/element count. *stack_.template Push<SizeType>(1) = 0; // Call handler bool hr = (dst == IterativeParsingObjectInitialState) ? handler.StartObject() : handler.StartArray(); // On handler short circuits the parsing. if (!hr) { RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); return IterativeParsingErrorState; } else { is.Take(); return dst; } } case IterativeParsingMemberKeyState: ParseString<parseFlags>(is, handler, true); if (HasParseError()) return IterativeParsingErrorState; else return dst; case IterativeParsingKeyValueDelimiterState: RAPIDJSON_ASSERT(token == ColonToken); is.Take(); return dst; case IterativeParsingMemberValueState: // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state. ParseValue<parseFlags>(is, handler); if (HasParseError()) { return IterativeParsingErrorState; } return dst; case IterativeParsingElementState: // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state. ParseValue<parseFlags>(is, handler); if (HasParseError()) { return IterativeParsingErrorState; } return dst; case IterativeParsingMemberDelimiterState: case IterativeParsingElementDelimiterState: is.Take(); // Update member/element count. *stack_.template Top<SizeType>() = *stack_.template Top<SizeType>() + 1; return dst; case IterativeParsingObjectFinishState: { // Transit from delimiter is only allowed when trailing commas are enabled if (!(parseFlags & kParseTrailingCommasFlag) && src == IterativeParsingMemberDelimiterState) { RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorObjectMissName, is.Tell()); return IterativeParsingErrorState; } // Get member count. SizeType c = *stack_.template Pop<SizeType>(1); // If the object is not empty, count the last member. if (src == IterativeParsingMemberValueState) ++c; // Restore the state. IterativeParsingState n = static_cast<IterativeParsingState>(*stack_.template Pop<SizeType>(1)); // Transit to Finish state if this is the topmost scope. if (n == IterativeParsingStartState) n = IterativeParsingFinishState; // Call handler bool hr = handler.EndObject(c); // On handler short circuits the parsing. if (!hr) { RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); return IterativeParsingErrorState; } else { is.Take(); return n; } } case IterativeParsingArrayFinishState: { // Transit from delimiter is only allowed when trailing commas are enabled if (!(parseFlags & kParseTrailingCommasFlag) && src == IterativeParsingElementDelimiterState) { RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorValueInvalid, is.Tell()); return IterativeParsingErrorState; } // Get element count. SizeType c = *stack_.template Pop<SizeType>(1); // If the array is not empty, count the last element. if (src == IterativeParsingElementState) ++c; // Restore the state. IterativeParsingState n = static_cast<IterativeParsingState>(*stack_.template Pop<SizeType>(1)); // Transit to Finish state if this is the topmost scope. if (n == IterativeParsingStartState) n = IterativeParsingFinishState; // Call handler bool hr = handler.EndArray(c); // On handler short circuits the parsing. if (!hr) { RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); return IterativeParsingErrorState; } else { is.Take(); return n; } } default: // This branch is for IterativeParsingValueState actually. // Use `default:` rather than // `case IterativeParsingValueState:` is for code coverage. // The IterativeParsingStartState is not enumerated in this switch-case. // It is impossible for that case. And it can be caught by following assertion. // The IterativeParsingFinishState is not enumerated in this switch-case either. // It is a "derivative" state which cannot triggered from Predict() directly. // Therefore it cannot happen here. And it can be caught by following assertion. RAPIDJSON_ASSERT(dst == IterativeParsingValueState); // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state. ParseValue<parseFlags>(is, handler); if (HasParseError()) { return IterativeParsingErrorState; } return IterativeParsingFinishState; } } template <typename InputStream> void HandleError(IterativeParsingState src, InputStream& is) { if (HasParseError()) { // Error flag has been set. return; } switch (src) { case IterativeParsingStartState: RAPIDJSON_PARSE_ERROR(kParseErrorDocumentEmpty, is.Tell()); return; case IterativeParsingFinishState: RAPIDJSON_PARSE_ERROR(kParseErrorDocumentRootNotSingular, is.Tell()); return; case IterativeParsingObjectInitialState: case IterativeParsingMemberDelimiterState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell()); return; case IterativeParsingMemberKeyState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell()); return; case IterativeParsingMemberValueState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell()); return; case IterativeParsingKeyValueDelimiterState: case IterativeParsingArrayInitialState: case IterativeParsingElementDelimiterState: RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); return; default: RAPIDJSON_ASSERT(src == IterativeParsingElementState); RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell()); return; } } RAPIDJSON_FORCEINLINE bool IsIterativeParsingDelimiterState(IterativeParsingState s) const { return s >= IterativeParsingElementDelimiterState; } RAPIDJSON_FORCEINLINE bool IsIterativeParsingCompleteState(IterativeParsingState s) const { return s <= IterativeParsingErrorState; } template <unsigned parseFlags, typename InputStream, typename Handler> ParseResult IterativeParse(InputStream& is, Handler& handler) { parseResult_.Clear(); ClearStackOnExit scope(*this); IterativeParsingState state = IterativeParsingStartState; SkipWhitespaceAndComments<parseFlags>(is); RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); while (is.Peek() != '\0') { Token t = Tokenize(is.Peek()); IterativeParsingState n = Predict(state, t); IterativeParsingState d = Transit<parseFlags>(state, t, n, is, handler); if (d == IterativeParsingErrorState) { HandleError(state, is); break; } state = d; // Do not further consume streams if a root JSON has been parsed. if ((parseFlags & kParseStopWhenDoneFlag) && state == IterativeParsingFinishState) break; SkipWhitespaceAndComments<parseFlags>(is); RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); } // Handle the end of file. if (state != IterativeParsingFinishState) HandleError(state, is); return parseResult_; } static const size_t kDefaultStackCapacity = 256; //!< Default stack capacity in bytes for storing a single decoded string. internal::Stack<StackAllocator> stack_; //!< A stack for storing decoded string temporarily during non-destructive parsing. ParseResult parseResult_; IterativeParsingState state_; }; // class GenericReader //! Reader with UTF8 encoding and default allocator. typedef GenericReader<UTF8<>, UTF8<> > Reader; RAPIDJSON_NAMESPACE_END #if defined(__clang__) || defined(_MSC_VER) RAPIDJSON_DIAG_POP #endif #ifdef __GNUC__ RAPIDJSON_DIAG_POP #endif #endif // RAPIDJSON_READER_H_
93,838
reader
h
en
c
code
{"qsc_code_num_words": 8976, "qsc_code_num_chars": 93838.0, "qsc_code_mean_word_length": 5.7921123, "qsc_code_frac_words_unique": 0.09993316, "qsc_code_frac_chars_top_2grams": 0.02558184, "qsc_code_frac_chars_top_3grams": 0.03289094, "qsc_code_frac_chars_top_4grams": 0.00384689, "qsc_code_frac_chars_dupe_5grams": 0.58792075, "qsc_code_frac_chars_dupe_6grams": 0.54645124, "qsc_code_frac_chars_dupe_7grams": 0.50013464, "qsc_code_frac_chars_dupe_8grams": 0.46737834, "qsc_code_frac_chars_dupe_9grams": 0.44539334, "qsc_code_frac_chars_dupe_10grams": 0.42173495, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02772148, "qsc_code_frac_chars_whitespace": 0.31650291, "qsc_code_size_file_byte": 93838.0, "qsc_code_num_lines": 2244.0, "qsc_code_num_chars_line_max": 224.0, "qsc_code_num_chars_line_mean": 41.81729055, "qsc_code_frac_chars_alphabet": 0.78287443, "qsc_code_frac_chars_comments": 0.18992306, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.50202977, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00814302, "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.00509103, "qsc_code_frac_lines_prompt_comments": 0.00044563, "qsc_code_frac_lines_assert": 0.01217862, "qsc_codec_frac_lines_func_ratio": 0.07645467, "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.12449256, "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}
000haoji/deep-student
src/components/KnowledgeBaseManagement.css
/* Knowledge Base Management 组件专用样式 */ .knowledge-base-container { min-height: 100vh; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); position: relative; overflow-x: hidden; overflow-y: auto; transition: all 0.3s ease; } .knowledge-base-container.drag-over { background: linear-gradient(135deg, #4299e1 0%, #3182ce 100%); box-shadow: inset 0 0 50px rgba(66, 153, 225, 0.3); } /* 拖拽覆盖层 */ .kb-drag-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(66, 153, 225, 0.9); backdrop-filter: blur(10px); display: flex; align-items: center; justify-content: center; z-index: 1000; animation: fadeIn 0.3s ease; } .kb-drag-overlay-content { text-align: center; color: white; padding: 3rem; border-radius: 20px; background: rgba(255, 255, 255, 0.1); border: 2px dashed rgba(255, 255, 255, 0.5); backdrop-filter: blur(20px); box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2); } .kb-drag-icon { font-size: 4rem; margin-bottom: 1rem; animation: bounce 1s infinite; } .kb-drag-title { font-size: 2rem; font-weight: 700; margin-bottom: 0.5rem; text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3); } .kb-drag-subtitle { font-size: 1.25rem; opacity: 0.9; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @keyframes bounce { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-10px); } } /* 背景装饰效果 */ .knowledge-base-container::before { content: ''; position: absolute; top: -40%; right: -40%; width: 80%; height: 80%; background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 50%, transparent 70%); border-radius: 50%; animation: float 20s infinite ease-in-out; } .knowledge-base-container::after { content: ''; position: absolute; bottom: -40%; left: -40%; width: 80%; height: 80%; background: radial-gradient(circle, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0.03) 50%, transparent 70%); border-radius: 50%; animation: float 25s infinite ease-in-out reverse; } @keyframes float { 0%, 100% { transform: translate(0, 0) rotate(0deg); } 33% { transform: translate(30px, -30px) rotate(120deg); } 66% { transform: translate(-20px, 20px) rotate(240deg); } } .knowledge-base-content { position: relative; z-index: 1; max-width: 1200px; margin: 0 auto; padding: 2rem; min-height: calc(100vh - 4rem); display: flex; flex-direction: column; } /* 页面标题区域 */ .kb-header { text-align: center; margin-bottom: 3rem; } .kb-title-icon { display: inline-flex; align-items: center; justify-content: center; width: 80px; height: 80px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 20px; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); margin-bottom: 1.5rem; transition: transform 0.3s ease; } .kb-title-icon:hover { transform: scale(1.05); } .kb-title-icon span { font-size: 2rem; } .kb-title { font-size: 3rem; font-weight: 800; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; margin-bottom: 1rem; } .kb-subtitle { font-size: 1.25rem; color: #ffffff; text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3); max-width: 600px; margin: 0 auto; line-height: 1.6; opacity: 0.9; } /* 统计卡片 */ .kb-stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 2rem; margin-bottom: 3rem; } .kb-stat-card { background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(20px); border-radius: 20px; padding: 2rem; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); transition: all 0.3s ease; position: relative; overflow: hidden; } .kb-stat-card::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(135deg, transparent 0%, rgba(255, 255, 255, 0.1) 100%); opacity: 0; transition: opacity 0.3s ease; } .kb-stat-card:hover { transform: translateY(-8px); box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15); } .kb-stat-card:hover::before { opacity: 1; } .kb-stat-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem; } .kb-stat-icon { width: 60px; height: 60px; border-radius: 15px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; color: white; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); } .kb-stat-icon.blue { background: linear-gradient(135deg, #4299e1, #3182ce); } .kb-stat-icon.green { background: linear-gradient(135deg, #48bb78, #38a169); } .kb-stat-icon.purple { background: linear-gradient(135deg, #9f7aea, #805ad5); } .kb-stat-icon.orange { background: linear-gradient(135deg, #ed8936, #dd6b20); } .kb-stat-value { font-size: 2.5rem; font-weight: 800; color: #2d3748; margin-bottom: 0.5rem; } .kb-stat-label { font-size: 0.9rem; color: #4a5568; font-weight: 500; } .kb-stat-progress { width: 100%; height: 6px; background: #e2e8f0; border-radius: 3px; margin-top: 1rem; overflow: hidden; } .kb-stat-progress-bar { height: 100%; background: linear-gradient(90deg, #4299e1, #3182ce); border-radius: 3px; transition: width 1s ease; } .kb-stat-status { display: flex; align-items: center; gap: 0.5rem; margin-top: 0.75rem; font-size: 0.8rem; color: #4a5568; } .kb-status-dot { width: 8px; height: 8px; border-radius: 50%; animation: pulse 2s infinite; } .kb-status-dot.green { background: #48bb78; } .kb-status-dot.red { background: #f56565; } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } } /* 上传区域 */ .kb-upload-section { background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(20px); border-radius: 20px; padding: 2.5rem; margin-bottom: 3rem; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); } .kb-upload-header { display: flex; align-items: center; gap: 1rem; margin-bottom: 2rem; } .kb-upload-icon { width: 60px; height: 60px; background: linear-gradient(135deg, #48bb78, #38a169); border-radius: 15px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; color: white; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); } .kb-upload-title { font-size: 1.5rem; font-weight: 700; color: #2d3748; margin-bottom: 0.25rem; } .kb-upload-subtitle { color: #718096; font-size: 0.9rem; } .kb-format-tags { display: flex; flex-wrap: wrap; gap: 0.75rem; margin-bottom: 2rem; } .kb-format-tag { display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.5rem 1rem; border-radius: 25px; font-size: 0.85rem; font-weight: 600; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; cursor: pointer; } .kb-format-tag:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); } .kb-format-tag.txt { background: linear-gradient(135deg, #e3f2fd, #bbdefb); color: #1565c0; } .kb-format-tag.md { background: linear-gradient(135deg, #e8f5e8, #c8e6c9); color: #2e7d32; } .kb-format-tag.pdf { background: linear-gradient(135deg, #ffebee, #ffcdd2); color: #c62828; } .kb-format-tag.docx { background: linear-gradient(135deg, #f3e5f5, #e1bee7); color: #7b1fa2; } .kb-upload-zone { border: 3px dashed #cbd5e0; border-radius: 20px; padding: 3rem; text-align: center; background: linear-gradient(135deg, #f7fafc, #edf2f7); transition: all 0.3s ease; cursor: pointer; position: relative; overflow: hidden; } .kb-upload-zone::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(135deg, rgba(66, 153, 225, 0.1), rgba(129, 140, 248, 0.1)); opacity: 0; transition: opacity 0.3s ease; } .kb-upload-zone:hover { border-color: #4299e1; background: linear-gradient(135deg, #ebf8ff, #e6fffa); transform: scale(1.02); } .kb-upload-zone:hover::before { opacity: 1; } .kb-upload-zone-icon { width: 80px; height: 80px; background: linear-gradient(135deg, #4299e1, #3182ce); border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 2rem; color: white; margin: 0 auto 1.5rem; box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1); transition: transform 0.3s ease; } .kb-upload-zone:hover .kb-upload-zone-icon { transform: scale(1.1) rotate(5deg); } .kb-upload-zone-title { font-size: 1.25rem; font-weight: 600; color: #2d3748; margin-bottom: 0.5rem; } .kb-upload-zone-subtitle { color: #718096; margin-bottom: 1.5rem; } .kb-upload-zone-button { display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.75rem 1.5rem; background: linear-gradient(135deg, #4299e1, #3182ce); color: white; border: none; border-radius: 12px; font-weight: 600; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); } .kb-upload-zone-button:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15); } /* 选中文件列表 */ .kb-selected-files { background: linear-gradient(135deg, #f0fff4, #e6fffa); border-radius: 20px; padding: 1.5rem; margin-top: 2rem; border: 2px solid #48bb78; } .kb-selected-header { display: flex; align-items: center; gap: 0.75rem; margin-bottom: 1.5rem; } .kb-selected-icon { width: 32px; height: 32px; background: linear-gradient(135deg, #48bb78, #38a169); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-size: 0.9rem; font-weight: bold; } .kb-selected-title { font-size: 1.1rem; font-weight: 600; color: #22543d; } .kb-selected-badge { margin-left: auto; padding: 0.25rem 0.75rem; background: #c6f6d5; color: #22543d; border-radius: 12px; font-size: 0.8rem; font-weight: 600; } .kb-file-list { display: grid; gap: 1rem; } .kb-file-item { background: rgba(255, 255, 255, 0.8); backdrop-filter: blur(10px); border-radius: 12px; padding: 1rem; display: flex; align-items: center; gap: 1rem; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); border: 1px solid rgba(255, 255, 255, 0.3); transition: all 0.3s ease; } .kb-file-item:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); } .kb-file-icon { width: 48px; height: 48px; background: linear-gradient(135deg, #4299e1, #3182ce); border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; color: white; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); } .kb-file-info { flex: 1; min-width: 0; } .kb-file-name { font-weight: 600; color: #2d3748; margin-bottom: 0.25rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .kb-file-meta { display: flex; gap: 0.75rem; } .kb-file-size { font-size: 0.8rem; color: #718096; background: #e2e8f0; padding: 0.25rem 0.5rem; border-radius: 6px; } .kb-file-status { font-size: 0.8rem; color: #22543d; background: #c6f6d5; padding: 0.25rem 0.5rem; border-radius: 6px; font-weight: 600; } .kb-file-check { width: 32px; height: 32px; background: #c6f6d5; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #22543d; font-size: 0.9rem; font-weight: bold; } /* 操作按钮 */ .kb-action-buttons { display: flex; flex-wrap: wrap; gap: 1rem; margin-top: 2rem; } .kb-button { display: inline-flex; align-items: center; gap: 0.75rem; padding: 1rem 2rem; border: none; border-radius: 12px; font-weight: 600; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); font-size: 1rem; position: relative; overflow: hidden; } .kb-button::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(135deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.1)); opacity: 0; transition: opacity 0.3s ease; } .kb-button:hover::before { opacity: 1; } .kb-button:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15); } .kb-button:disabled { opacity: 0.6; cursor: not-allowed; transform: none !important; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important; } .kb-button.primary { background: linear-gradient(135deg, #4299e1, #3182ce); color: white; } .kb-button.secondary { background: linear-gradient(135deg, #718096, #4a5568); color: white; } .kb-button.danger { background: linear-gradient(135deg, #f56565, #e53e3e); color: white; } /* 文档列表 */ .kb-documents-section { background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(20px); border-radius: 20px; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); overflow-x: auto; overflow-y: visible; } .kb-documents-header { display: flex; align-items: center; justify-content: space-between; padding: 2rem 2.5rem; border-bottom: 1px solid #e2e8f0; } .kb-documents-title-group { display: flex; align-items: center; gap: 1rem; } .kb-documents-icon { width: 60px; height: 60px; background: linear-gradient(135deg, #9f7aea, #805ad5); border-radius: 15px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; color: white; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); } .kb-documents-title { font-size: 1.5rem; font-weight: 700; color: #2d3748; margin-bottom: 0.25rem; } .kb-documents-subtitle { color: #718096; font-size: 0.9rem; } /* 加载状态 */ .kb-loading { text-align: center; padding: 4rem; } .kb-loading-icon { width: 80px; height: 80px; margin: 0 auto 2rem; position: relative; } .kb-loading-spinner { width: 100%; height: 100%; border: 4px solid #e2e8f0; border-top: 4px solid #4299e1; border-radius: 50%; animation: spin 1s linear infinite; } .kb-loading-inner { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 32px; height: 32px; background: linear-gradient(135deg, #4299e1, #3182ce); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-size: 1rem; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .kb-loading-title { font-size: 1.5rem; font-weight: 600; color: #2d3748; margin-bottom: 0.5rem; } .kb-loading-subtitle { color: #718096; margin-bottom: 1.5rem; } .kb-loading-dots { display: flex; justify-content: center; gap: 0.5rem; } .kb-loading-dot { width: 8px; height: 8px; border-radius: 50%; animation: bounce 1.4s infinite ease-in-out both; } .kb-loading-dot:nth-child(1) { background: #4299e1; animation-delay: -0.32s; } .kb-loading-dot:nth-child(2) { background: #9f7aea; animation-delay: -0.16s; } .kb-loading-dot:nth-child(3) { background: #f56565; } @keyframes bounce { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } } /* 空状态 */ .kb-empty { text-align: center; padding: 5rem 2rem; } .kb-empty-icon { width: 120px; height: 120px; margin: 0 auto 2rem; position: relative; } .kb-empty-circle { width: 100%; height: 100%; background: linear-gradient(135deg, #e6fffa, #b2f5ea); border-radius: 50%; display: flex; align-items: center; justify-content: center; animation: pulse-soft 3s infinite ease-in-out; } .kb-empty-circle span { font-size: 3rem; animation: bounce-soft 2s infinite ease-in-out; } @keyframes pulse-soft { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.05); } } @keyframes bounce-soft { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-10px); } } .kb-empty-title { font-size: 2rem; font-weight: 700; color: #2d3748; margin-bottom: 1rem; } .kb-empty-subtitle { font-size: 1.25rem; color: #718096; margin-bottom: 2rem; max-width: 600px; margin-left: auto; margin-right: auto; line-height: 1.6; } .kb-empty-formats { display: flex; flex-wrap: wrap; gap: 1rem; justify-content: center; margin-bottom: 2rem; } .kb-empty-cta { display: inline-flex; align-items: center; gap: 0.75rem; padding: 1rem 2rem; background: linear-gradient(135deg, #4299e1, #3182ce); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 1.1rem; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1); } .kb-empty-cta:hover { transform: translateY(-2px); box-shadow: 0 12px 30px rgba(0, 0, 0, 0.15); } .kb-empty-cta span:first-child { font-size: 1.25rem; animation: bounce-soft 2s infinite ease-in-out; } /* 文档表格容器 */ .kb-table-container { max-height: 60vh; overflow-y: auto; overflow-x: auto; border-radius: 8px; background: #ffffff; } .kb-table-container::-webkit-scrollbar { width: 8px; height: 8px; } .kb-table-container::-webkit-scrollbar-track { background: #f8f9fa; border-radius: 4px; } .kb-table-container::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; } .kb-table-container::-webkit-scrollbar-thumb:hover { background: #94a3b8; } .kb-table-container::-webkit-scrollbar-corner { background: #f8f9fa; } /* 文档表格 */ .kb-table { width: 100%; border-collapse: collapse; min-width: 800px; } .kb-table thead { background: linear-gradient(135deg, #f7fafc, #edf2f7); position: sticky; top: 0; z-index: 10; } .kb-table th { padding: 1.5rem; text-align: left; font-weight: 600; color: #4a5568; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 0.05em; border-bottom: 2px solid #e2e8f0; } .kb-table th:first-child { text-align: left; } .kb-table th:not(:first-child) { text-align: center; } .kb-table tbody tr { border-bottom: 1px solid #e2e8f0; transition: all 0.3s ease; } .kb-table tbody tr:hover { background: linear-gradient(135deg, #f7fafc, #edf2f7); transform: scale(1.01); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); } .kb-table td { padding: 2rem 1.5rem; vertical-align: middle; } .kb-doc-cell { display: flex; align-items: center; gap: 1.5rem; } .kb-doc-icon-wrapper { position: relative; } .kb-doc-icon { width: 64px; height: 64px; background: linear-gradient(135deg, #4299e1, #3182ce); border-radius: 15px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; color: white; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); transition: transform 0.3s ease; } .kb-table tbody tr:hover .kb-doc-icon { transform: scale(1.1) rotate(5deg); } .kb-doc-number { position: absolute; top: -4px; right: -4px; width: 20px; height: 20px; background: linear-gradient(135deg, #48bb78, #38a169); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-size: 0.7rem; font-weight: bold; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); } .kb-doc-info { flex: 1; min-width: 0; } .kb-doc-name { font-size: 1.1rem; font-weight: 600; color: #2d3748; margin-bottom: 0.5rem; transition: color 0.3s ease; } .kb-table tbody tr:hover .kb-doc-name { color: #4299e1; } .kb-doc-meta { display: flex; gap: 0.75rem; } .kb-doc-id { font-size: 0.8rem; color: #718096; background: #e2e8f0; padding: 0.25rem 0.5rem; border-radius: 6px; font-family: monospace; } .kb-doc-status { font-size: 0.8rem; color: #22543d; background: #c6f6d5; padding: 0.25rem 0.5rem; border-radius: 6px; font-weight: 600; } .kb-cell-center { text-align: center; } .kb-file-size-display { font-size: 1.1rem; font-weight: 600; color: #2d3748; margin-bottom: 0.25rem; } .kb-file-size-label { font-size: 0.8rem; color: #718096; } .kb-chunks-badge { display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.5rem 1rem; background: linear-gradient(135deg, #e6fffa, #b2f5ea); color: #234e52; border-radius: 20px; font-weight: 600; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); transition: all 0.3s ease; } .kb-table tbody tr:hover .kb-chunks-badge { background: linear-gradient(135deg, #b2f5ea, #9ae6b4); transform: scale(1.05); } .kb-chunks-dot { width: 8px; height: 8px; background: #48bb78; border-radius: 50%; animation: pulse 2s infinite; } .kb-date-display { font-weight: 600; color: #4a5568; margin-bottom: 0.25rem; } .kb-date-label { font-size: 0.8rem; color: #718096; } .kb-delete-button { position: relative; padding: 0.75rem 1rem; background: linear-gradient(135deg, #fed7d7, #feb2b2); color: #c53030; border: 2px solid #fed7d7; border-radius: 12px; font-weight: 600; cursor: pointer; transition: all 0.3s ease; overflow: hidden; } .kb-delete-button::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(135deg, #f56565, #e53e3e); opacity: 0; transition: opacity 0.3s ease; } .kb-delete-button:hover { color: white; border-color: #f56565; transform: scale(1.05); } .kb-delete-button:hover::before { opacity: 1; } .kb-delete-content { position: relative; z-index: 1; display: flex; align-items: center; gap: 0.5rem; } .kb-delete-content span:first-child { font-size: 1.1rem; transition: transform 0.3s ease; } .kb-delete-button:hover .kb-delete-content span:first-child { animation: bounce-soft 0.6s ease-in-out; } /* 处理状态显示 */ .kb-processing-status { margin-top: 1rem; padding: 1.5rem; border-radius: 15px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); border: 2px solid; } .kb-processing-status.pending { background: linear-gradient(135deg, #fef5e7, #fed7aa); border-color: #f6ad55; color: #744210; } .kb-processing-status.reading { background: linear-gradient(135deg, #e6fffa, #b2f5ea); border-color: #4299e1; color: #1e4a8c; } .kb-processing-status.completed { background: linear-gradient(135deg, #f0fff4, #c6f6d5); border-color: #48bb78; color: #22543d; } .kb-processing-status.failed { background: linear-gradient(135deg, #fed7d7, #feb2b2); border-color: #f56565; color: #c53030; } .kb-processing-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem; } .kb-processing-title { font-weight: 600; font-size: 0.9rem; } .kb-processing-percentage { font-weight: 600; font-size: 0.9rem; background: rgba(255, 255, 255, 0.5); padding: 0.25rem 0.75rem; border-radius: 20px; } .kb-processing-bar { width: 100%; height: 8px; background: rgba(255, 255, 255, 0.3); border-radius: 4px; overflow: hidden; margin-bottom: 0.75rem; } .kb-processing-progress { height: 100%; background: linear-gradient(90deg, #4299e1, #3182ce); border-radius: 4px; transition: width 0.5s ease; box-shadow: 0 0 8px rgba(66, 153, 225, 0.4); } .kb-processing-chunks { font-size: 0.8rem; font-weight: 600; background: rgba(255, 255, 255, 0.4); padding: 0.5rem 0.75rem; border-radius: 12px; display: inline-block; } .kb-chunks-info { margin-bottom: 0.5rem; } .kb-chunks-progress { height: 6px; background: rgba(255, 255, 255, 0.3); border-radius: 3px; overflow: hidden; } .kb-chunks-progress-bar { height: 100%; background: linear-gradient(90deg, #4299e1, #3182ce); border-radius: 3px; transition: width 0.3s ease; box-shadow: 0 0 8px rgba(66, 153, 225, 0.6); } /* 知识库滚动条美化 */ .knowledge-base-container::-webkit-scrollbar { width: 8px; } .knowledge-base-container::-webkit-scrollbar-track { background: rgba(255, 255, 255, 0.1); border-radius: 4px; } .knowledge-base-container::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.3); border-radius: 4px; transition: background 0.3s ease; } .knowledge-base-container::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.5); } .kb-documents-section::-webkit-scrollbar { height: 6px; } .kb-documents-section::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 3px; } .kb-documents-section::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 3px; transition: background 0.3s ease; } .kb-documents-section::-webkit-scrollbar-thumb:hover { background: #94a3b8; } /* 响应式设计 */ @media (max-width: 768px) { .knowledge-base-content { padding: 1rem; min-height: calc(100vh - 2rem); } .kb-title { font-size: 2rem; } .kb-stats-grid { grid-template-columns: 1fr; gap: 1rem; } .kb-stat-card, .kb-upload-section, .kb-documents-section { padding: 1.5rem; } .kb-action-buttons { flex-direction: column; } .kb-button { justify-content: center; } .kb-table-container { max-height: 50vh; } .kb-table { font-size: 0.9rem; min-width: 600px; } .kb-table th, .kb-table td { padding: 1rem 0.75rem; } .kb-doc-icon { width: 48px; height: 48px; font-size: 1.25rem; } .kb-doc-cell { gap: 1rem; } } @media (max-width: 480px) { .knowledge-base-content { padding: 0.75rem; min-height: calc(100vh - 1.5rem); } .kb-title { font-size: 1.5rem; } .kb-subtitle { font-size: 1rem; } .kb-upload-zone { padding: 2rem 1rem; } .kb-format-tags { justify-content: center; } .kb-table-container { max-height: 45vh; } .kb-table { min-width: 500px; font-size: 0.8rem; } .kb-documents-header { flex-direction: column; gap: 1rem; text-align: center; } }
25,719
KnowledgeBaseManagement
css
en
css
data
{"qsc_code_num_words": 3629, "qsc_code_num_chars": 25719.0, "qsc_code_mean_word_length": 4.60457426, "qsc_code_frac_words_unique": 0.10278314, "qsc_code_frac_chars_top_2grams": 0.01125075, "qsc_code_frac_chars_top_3grams": 0.01077199, "qsc_code_frac_chars_top_4grams": 0.07540395, "qsc_code_frac_chars_dupe_5grams": 0.61639737, "qsc_code_frac_chars_dupe_6grams": 0.53572711, "qsc_code_frac_chars_dupe_7grams": 0.46157989, "qsc_code_frac_chars_dupe_8grams": 0.39060443, "qsc_code_frac_chars_dupe_9grams": 0.30897666, "qsc_code_frac_chars_dupe_10grams": 0.27917415, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.10902506, "qsc_code_frac_chars_whitespace": 0.18402737, "qsc_code_size_file_byte": 25719.0, "qsc_code_num_lines": 1349.0, "qsc_code_num_chars_line_max": 117.0, "qsc_code_num_chars_line_mean": 19.06523351, "qsc_code_frac_chars_alphabet": 0.68722005, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.55421687, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "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}
0015/StickiNote
main/NVSManager.cpp
#include "NVSManager.hpp" #include "esp_log.h" #include "esp_random.h" #include <cstdlib> #include <cstdio> std::string NVSManager::generateUUID() { char uuid[9]; sprintf(uuid, "%08X", esp_random()); ESP_LOGI("NVS", "ID: %s", uuid); return std::string(uuid); } void NVSManager::init() { esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { nvs_flash_erase(); nvs_flash_init(); } } void NVSManager::updateSinglePostIt(const PostItData& postIt) { if (postIt.id.empty()) return; std::vector<PostItData> postIts = loadPostIts(); bool found = false; for (auto& p : postIts) { if (p.id == postIt.id) { p = postIt; found = true; break; } } if (!found) { ESP_LOGW("NVS", "Post-it with ID %s not found, adding a new one.", postIt.id.c_str()); postIts.push_back(postIt); } cJSON *root = cJSON_CreateArray(); for (const auto& p : postIts) { cJSON *postit_obj = cJSON_CreateObject(); cJSON_AddStringToObject(postit_obj, "id", p.id.c_str()); cJSON_AddNumberToObject(postit_obj, "x", p.x); cJSON_AddNumberToObject(postit_obj, "y", p.y); cJSON_AddNumberToObject(postit_obj, "width", p.width); cJSON_AddNumberToObject(postit_obj, "height", p.height); cJSON_AddStringToObject(postit_obj, "text", p.text.c_str()); cJSON_AddItemToArray(root, postit_obj); } char *json_str = cJSON_Print(root); ESP_LOGI("NVS", "Updated JSON: %s", json_str); cJSON_Delete(root); nvs_handle_t nvs_handle; esp_err_t err = nvs_open("storage", NVS_READWRITE, &nvs_handle); if (err != ESP_OK) { ESP_LOGE("NVS", "Failed to open NVS for writing!"); free(json_str); return; } err = nvs_set_str(nvs_handle, "postits", json_str); if (err == ESP_OK) { ESP_LOGI("NVS", "Post-its successfully updated in NVS."); } else { ESP_LOGE("NVS", "Failed to write Post-its to NVS."); } err = nvs_commit(nvs_handle); if (err != ESP_OK) { ESP_LOGE("NVS", "Failed to commit data to NVS!"); } else { ESP_LOGI("NVS", "NVS commit successful."); } nvs_close(nvs_handle); free(json_str); } std::vector<PostItData> NVSManager::loadPostIts() { std::vector<PostItData> postIts; nvs_handle_t nvs_handle; esp_err_t err = nvs_open("storage", NVS_READONLY, &nvs_handle); if (err != ESP_OK) { ESP_LOGW("NVS", "Failed to open NVS for reading."); return postIts; } size_t required_size = 0; err = nvs_get_str(nvs_handle, "postits", NULL, &required_size); if (err != ESP_OK || required_size == 0) { ESP_LOGW("NVS", "No saved Post-its in NVS."); nvs_close(nvs_handle); return postIts; } char *json_str = (char*)malloc(required_size); err = nvs_get_str(nvs_handle, "postits", json_str, &required_size); nvs_close(nvs_handle); if (err != ESP_OK) { ESP_LOGE("NVS", "Failed to read Post-its from NVS."); free(json_str); return postIts; } ESP_LOGI("NVS", "Loaded JSON from NVS: %s", json_str); cJSON *root = cJSON_Parse(json_str); free(json_str); if (!root) { ESP_LOGE("NVS", "Failed to parse JSON from NVS."); return postIts; } int count = cJSON_GetArraySize(root); ESP_LOGI("NVS", "Restoring %d Post-it notes", count); for (int i = 0; i < count; i++) { cJSON *postit_obj = cJSON_GetArrayItem(root, i); if (!postit_obj) continue; PostItData data; data.id = cJSON_GetObjectItem(postit_obj, "id")->valuestring; data.x = cJSON_GetObjectItem(postit_obj, "x")->valueint; data.y = cJSON_GetObjectItem(postit_obj, "y")->valueint; data.width = cJSON_GetObjectItem(postit_obj, "width")->valueint; data.height = cJSON_GetObjectItem(postit_obj, "height")->valueint; data.text = cJSON_GetObjectItem(postit_obj, "text")->valuestring; postIts.push_back(data); } cJSON_Delete(root); return postIts; }
4,186
NVSManager
cpp
en
cpp
code
{"qsc_code_num_words": 546, "qsc_code_num_chars": 4186.0, "qsc_code_mean_word_length": 4.46886447, "qsc_code_frac_words_unique": 0.22710623, "qsc_code_frac_chars_top_2grams": 0.05901639, "qsc_code_frac_chars_top_3grams": 0.02459016, "qsc_code_frac_chars_top_4grams": 0.02459016, "qsc_code_frac_chars_dupe_5grams": 0.16147541, "qsc_code_frac_chars_dupe_6grams": 0.14139344, "qsc_code_frac_chars_dupe_7grams": 0.11516393, "qsc_code_frac_chars_dupe_8grams": 0.08319672, "qsc_code_frac_chars_dupe_9grams": 0.08319672, "qsc_code_frac_chars_dupe_10grams": 0.08319672, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00189095, "qsc_code_frac_chars_whitespace": 0.24199713, "qsc_code_size_file_byte": 4186.0, "qsc_code_num_lines": 140.0, "qsc_code_num_chars_line_max": 95.0, "qsc_code_num_chars_line_mean": 29.9, "qsc_code_frac_chars_alphabet": 0.76709738, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.18965517, "qsc_code_cate_autogen": 1.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.12971811, "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.04310345, "qsc_codecpp_frac_lines_func_ratio": 0.0, "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.09482759, "qsc_codecpp_frac_lines_print": 0.00862069}
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_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/StickiNote
main/LVGL_WidgetManager.cpp
#include "LVGL_WidgetManager.hpp" #include "esp_log.h" #include <algorithm> #include "esp_timer.h" #define DOUBLE_TAP_TIME 300 #define MAX_POSTITS 10 LV_IMG_DECLARE(icon_resize); LV_FONT_DECLARE(sticky_font_32) lv_obj_t *LVGL_WidgetManager::screen_ = nullptr; lv_obj_t *LVGL_WidgetManager::kb_ = nullptr; LVGL_WidgetManager *LVGL_WidgetManager::instance = nullptr; int LVGL_WidgetManager::screen_width_ = 0; int LVGL_WidgetManager::screen_height_ = 0; std::vector<lv_obj_t *> LVGL_WidgetManager::widgets_; LVGL_WidgetManager::LVGL_WidgetManager(lv_obj_t *screen, lv_obj_t *kb) { instance = this; screen_ = screen; kb_ = kb; widgets_.reserve(MAX_POSTITS); printf("LVGL_WidgetManager Initialized - Parent: %p, Keyboard: %p\n", screen_, kb_); screen_width_ = lv_obj_get_width(lv_screen_active()); screen_height_ = lv_obj_get_height(lv_screen_active()); printf("LVGL_WidgetManager Initialized - screen_width_: %d, screen_height_: %d\n", screen_width_, screen_height_); static lv_style_t style_fab; lv_style_init(&style_fab); lv_style_set_radius(&style_fab, LV_RADIUS_CIRCLE); lv_style_set_bg_opa(&style_fab, LV_OPA_COVER); lv_style_set_bg_color(&style_fab, lv_palette_main(LV_PALETTE_GREY)); lv_style_set_shadow_width(&style_fab, 10); lv_style_set_shadow_color(&style_fab, lv_palette_darken(LV_PALETTE_GREY, 2)); lv_style_set_text_color(&style_fab, lv_color_white()); lv_obj_t *fab_btn = lv_btn_create(screen_); lv_obj_set_size(fab_btn, 80, 80); lv_obj_add_style(fab_btn, &style_fab, LV_PART_MAIN); lv_obj_align(fab_btn, LV_ALIGN_BOTTOM_RIGHT, 20, 20); lv_obj_set_style_bg_image_src(fab_btn, LV_SYMBOL_PLUS, 0); lv_obj_add_event_cb(fab_btn, [](lv_event_t *e) { if (instance) { ESP_LOGE("LVGL", "fab_btn_event_cb"); instance->createPostIt(20, 20, 300, 300, "", NVSManager::generateUUID()); } }, LV_EVENT_CLICKED, nullptr); } void LVGL_WidgetManager::createPostIt(int x, int y, int width, int height, const char* text, std::string id) { if (widgets_.size() >= MAX_POSTITS) { ESP_LOGW("LVGL", "Maximum Post-it limit reached (%d). Cannot create more.", MAX_POSTITS); return; } if (!screen_) { ESP_LOGE("LVGL", "Error: Parent object is NULL!"); return; } if (!kb_) { printf("Warning: kb_ is NULL. Creating a default keyboard.\n"); return; } static lv_style_t style_postit; lv_style_init(&style_postit); lv_style_set_bg_opa(&style_postit, LV_OPA_COVER); lv_style_set_bg_color(&style_postit, lv_color_make(230, 230, 230)); lv_style_set_border_color(&style_postit, lv_color_black()); lv_style_set_border_width(&style_postit, 2); lv_style_set_radius(&style_postit, 5); lv_obj_t *postit = lv_obj_create(screen_); if (!postit) { ESP_LOGE("LVGL", "Error: Failed to create Post-it object!"); return; } lv_obj_add_style(postit, &style_postit, LV_PART_MAIN); lv_obj_clear_flag(postit, LV_OBJ_FLAG_SCROLLABLE); lv_obj_set_pos(postit, x, y); lv_obj_set_size(postit, width, height); static lv_style_t style_textarea; lv_style_init(&style_textarea); lv_style_set_bg_opa(&style_textarea, LV_OPA_COVER); lv_style_set_bg_color(&style_textarea, lv_color_white()); lv_style_set_border_color(&style_textarea, lv_color_black()); lv_style_set_border_width(&style_textarea, 1); lv_style_set_text_color(&style_textarea, lv_color_black()); lv_style_set_pad_all(&style_textarea, 5); lv_style_set_text_font(&style_textarea, &sticky_font_32); lv_obj_t *textarea = lv_textarea_create(postit); lv_obj_set_size(textarea, width - 20, height - 30); lv_obj_align(textarea, LV_ALIGN_TOP_LEFT, 10, 10); lv_obj_add_style(textarea, &style_textarea, LV_PART_MAIN); lv_obj_clear_flag(textarea, LV_OBJ_FLAG_SCROLLABLE); lv_obj_add_event_cb(textarea, textarea_event_handler, LV_EVENT_PRESSING, nullptr); lv_obj_add_event_cb(textarea, textarea_event_handler, LV_EVENT_RELEASED, nullptr); lv_obj_add_event_cb(textarea, textarea_kb_event_handler, LV_EVENT_CLICKED, kb_); lv_obj_add_event_cb(textarea, textarea_kb_event_handler, LV_EVENT_DEFOCUSED, kb_); lv_keyboard_set_textarea(kb_, textarea); if (text == nullptr || text[0] == '\0') { lv_textarea_set_placeholder_text(textarea, "Enter text here..."); }else{ lv_textarea_set_text(textarea, text); lv_textarea_set_cursor_pos(textarea, 0); } lv_obj_t *close_btn = lv_btn_create(postit); lv_obj_set_size(close_btn, 30, 30); lv_obj_align(close_btn, LV_ALIGN_TOP_RIGHT, 20, -20); lv_obj_set_style_bg_color(close_btn, lv_palette_main(LV_PALETTE_RED), LV_PART_MAIN); lv_obj_t *close_label = lv_label_create(close_btn); lv_label_set_text(close_label, "X"); lv_obj_center(close_label); lv_obj_add_event_cb(close_btn, [](lv_event_t *e) { lv_obj_t* btn = (lv_obj_t*)lv_event_get_target(e); lv_obj_t* postIt = (lv_obj_t*)lv_obj_get_parent(btn); LVGL_WidgetManager::instance->removePostIt(postIt); }, LV_EVENT_CLICKED, nullptr); lv_obj_t *resize_btn = lv_button_create(postit); lv_obj_set_size(resize_btn, 40, 40); lv_obj_align(resize_btn, LV_ALIGN_BOTTOM_RIGHT, 20, 20); lv_obj_set_style_bg_opa(resize_btn, LV_OPA_TRANSP, LV_PART_MAIN); lv_obj_set_style_border_color(resize_btn, lv_palette_main(LV_PALETTE_GREY), LV_PART_MAIN); lv_obj_set_style_border_width(resize_btn, 2, LV_PART_MAIN); lv_obj_t *resize_icon = lv_img_create(resize_btn); lv_img_set_src(resize_icon, &icon_resize); lv_obj_center(resize_icon); lv_obj_add_event_cb(resize_btn, drag_event_handler, LV_EVENT_PRESSING, textarea); lv_obj_add_event_cb(resize_btn, drag_event_handler, LV_EVENT_RELEASED, textarea); lv_obj_set_user_data(postit, (void *)new std::string(id)); widgets_.push_back(postit); ESP_LOGE("LVGL", "Post-it created. Total count: %d\n", (int)widgets_.size()); PostItData postItData = {id, x, y, width, height, text}; NVSManager::updateSinglePostIt(postItData); } void LVGL_WidgetManager::removePostIt(lv_obj_t *postit) { if (!postit) return; std::string *id_ptr = static_cast<std::string *>(lv_obj_get_user_data(postit)); if (!id_ptr) { ESP_LOGE("LVGL", "Failed to get Post-it ID for deletion."); return; } std::string postItID = *id_ptr; delete id_ptr; lv_obj_del(postit); auto it = std::find(widgets_.begin(), widgets_.end(), postit); if (it != widgets_.end()) { widgets_.erase(it); } NVSManager::removePostItFromNVS(postItID); ESP_LOGI("LVGL", "Post-it removed successfully. ID: %s", postItID.c_str()); } void LVGL_WidgetManager::deleteAllWidgets() { for (auto widget : widgets_) { lv_obj_del(widget); } widgets_.clear(); } int LVGL_WidgetManager::getWidgetCount() const { return widgets_.size(); } void LVGL_WidgetManager::btn_event_cb(lv_event_t *e) { lv_event_code_t code = lv_event_get_code(e); lv_obj_t *btn = (lv_obj_t *)lv_event_get_target(e); if (code == LV_EVENT_CLICKED) { static uint8_t cnt = 0; cnt++; /*Get the first child of the button which is the label and change its text*/ lv_obj_t *label = lv_obj_get_child(btn, 0); lv_label_set_text_fmt(label, "Button: %d", cnt); } } void LVGL_WidgetManager::drag_event_handler(lv_event_t *e) { lv_event_code_t code = lv_event_get_code(e); lv_obj_t *obj = (lv_obj_t *)lv_event_get_target(e); lv_obj_t *postit = (lv_obj_t *)lv_obj_get_parent(obj); if (postit == NULL) return; if (code == LV_EVENT_RELEASED) { ESP_LOGI("LVGL", "Post-it resize finalized and saved."); instance->saveSinglePostItToNVS(postit); return; } lv_indev_t *indev = lv_indev_active(); if (indev == NULL) return; lv_point_t vect; lv_indev_get_vect(indev, &vect); if (vect.x == 0 && vect.y == 0) return; lv_obj_move_foreground(postit); int32_t x = lv_obj_get_width(postit) + vect.x; int32_t y = lv_obj_get_height(postit) + vect.y; lv_obj_set_size(postit, x, y); lv_obj_t *textarea = (lv_obj_t *)lv_event_get_user_data(e); if (textarea == NULL) return; x = lv_obj_get_width(textarea) + vect.x; y = lv_obj_get_height(textarea) + vect.y; lv_obj_set_size(textarea, x, y); } void LVGL_WidgetManager::textarea_event_handler(lv_event_t *e) { lv_event_code_t code = lv_event_get_code(e); lv_obj_t *textarea = (lv_obj_t *)lv_event_get_target(e); lv_obj_t *postit = (lv_obj_t *)lv_obj_get_parent(textarea); if (!postit || !screen_) return; lv_obj_move_foreground(postit); if (code == LV_EVENT_PRESSING){ lv_indev_t *indev = lv_indev_active(); if (indev == NULL) return; lv_point_t vect; lv_indev_get_vect(indev, &vect); int32_t x = lv_obj_get_x_aligned(postit) + vect.x; int32_t y = lv_obj_get_y_aligned(postit) + vect.y; lv_obj_set_pos(postit, x, y); }else if (code == LV_EVENT_RELEASED){ instance->saveSinglePostItToNVS(postit); } } void LVGL_WidgetManager::textarea_kb_event_handler(lv_event_t *e) { lv_event_code_t code = lv_event_get_code(e); lv_obj_t *textarea = (lv_obj_t *)lv_event_get_target(e); lv_obj_t *kb = (lv_obj_t *)lv_event_get_user_data(e); lv_obj_t *postit = (lv_obj_t *)lv_obj_get_parent(textarea); if (!postit || !screen_) return; int screen_mid = screen_height_ / 2; int postit_y = lv_obj_get_y_aligned(postit); int kb_height = screen_height_ / 3; static int original_screen_y = 0; static int64_t last_tap_time = 0; int64_t current_time = esp_timer_get_time() / 1000; if (code == LV_EVENT_CLICKED) { if (current_time - last_tap_time < DOUBLE_TAP_TIME) { ESP_LOGI("LVGL", "Double-tap detected! Opening keyboard."); lv_obj_move_foreground(postit); lv_keyboard_set_textarea(kb, textarea); lv_obj_remove_flag(kb, LV_OBJ_FLAG_HIDDEN); if (postit_y > screen_mid) { original_screen_y = lv_obj_get_y_aligned(screen_); lv_obj_set_y(screen_, original_screen_y - kb_height); } } last_tap_time = current_time; }else if (code == LV_EVENT_DEFOCUSED) { lv_keyboard_set_textarea(kb, NULL); lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN); lv_obj_set_y(screen_, original_screen_y); instance->saveSinglePostItToNVS(postit); } } void LVGL_WidgetManager::saveSinglePostItToNVS(lv_obj_t *postit) { std::string *id_ptr = static_cast<std::string *>(lv_obj_get_user_data(postit)); ESP_LOGI("LVGL", "saveSinglePostItToNVS: Post-it ID: %s", *id_ptr); if (!id_ptr) return; PostItData postIt; postIt.id = *id_ptr; postIt.x = lv_obj_get_x(postit); postIt.y = lv_obj_get_y(postit); postIt.width = lv_obj_get_width(postit); postIt.height = lv_obj_get_height(postit); postIt.text = lv_textarea_get_text(lv_obj_get_child(postit, 0)); NVSManager::updateSinglePostIt(postIt); } void LVGL_WidgetManager::loadPostItsFromNVS() { std::vector<PostItData> postIts = NVSManager::loadPostIts(); if (postIts.empty()) { ESP_LOGW("LVGL", "No Post-its found in NVS."); return; } for (const auto& postIt : postIts) { ESP_LOGI("LVGL", "Creating Post-it ID: %s at (%d, %d)", postIt.id.c_str(), postIt.x, postIt.y); createPostIt(postIt.x, postIt.y, postIt.width, postIt.height, postIt.text.c_str(), postIt.id); } } void NVSManager::removePostItFromNVS(const std::string &postItID) { std::vector<PostItData> postIts = loadPostIts(); auto it = std::remove_if(postIts.begin(), postIts.end(), [&](const PostItData &p) { return p.id == postItID; }); if (it == postIts.end()) { ESP_LOGW("NVS", "Post-it with ID %s not found in NVS.", postItID.c_str()); return; } postIts.erase(it, postIts.end()); cJSON *root = cJSON_CreateArray(); for (const auto &p : postIts) { cJSON *postit_obj = cJSON_CreateObject(); cJSON_AddStringToObject(postit_obj, "id", p.id.c_str()); cJSON_AddNumberToObject(postit_obj, "x", p.x); cJSON_AddNumberToObject(postit_obj, "y", p.y); cJSON_AddNumberToObject(postit_obj, "width", p.width); cJSON_AddNumberToObject(postit_obj, "height", p.height); cJSON_AddStringToObject(postit_obj, "text", p.text.c_str()); cJSON_AddItemToArray(root, postit_obj); } char *json_str = cJSON_Print(root); cJSON_Delete(root); nvs_handle_t nvs_handle; esp_err_t err = nvs_open("storage", NVS_READWRITE, &nvs_handle); if (err != ESP_OK) { ESP_LOGE("NVS", "Failed to open NVS for deletion!"); free(json_str); return; } err = nvs_set_str(nvs_handle, "postits", json_str); if (err == ESP_OK) { ESP_LOGI("NVS", "Post-it successfully deleted from NVS."); } else { ESP_LOGE("NVS", "Failed to update NVS after deletion."); } err = nvs_commit(nvs_handle); if (err != ESP_OK) { ESP_LOGE("NVS", "Failed to commit NVS after deletion!"); } else { ESP_LOGI("NVS", "NVS commit successful after deletion."); } nvs_close(nvs_handle); free(json_str); }
12,950
LVGL_WidgetManager
cpp
en
cpp
code
{"qsc_code_num_words": 2005, "qsc_code_num_chars": 12950.0, "qsc_code_mean_word_length": 4.1925187, "qsc_code_frac_words_unique": 0.12468828, "qsc_code_frac_chars_top_2grams": 0.06364502, "qsc_code_frac_chars_top_3grams": 0.02640971, "qsc_code_frac_chars_top_4grams": 0.01046871, "qsc_code_frac_chars_dupe_5grams": 0.41184868, "qsc_code_frac_chars_dupe_6grams": 0.33119201, "qsc_code_frac_chars_dupe_7grams": 0.23209612, "qsc_code_frac_chars_dupe_8grams": 0.21103973, "qsc_code_frac_chars_dupe_9grams": 0.19248156, "qsc_code_frac_chars_dupe_10grams": 0.15500833, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00915416, "qsc_code_frac_chars_whitespace": 0.15644788, "qsc_code_size_file_byte": 12950.0, "qsc_code_num_lines": 398.0, "qsc_code_num_chars_line_max": 117.0, "qsc_code_num_chars_line_mean": 32.53768844, "qsc_code_frac_chars_alphabet": 0.7603442, "qsc_code_frac_chars_comments": 0.00586873, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.13803681, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.07666615, "qsc_code_frac_chars_long_word_length": 0.00341774, "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.01840491, "qsc_codecpp_frac_lines_func_ratio": 0.0, "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.04907975, "qsc_codecpp_frac_lines_print": 0.00920245}
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}
0000cd/wolf-set
content/posts/about.md
--- author: 狼 title: 关于狼集 date: 2024-04-04 draft: false --- - [这是开源项目,你也可以快速创建**属于你自己的**网址导航。](https://github.com/0000cd/wolf-set) - [点我访问【**首页**】,浏览共 {{< total >}} 个有趣网址导航,和 {{< total "开源" >}} 个开源项目!](/) ## 狼集 Wolf Set [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=0000cd_wolf-set&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=0000cd_wolf-set) 宇宙总需要些航天器,“📀各位都好吧?” 让我们路过些互联网小行星。 狼集 Wolf Set,源自“狼牌工作网址导航”。集万千兴趣,再次发现分享互联网的新乐趣! ### 灵感 Wolf(狼)+ Set(集合),音同“狼藉”(杂乱不堪,糟透了!),一个聚合发现与分享的地方。 Wolf Set 则更常见于游戏,是指“狼套装”,一身盔甲或装备,你冒险可靠的家伙。 ![镀金铝板](/img/欢迎回来.png) ## 特别感谢 - 静态生成:[Hugo](https://gohugo.io/) - The world’s fastest framework for building websites. - 网站统计:[Umami](https://umami.is/) - The modern analytics platform for effortless insights. - 友链接力:[travellings](https://www.travellings.cn/) - 让流量相互流动,让网络开放起来。 - 内容分发:[Cloudflare](https://www.cloudflare.com/) - 随时随地连接、保护和构建。 - AI 助手:[Gpt-4 & Claude 3.5](https://poe.com/) - 部分代码由 AI 协助。 - JS 库:[Isotope](https://isotope.metafizzy.co/) - Filter & sort magical layouts. --- ## Bluf theme Bluf 是一款简明扼要的**瀑布流**卡片式 Hugo 主题,非常适合脑暴、作品集、链接导航、等需要**收集分享**的场景。作者是逊狼,部分代码由 GPT-4 与 Claude AI 协助。 ### 用法 Bluf 是一款单页 Hugo 主题,这意味着你应该将数据放置在 data 目录中,而**不**是按照传统方式在 content 目录下编写文章。你需要在 data 目录下准备以下三个配置文件(以下示例为 yaml): - cards.yaml:包含主页瀑布流所有卡片的核心数据。 - navbar.yaml:包括顶部导航栏的标签筛选和外链数据。 - tag_classes.yaml:配置标签和标签样式之间的映射关系。 ### 灵感 Blue + Wolf = Bluf - BLUF (bottom line up front) is the practice of beginning a message with its key information (the "bottom line"). This provides the reader with the most important information first. - BLUF(先行底行)是一种沟通方式,即在信息的开始部分先给出关键信息(即“底行”)。这样做可以让读者首先了解到最重要的信息。 --- ## License - content 与 data 目录下的内容遵循 **[CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh-hans)** 许可协议共享。 - **Bluf** 主题因集成 **[Isotope](https://isotope.metafizzy.co/license)**,遵循 **GPLv3** 许可协议。
1,917
about
md
zh
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.00417319, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 53.0, "qsc_doc_num_words": 457, "qsc_doc_num_chars": 1917.0, "qsc_doc_num_lines": 65.0, "qsc_doc_mean_word_length": 2.96936543, "qsc_doc_frac_words_full_bracket": 0.0025413, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.64113786, "qsc_doc_entropy_unigram": 5.45701267, "qsc_doc_frac_words_all_caps": 0.01270648, "qsc_doc_frac_lines_dupe_lines": 0.15, "qsc_doc_frac_chars_dupe_lines": 0.01295896, "qsc_doc_frac_chars_top_2grams": 0.03095063, "qsc_doc_frac_chars_top_3grams": 0.02873987, "qsc_doc_frac_chars_top_4grams": 0.03389831, "qsc_doc_frac_chars_dupe_5grams": 0.04421518, "qsc_doc_frac_chars_dupe_6grams": 0.0, "qsc_doc_frac_chars_dupe_7grams": 0.0, "qsc_doc_frac_chars_dupe_8grams": 0.0, "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": 18.57142857, "qsc_doc_frac_chars_hyperlink_html_tag": 0.24047992, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.01694915, "qsc_doc_frac_chars_whitespace": 0.10745957, "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}
0000cd/wolf-set
content/posts/example.md
--- author: 逊狼 title: 网红狼求生之路引热议 date: 2024-04-04 draft: false --- ## BLUF (Bottom Line Up Front) 一只青海可可西里的野狼因被游客频繁投喂而成为“网红”,其行为模式从野生狼转变为类似家犬的依赖,引起网友热议与专家担忧。 ## 新闻报道 近日,一头青海可可西里的野狼意外成为网络红星。最初,这只野狼因不明原因被狼群赶出,瘦弱到皮包骨。然而,自从今年7月一位过路的网友在国道附近给它投喂了两个蛋黄派后,它的命运戏剧性地改变了。 这只野狼开始每天在公路上讨食,游客们被它那瘦骨嶙峋的模样所吸引,纷纷投喂食物。经过一段时间,这头狼与人类变得亲近,不再仅是被动等待投喂,而是积极迎接过往的车辆,并跟随车辆以示亲昵,以获取食物。 随着时间的流逝,这只曾经饥饿的野狼已经变得身体健壮,甚至开始挑食,偏爱高热量食物如炸鸡和蛋黄派。有趣的是,这只狼被保护站的工作人员转移到戈壁深处,但它又坚持不懈地回到了求食的道路上,并且似乎还吸引了其他狼加入,形成了一种“师徒”关系。 值得注意的是,这只狼由于长时间接触车辆,甚至学会了识别不同的车标。这一现象引发了人们对于动物生存意义的思考,同时也激起了网友们对这只狼的同情与喜爱,有人赞其可爱,有人担心它过度依赖人类投喂,可能会失去捕猎能力,或者过于亲近人类而引发危险。 专家们则警告不应随意投喂野生动物,认为这种行为虽出于善意,但缺乏理性,可能导致不良后果。他们强调死亡是自然界的一部分,而这只狼不需要救助,而是需要人们停止投喂。 尽管这个话题有多种看法,但大家普遍认为应适度投喂,避免影响该狼及其环境的自然秩序。这只网红狼通过独特的适应方式,从濒临死亡的境地中存活下来,也许正是自然选择的一种体现。
770
example
md
zh
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 14.0, "qsc_doc_num_words": 368, "qsc_doc_num_chars": 770.0, "qsc_doc_num_lines": 24.0, "qsc_doc_mean_word_length": 1.80163043, "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.66304348, "qsc_doc_entropy_unigram": 5.19228346, "qsc_doc_frac_words_all_caps": 0.00229885, "qsc_doc_frac_lines_dupe_lines": 0.13333333, "qsc_doc_frac_chars_dupe_lines": 0.0080429, "qsc_doc_frac_chars_top_2grams": 0.02413273, "qsc_doc_frac_chars_top_3grams": 0.01809955, "qsc_doc_frac_chars_top_4grams": 0.02714932, "qsc_doc_frac_chars_dupe_5grams": 0.01508296, "qsc_doc_frac_chars_dupe_6grams": 0.0, "qsc_doc_frac_chars_dupe_7grams": 0.0, "qsc_doc_frac_chars_dupe_8grams": 0.0, "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": 29.84, "qsc_doc_frac_chars_hyperlink_html_tag": 0.0, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.01222826, "qsc_doc_frac_chars_whitespace": 0.04415584, "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}
0000cd/wolf-set
themes/bluf/layouts/404.html
<!DOCTYPE html> <html lang="{{ .Site.LanguageCode }}"> <head> <!--https://github.com/vicevolf/retro-404--> <!-- https://github.com/gaoryrt/retro-404 --> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, viewport-fit=cover"> <title>404 Not Found</title> {{ if .Site.Params.enableUmami }} <script defer src="{{ .Site.Params.UmamiLink }}" data-website-id="{{ .Site.Params.UmamiID }}"></script> {{ end }} <style type="text/css"> html { overflow: hidden; font-family: Courier New, serif; font-style: normal; font-stretch: normal; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; vertical-align: baseline; -webkit-tap-highlight-color: transparent; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; text-size-adjust: 100%; background: #0000cd; color: #fafafa; font-size: 16px } body, html { width: 100%; height: 100% } body { display: -webkit-flex; display: flex; -webkit-align-items: center; align-items: center; -webkit-justify-content: center; justify-content: center; position: relative; filter: contrast(150%) brightness(120%) saturate(100%); image-rendering: pixelated; overflow: hidden; } body::before { content: ""; position: absolute; top: -50%; left: -50%; width: 200%; height: 200%; background: radial-gradient(circle at center, transparent 30%, black 250%); transform: scale(0.5); z-index: 1; pointer-events: none; } body a { color: #fafafa; text-decoration: none; } * { margin: 0; padding: 0; box-sizing: border-box } .container { width: 550px; text-align: center } p { margin: 30px 0; text-align: left } .title { background: #ccc; color: #0000cd; padding: 2px 6px } @keyframes blink { 0%, 49% { visibility: visible; } 50%, 100% { visibility: hidden; } } .blink { animation: blink 1s step-start infinite; } h1, p { position: relative; z-index: 2; } </style> </head> <body> <div class="container"> <span class="title">404 Not Found</span> <p> ░▒▓ A wild <strong>404-PAGE</strong> appeared! ▓▒░<br> ✦<em>Thank you!</em> But the page is in another path~✧<br><br> * <em>Don't Panic!</em> adventurer. The quest isn't over yet.<br> * Pro tip: <strong>DONT</strong> Forget to <a href="/feed.xml">Feed the Wolf</a>. ▓▒░<br> ------ </p> <div><a href="/">✦ Press any key to continue </a><span class="blink">_</span></div> </div> </div> <script type="text/javascript"> window.onload = function () { document.body.addEventListener('keydown', function () { window.location.href = '{{ .Site.BaseURL }}'; }); } </script> </body> </html>
3,809
404
html
en
html
code
{"qsc_code_num_words": 377, "qsc_code_num_chars": 3809.0, "qsc_code_mean_word_length": 4.77453581, "qsc_code_frac_words_unique": 0.5198939, "qsc_code_frac_chars_top_2grams": 0.02222222, "qsc_code_frac_chars_top_3grams": 0.03111111, "qsc_code_frac_chars_top_4grams": 0.02833333, "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.03955288, "qsc_code_frac_chars_whitespace": 0.38934103, "qsc_code_size_file_byte": 3809.0, "qsc_code_num_lines": 148.0, "qsc_code_num_chars_line_max": 127.0, "qsc_code_num_chars_line_mean": 25.73648649, "qsc_code_frac_chars_alphabet": 0.72914875, "qsc_code_frac_chars_comments": 0.02336571, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.09836066, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00819672, "qsc_code_frac_chars_string_length": 0.09298576, "qsc_code_frac_chars_long_word_length": 0.00591239, "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_codehtml_cate_ast": 1.0, "qsc_codehtml_frac_words_text": 0.10291415, "qsc_codehtml_num_chars_text": 392.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": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_codehtml_cate_ast": 0, "qsc_codehtml_frac_words_text": 1, "qsc_codehtml_num_chars_text": 0}
0000cd/wolf-set
themes/bluf/layouts/index.html
<!DOCTYPE html> <html lang="{{ .Site.LanguageCode }}"> <head> {{ partial "head.html" . }} <title>{{ .Site.Title }}</title> <meta name="description" content="{{ .Site.Params.description }}" /> <meta name="keywords" content="{{ range .Site.Params.keywords }}{{ . }},{{ end }}" /> </head> <body> <div class="top-bar"> <div class="top-bar-inner"> <div class="top-bar-title"> <a href="{{ .Site.BaseURL }}"> <img class="top-bar-logo" src="/logo.webp" alt="Logo"> </a> <h1 class="top-title" style="font-size: 1em;">{{ .Site.Params.pagename }}</h1> <noscript>{{ .Site.Params.alias }}</noscript> </div> <nav class="top-bar-nav"> <div class="menu-container"> <button class="theme-toggle" id="themeToggle" title="切换深浅配色"> 深色模式 </button> </div> {{ with .Site.Data.navbar.external_links }} <div class="menu-container external_links"> {{ range . }} <a href="{{ .url | safeURL }}" target="_blank" class="menu-toggle exlink" rel="noopener" {{ if $.Site.Params.enableUmami }}data-umami-event="NAV-{{ .name }}" {{ end }}> {{ .name }} </a> {{ end }} </div> {{ end }} {{ range .Site.Data.navbar.categories }} <div class="menu-container categories"> <div class="menu-toggle" id="menu-toggle-{{ .id }}">{{ .name }}</div> <div class="nav-button filter-button-group" id="filter-group-{{ .id }}"> {{ range .tags }} <button class="menu-toggle-btn filter-btn" data-filter=".{{ index $.Site.Data.tag_classes . }}">{{ . }}</button> {{ end }} </div> </div> {{ end }} {{ with .Site.Data.navbar.hot_tags }} <div class="hot-tags-container filter-button-group"> {{ range . }} <button class="hot-tag filter-btn" data-filter=".{{ index $.Site.Data.tag_classes . }}">{{ . }}</button> {{ end }} </div> {{ end }} </nav> </div> </div> <div class="grid" id="myGrid"> {{ range $index, $element := .Site.Data.cards }} {{ $title := .title }} <article id="{{ .title }}"> <div class="grid-item {{ range .tags }}{{ index $.Site.Data.tag_classes . }} {{ end }} {{- with .hex -}} {{ partial "getColorCategory" . }} {{- end -}}"> {{/* 处理链接变量 */}} {{ $link0 := false }} {{ with .links }} {{ if reflect.IsSlice . }} {{ $link0 = (index . 0).url | safeURL }} {{ else }} {{ $link0 = . | safeURL }} {{ end }} {{ end }} {{ $media := .media | default false }} <div class="grid-item-head"> {{ $extensions := slice "jpg" "jpeg" "png" "gif" "webp" "mp4" "webm" }} {{ $galleryPath := "assets/gallery" }} {{ $galleryPublicPath := "gallery" }} {{ $folders := readDir $galleryPath }} {{ range $ext := $extensions }} {{ $imgPath := printf "img/%s.%s" $title $ext }} {{ if (resources.Get $imgPath) }} {{ $image := resources.Get $imgPath }} {{ $displayWidth := 255 }} {{ $ratio := div (float $image.Height) $image.Width }} {{ $displayHeight := math.Round (mul $displayWidth $ratio) }} {{ if $.Site.Params.gallery }} {{/* 查找是否存在对应的画廊文件夹 */}} {{ $matchedFolder := false }} {{ range $folder := $folders }} {{- if and $folder.IsDir (eq (lower $folder.Name) (lower $title)) -}} {{ $matchedFolder = true }} {{ $folderName := $folder.Name }} <div class="gallery" {{ if $.Site.Params.enableUmami}}data-umami-event="GALLERY-{{ $title }}"{{ end }}> <a href="{{ $image.RelPermalink | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" id="cover" aria-label="{{ $title }}-cover"> <img class="grid-item-img cover-img" src="{{ $image.RelPermalink }}" width="{{ $displayWidth }}" height="{{ $displayHeight }}" alt="" {{ if ge $index 10 }}loading="lazy"{{ end }} onload="this.classList.add('loaded')" title="查看画廊"> <div class="cover-line"></div> </a> {{ if $media }} {{ if reflect.IsSlice $media }} {{ range $media }} <a href="{{ .url | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" style="display: none;"></a> {{ end }} {{ else }} <a href="{{ $media | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" style="display: none;"></a> {{ end }} {{ end }} {{ $galleryImagesPath := printf "%s/%s" $galleryPath $folderName }} {{ $galleryImageFiles := readDir $galleryImagesPath }} {{- range $galleryImage := $galleryImageFiles -}} {{- $galleryImageExt := path.Ext $galleryImage.Name -}} {{- $galleryImageExt := strings.TrimPrefix "." $galleryImageExt -}} {{- if in $extensions $galleryImageExt -}} {{ $galleryImageResource := resources.Get (printf "gallery/%s/%s" $folderName $galleryImage.Name) }} {{ $galleryImagePublicPath := printf "%s/%s/%s" $galleryPublicPath $folderName $galleryImage.Name }} <a href="{{ $galleryImageResource.RelPermalink | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" data-caption="{{ $title }} - {{ $galleryImage.Name }}" style="display: none;"></a> {{- end -}} {{- end -}} </div> {{- end -}} {{ end }} {{/* 如果没有找到对应的画廊文件夹 */}} {{ if not $matchedFolder }} {{ if $media }} <div class="gallery" {{ if $.Site.Params.enableUmami}}data-umami-event="GALLERY-{{ $title }}"{{ end }}> <a href="{{ $image.RelPermalink | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" id="cover" aria-label="{{ $title }}-cover"> <img class="grid-item-img cover-img" src="{{ $image.RelPermalink }}" width="{{ $displayWidth }}" height="{{ $displayHeight }}" alt="" {{ if ge $index 10 }}loading="lazy"{{ end }} onload="this.classList.add('loaded')" title="查看画廊"> <div class="cover-line"></div> </a> {{ if reflect.IsSlice $media }} {{ range $media }} <a href="{{ .url | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" style="display: none;"></a> {{ end }} {{ else }} <a href="{{ $media | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" style="display: none;"></a> {{ end }} </div> {{ else }} {{ if $link0 }} <a href="{{ $link0 }}" target="_blank" rel="noopener" aria-label="{{ $title }}-img" {{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ $title }}"{{ end }}> {{ end }} <img class="grid-item-img" src="{{ $image.RelPermalink }}" width="{{ $displayWidth }}" height="{{ $displayHeight }}" alt="" {{ if ge $index 10 }}loading="lazy"{{ end }} onload="this.classList.add('loaded')"> {{ if $link0 }} </a> {{ end }} {{ end }} {{ end }} {{ else }} {{ if $link0 }} <a href="{{ $link0 }}" target="_blank" rel="noopener" aria-label="{{ $title }}-img" {{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ $title }}"{{ end }}> {{ end }} <img class="grid-item-img" src="{{ $image.RelPermalink }}" width="{{ $displayWidth }}" height="{{ $displayHeight }}" alt="" {{ if ge $index 10 }}loading="lazy"{{ end }} onload="this.classList.add('loaded')"> {{ if $link0 }} </a> {{ end }} {{ end }} {{ break }} {{ end }} {{ end }} {{ if $link0 }} <a href="{{ $link0 }}" target="_blank" rel="noopener" {{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ $title }}"{{ end }}> {{ end }} <header class="grid-item-header"> <h2 class="grid-item-title">{{ .title }}</h2> <div class="grid-item-color-mark" style="background:{{ if eq (substr .hex 0 1) "#" }}{{ .hex }}{{ else }}#{{ .hex }}{{ end }};"> </div> </header> {{ if $link0 }} </a> {{ end }} </div> <div class="grid-item-middle"> <div class="grid-item-tags filter-button-group"> {{ range .tags }} <button class="filter-btn grid-item-tag" data-filter=".{{ index $.Site.Data.tag_classes . }}">{{ . }}</button> {{ end }} </div> <div class="grid-item-date" datetime="{{ .date }}">{{ .date }}</div> </div> {{ if $link0 }} <a href="{{ $link0 }}" target="_blank" rel="noopener" {{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ $title }}"{{ end }}> {{ end }} <section class="grid-item-description"> <p>{{ .description }}</p> </section> {{ if $link0 }} </a> {{ end }} {{ if reflect.IsSlice .links }} {{ if gt (len .links) 1 }} <nav class="grid-item-links"> {{ range after 1 .links }} <a href="{{ .url | safeURL }}" target="_blank" rel="noopener" {{ if $.Site.Params.enableUmami}}data-umami-event="LINK-{{ $title }}-{{ .name }}"{{ end }}> {{ .name }} </a> {{ end }} </nav> {{ end }} {{ end }} </div> </article> {{ end }} </div> <button id="reset-filters" onclick="showConfetti()">✕</button> <script src="/js/isotope.min.js"></script> {{ $js := resources.Get "js/script.new.js" }} {{ $secureJS := $js | resources.Minify | resources.Fingerprint }} <script src="{{ $secureJS.RelPermalink }}" integrity="{{ $secureJS.Data.Integrity }}"></script> <script> window.addEventListener('load', function() { document.getElementById('myGrid').classList.add('show'); }); </script> {{ if .Site.Params.greetings }} <div class="greeting-widget"> <div class="avatar"> <img src="/avatar.webp" alt="Avatar"> </div> <div class="message"> <span id="random-greeting"></span> </div> </div> <script> document.addEventListener('DOMContentLoaded', function() { const greetings = {{ .Site.Params.greetings }}; const mobileGreetings = {{ .Site.Params.mobileGreetings | default .Site.Params.greetings }}; const widget = document.querySelector('.greeting-widget'); const greetingEl = document.getElementById('random-greeting'); const isMobile = window.matchMedia('(max-width: 768px)').matches; const greetingArray = isMobile ? mobileGreetings : greetings; const randomIndex = Math.floor(Math.random() * greetingArray.length); greetingEl.textContent = greetingArray[randomIndex]; setTimeout(() => { widget.classList.add('show'); }, 500); setTimeout(() => { widget.classList.remove('show'); }, 3500); }); </script> {{ partial "footer.html" . }} {{ end }} {{ with .Site.Params.confettiEmojis }} <script> document.addEventListener('DOMContentLoaded', function() { const script = document.createElement('script'); script.src = '/js/js-confetti.js'; script.onload = function() { const jsConfetti = new JSConfetti(); window.showConfetti = function() { jsConfetti.addConfetti(); jsConfetti.addConfetti({ emojis: {{ . }}, emojiSize: 60, confettiNumber: 30 }); } }; document.head.appendChild(script); }); </script> {{ end }} {{ if .Site.Params.gallery }} <script> document.addEventListener('DOMContentLoaded', function() { const linkElement = document.createElement('link'); linkElement.rel = 'stylesheet'; linkElement.href = '/css/glightbox.min.css'; document.head.appendChild(linkElement); const script = document.createElement('script'); script.src = '/js/glightbox.min.js'; script.onload = () => { const lightbox = GLightbox({ loop: true, }); lightbox.on('open', () => { setTimeout(() => { lightbox.nextSlide(); }, 500); }); }; document.head.appendChild(script); }); {{ if eq hugo.Environment "production" }} {{ if $.Site.Params.enableUmami }} document.querySelectorAll('.gallery').forEach(gallery => { const eventName = gallery.dataset.umamiEvent; let canTrack = true; gallery.querySelectorAll('.glightbox').forEach(link => { link.addEventListener('click', () => { if (canTrack) { window.umami?.track(eventName); canTrack = false; setTimeout(() => canTrack = true, 3000); } }); }); }); {{ end }} {{ end }} </script> {{ end }} </body> </html>
19,618
index
html
en
html
code
{"qsc_code_num_words": 1236, "qsc_code_num_chars": 19618.0, "qsc_code_mean_word_length": 5.40291262, "qsc_code_frac_words_unique": 0.20954693, "qsc_code_frac_chars_top_2grams": 0.02755316, "qsc_code_frac_chars_top_3grams": 0.02725367, "qsc_code_frac_chars_top_4grams": 0.0309973, "qsc_code_frac_chars_dupe_5grams": 0.368823, "qsc_code_frac_chars_dupe_6grams": 0.36088649, "qsc_code_frac_chars_dupe_7grams": 0.31985624, "qsc_code_frac_chars_dupe_8grams": 0.31985624, "qsc_code_frac_chars_dupe_9grams": 0.29679545, "qsc_code_frac_chars_dupe_10grams": 0.28960767, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00615907, "qsc_code_frac_chars_whitespace": 0.51998165, "qsc_code_size_file_byte": 19618.0, "qsc_code_num_lines": 397.0, "qsc_code_num_chars_line_max": 188.0, "qsc_code_num_chars_line_mean": 49.41561713, "qsc_code_frac_chars_alphabet": 0.70287777, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.51775148, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.14730618, "qsc_code_frac_chars_long_word_length": 0.01778888, "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_codehtml_cate_ast": 1.0, "qsc_codehtml_frac_words_text": 0.39412784, "qsc_codehtml_num_chars_text": 7732.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": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 1, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_codehtml_cate_ast": 0, "qsc_codehtml_frac_words_text": 0, "qsc_codehtml_num_chars_text": 0}
000haoji/deep-student
src/components/MistakeLibrary.tsx
import React, { useState, useEffect, useMemo } from 'react'; import { TauriAPI, MistakeItem } from '../utils/tauriApi'; import { useSubject } from '../contexts/SubjectContext'; interface MistakeLibraryProps { onSelectMistake: (mistake: MistakeItem) => void; onBack: () => void; // 🎯 修复:添加刷新触发器,每次切换到错题库页面时会变化 refreshTrigger?: number; } export const MistakeLibrary: React.FC<MistakeLibraryProps> = ({ onSelectMistake, onBack, refreshTrigger }) => { const [mistakes, setMistakes] = useState<MistakeItem[]>([]); const [filteredMistakes, setFilteredMistakes] = useState<MistakeItem[]>([]); const [selectedType, setSelectedType] = useState('全部'); const [searchTerm, setSearchTerm] = useState(''); const [loading, setLoading] = useState(false); const [availableTypes, setAvailableTypes] = useState<string[]>([]); // 使用全局科目状态 const { currentSubject } = useSubject(); // 从现有错题数据中提取可用科目 const availableSubjects = useMemo(() => { const subjects = Array.from(new Set(mistakes.map(mistake => mistake.subject).filter(Boolean))); return subjects; }, [mistakes]); // 新增:分页状态 const [currentPage, setCurrentPage] = useState(1); const [itemsPerPage, setItemsPerPage] = useState(12); // 每页显示12个卡片 const [typeDropdownOpen, setTypeDropdownOpen] = useState(false); // 🎯 修复:将loadData提取为独立函数,支持手动刷新 const loadData = async () => { setLoading(true); try { // 加载错题数据 console.log('🔍 [MistakeLibrary] 开始加载错题数据...'); const rawMistakes = await TauriAPI.getMistakes(); console.log('🔍 [MistakeLibrary] 从数据库加载的原始错题数据:', { 错题总数: rawMistakes.length, 前3个错题信息: rawMistakes.slice(0, 3).map(m => ({ id: m.id, questionImagesLength: m.question_images?.length || 0, questionImages: m.question_images, hasQuestionImages: !!m.question_images && m.question_images.length > 0 })) }); // 转换错题数据:为每个错题生成图片URLs const mistakesWithUrls = await Promise.all(rawMistakes.map(async (mistake) => { try { // 转换 question_images (file paths) 为 question_image_urls (URLs) console.log(`🖼️ [图片处理] 错题 ${mistake.id} 的图片路径:`, { questionImages: mistake.question_images, questionImagesLength: mistake.question_images?.length || 0, questionImagesType: typeof mistake.question_images }); if (!mistake.question_images || mistake.question_images.length === 0) { console.log(`⚠️ [图片处理] 错题 ${mistake.id} 没有图片路径`); return { ...mistake, question_image_urls: [] }; } const questionImageUrls = await Promise.all( mistake.question_images.map(async (imagePath, index) => { try { console.log(`🖼️ [图片处理] 正在处理图片 ${index + 1}/${mistake.question_images.length}: "${imagePath}"`); // 添加超时机制 const timeoutPromise = new Promise<never>((_, reject) => { setTimeout(() => reject(new Error('图片加载超时')), 10000); // 10秒超时 }); const base64Promise = TauriAPI.getImageAsBase64(imagePath); const base64Data = await Promise.race([base64Promise, timeoutPromise]); // 检查返回的数据是否已经是完整的data URL const dataUrl = base64Data.startsWith('data:') ? base64Data : `data:image/jpeg;base64,${base64Data}`; console.log(`✅ [图片处理] 图片 ${index + 1} 处理成功`, { 原始数据长度: base64Data.length, 是否已是DataURL: base64Data.startsWith('data:'), 最终URL长度: dataUrl.length, URL前缀: dataUrl.substring(0, 50) }); // 验证生成的data URL if (dataUrl.length < 100) { console.warn(`⚠️ [图片处理] 图片 ${index + 1} 的data URL似乎太短: ${dataUrl.length} 字符`); } return dataUrl; } catch (error) { console.error(`❌ [图片处理] 加载图片失败: "${imagePath}"`, { error, errorMessage: error instanceof Error ? error.message : String(error), mistakeId: mistake.id, imageIndex: index, isTimeout: error instanceof Error && error.message === '图片加载超时' }); return ''; // 返回空字符串作为fallback } }) ); const validUrls = questionImageUrls.filter(url => url !== ''); console.log(`🖼️ [图片处理] 错题 ${mistake.id} 最终图片URLs:`, { 总数量: questionImageUrls.length, 有效数量: validUrls.length, 失败数量: questionImageUrls.length - validUrls.length, validUrlsPreview: validUrls.map((url, i) => `${i+1}: ${url.substring(0, 50)}...`), validUrlsActual: validUrls }); const filteredUrls = questionImageUrls.filter(url => url !== ''); const result = { ...mistake, question_image_urls: filteredUrls // 过滤掉失败的图片 }; console.log(`🔧 [数据组装] 错题 ${mistake.id} 最终结果:`, { 有question_image_urls字段: 'question_image_urls' in result, question_image_urls长度: result.question_image_urls?.length || 0, question_image_urls值: result.question_image_urls }); // 调试日志:检查聊天历史数据 console.log(`🔍 错题 ${mistake.id} 数据结构:`, { id: mistake.id, chatHistoryLength: mistake.chat_history?.length || 0, chatHistoryExists: !!mistake.chat_history, chatHistoryType: typeof mistake.chat_history, chatHistoryFirst: mistake.chat_history?.[0], questionImagesCount: mistake.question_images?.length || 0, questionImageUrlsCount: result.question_image_urls?.length || 0 }); return result; } catch (error) { console.warn(`处理错题图片失败: ${mistake.id}`, error); return { ...mistake, question_image_urls: [] // 如果所有图片都失败,返回空数组 }; } })); const allMistakes = mistakesWithUrls; setMistakes(allMistakes); setFilteredMistakes(allMistakes); // 科目选项现在由全局状态管理 // 动态提取可用的错题类型选项 const types = Array.from(new Set(allMistakes.map(m => m.mistake_type).filter(t => t && t.trim() !== ''))).sort(); setAvailableTypes(types); console.log('加载错题库数据:', { 总数: allMistakes.length, 科目: Array.from(new Set(allMistakes.map(m => m.subject))).sort(), 类型: types }); } catch (error) { console.error('加载错题失败:', error); alert('加载错题失败: ' + error); } finally { setLoading(false); } }; // 🎯 修复:页面切换时自动重新加载数据 useEffect(() => { console.log('🔄 错题库页面加载/刷新,refreshTrigger:', refreshTrigger); loadData(); }, [refreshTrigger]); // 依赖refreshTrigger,每次切换到错题库页面时都会重新加载 // 应用筛选条件 useEffect(() => { let filtered = mistakes; // 使用全局科目状态进行筛选 if (currentSubject && currentSubject !== '全部') { filtered = filtered.filter(m => m.subject === currentSubject); } if (selectedType !== '全部') { filtered = filtered.filter(m => m.mistake_type === selectedType); } if (searchTerm) { filtered = filtered.filter(m => m.user_question.toLowerCase().includes(searchTerm.toLowerCase()) || m.ocr_text.toLowerCase().includes(searchTerm.toLowerCase()) || m.tags.some(tag => tag.toLowerCase().includes(searchTerm.toLowerCase())) ); } setFilteredMistakes(filtered); setCurrentPage(1); // 每次筛选后重置到第一页 console.log('应用筛选条件:', { 科目: currentSubject, 类型: selectedType, 搜索词: searchTerm, 筛选结果: filtered.length }); }, [mistakes, currentSubject, selectedType, searchTerm]); // 处理点击外部关闭下拉框 useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (typeDropdownOpen) { const target = event.target as Node; const dropdown = document.querySelector('.type-dropdown-container'); if (dropdown && !dropdown.contains(target)) { setTypeDropdownOpen(false); } } }; document.addEventListener('mousedown', handleClickOutside); return () => { document.removeEventListener('mousedown', handleClickOutside); }; }, [typeDropdownOpen]); const formatDate = (dateString: string) => { return new Date(dateString).toLocaleDateString('zh-CN', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); }; // 分页逻辑 const paginatedMistakes = useMemo(() => { const startIndex = (currentPage - 1) * itemsPerPage; const endIndex = startIndex + itemsPerPage; return filteredMistakes.slice(startIndex, endIndex); }, [filteredMistakes, currentPage, itemsPerPage]); const totalPages = Math.ceil(filteredMistakes.length / itemsPerPage); const handlePageChange = (newPage: number) => { if (newPage >= 1 && newPage <= totalPages) { setCurrentPage(newPage); } }; return ( <div style={{ width: '100%', background: '#f8fafc' }}> {/* 🎯 修复:添加CSS动画支持 */} <style>{` @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } `}</style> {/* 头部区域 - 统一白色样式 */} <div style={{ background: 'white', borderBottom: '1px solid #e5e7eb', padding: '24px 32px', position: 'relative' }}> <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: '4px', background: 'linear-gradient(90deg, #667eea, #764ba2)' }}></div> <div style={{ position: 'relative', zIndex: 1 }}> <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}> <svg style={{ width: '32px', height: '32px', marginRight: '12px', color: '#667eea' }} fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}> <path d="M12 7v14" /> <path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z" /> </svg> <h1 style={{ fontSize: '28px', fontWeight: '700', margin: 0, color: '#1f2937' }}>错题库</h1> </div> <p style={{ fontSize: '16px', color: '#6b7280', margin: 0, lineHeight: '1.5' }}> 管理和回顾您的错题集合,追踪学习进度和薄弱环节 </p> </div> </div> {/* 筛选器 - 与统一回顾分析一致的样式 */} <div style={{ background: 'white', margin: '0 24px 24px 24px', borderRadius: '16px', padding: '24px', boxShadow: '0 4px 20px rgba(0, 0, 0, 0.05)', border: '1px solid #f1f5f9' }}> <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '20px', alignItems: 'end' }}> {/* 科目筛选现在由全局状态控制 */} <div> <label style={{ display: 'block', fontSize: '14px', fontWeight: '600', color: '#374151', marginBottom: '8px' }}>类型筛选</label> {/* 自定义类型下拉框 - 保持原生样式外观 + 自定义下拉列表 */} <div className="type-dropdown-container" style={{ position: 'relative' }}> <div style={{ width: '100%', padding: '12px 16px', border: '2px solid #e2e8f0', borderRadius: '12px', fontSize: '14px', background: 'white', cursor: 'pointer', transition: 'all 0.2s ease', display: 'flex', justifyContent: 'space-between', alignItems: 'center', minHeight: '20px' }} onClick={() => setTypeDropdownOpen(!typeDropdownOpen)} onMouseOver={(e) => { if (!typeDropdownOpen) { e.currentTarget.style.borderColor = '#667eea'; } }} onMouseOut={(e) => { if (!typeDropdownOpen) { e.currentTarget.style.borderColor = '#e2e8f0'; } }} > <span style={{ color: '#374151' }}> {selectedType === '全部' ? '全部类型' : selectedType} </span> <span style={{ transform: typeDropdownOpen ? 'rotate(180deg)' : 'rotate(0deg)', transition: 'transform 0.2s ease', color: '#6b7280', fontSize: '12px' }}>▼</span> </div> {typeDropdownOpen && ( <div style={{ position: 'absolute', top: '100%', left: 0, right: 0, backgroundColor: '#fff', borderRadius: '12px', border: '1px solid #e0e0e0', marginTop: '8px', boxShadow: '0 6px 16px rgba(0,0,0,0.12)', zIndex: 9999, overflow: 'hidden', maxHeight: '300px', overflowY: 'auto' }}> <div style={{ padding: '12px 16px', cursor: 'pointer', color: '#333', fontSize: '14px', borderBottom: availableTypes.length > 0 ? '1px solid #f0f0f0' : 'none', backgroundColor: selectedType === '全部' ? '#f0f7ff' : 'transparent', transition: 'all 0.2s ease', minHeight: '44px', display: 'flex', alignItems: 'center' }} onClick={() => { setSelectedType('全部'); setTypeDropdownOpen(false); }} onMouseOver={(e) => { if (selectedType !== '全部') { e.currentTarget.style.backgroundColor = '#f7f7f7'; } }} onMouseOut={(e) => { if (selectedType !== '全部') { e.currentTarget.style.backgroundColor = 'transparent'; } }} > 全部类型 </div> {availableTypes.map((type, index) => ( <div key={type} style={{ padding: '12px 16px', cursor: 'pointer', color: '#333', fontSize: '14px', borderBottom: index < availableTypes.length - 1 ? '1px solid #f0f0f0' : 'none', backgroundColor: selectedType === type ? '#f0f7ff' : 'transparent', transition: 'all 0.2s ease', minHeight: '44px', display: 'flex', alignItems: 'center' }} onClick={() => { setSelectedType(type); setTypeDropdownOpen(false); }} onMouseOver={(e) => { if (selectedType !== type) { e.currentTarget.style.backgroundColor = '#f7f7f7'; } }} onMouseOut={(e) => { if (selectedType !== type) { e.currentTarget.style.backgroundColor = 'transparent'; } }} > {type} </div> ))} </div> )} </div> </div> <div> <label style={{ display: 'block', fontSize: '14px', fontWeight: '600', color: '#374151', marginBottom: '8px' }}>搜索</label> <input type="text" placeholder="搜索题目、标签或内容..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} style={{ width: '100%', padding: '12px 16px', border: '2px solid #e2e8f0', borderRadius: '12px', fontSize: '14px', background: 'white', transition: 'all 0.2s ease' }} onFocus={(e) => e.target.style.borderColor = '#667eea'} onBlur={(e) => e.target.style.borderColor = '#e2e8f0'} /> </div> </div> </div> <div className="mistake-library" style={{ padding: '0 24px 24px 24px', background: 'transparent' }}> <div className="library-content"> {loading ? ( <div className="loading">加载中...</div> ) : filteredMistakes.length === 0 ? ( <div className="empty-state"> <p>暂无错题记录</p> <p>开始分析题目来建立您的错题库吧!</p> </div> ) : ( <> <div className="mistakes-grid"> {paginatedMistakes.map((mistake) => ( <div key={mistake.id} className="mistake-card" onClick={() => onSelectMistake(mistake)} > <div className="mistake-header"> <span className="subject-badge">{mistake.subject}</span> <span className="date">{formatDate(mistake.created_at)}</span> </div> <div className="mistake-content"> <h4>{mistake.user_question}</h4> <p className="ocr-preview"> {mistake.ocr_text.length > 100 ? mistake.ocr_text.substring(0, 100) + '...' : mistake.ocr_text } </p> </div> <div className="mistake-tags"> {mistake.tags.slice(0, 3).map((tag, index) => ( <span key={index} className="tag">{tag}</span> ))} {mistake.tags.length > 3 && ( <span className="tag-more">+{mistake.tags.length - 3}</span> )} </div> <div className="mistake-footer"> <span className="type">{mistake.mistake_type}</span> <span className="status">{mistake.status === 'completed' ? '已完成' : '分析中'}</span> </div> </div> ))} </div> {totalPages > 1 && ( <div className="pagination-controls" style={{ marginTop: '24px', display: 'flex', justifyContent: 'center', alignItems: 'center', gap: '8px' }}> <button onClick={() => handlePageChange(currentPage - 1)} disabled={currentPage === 1} style={{ padding: '8px 16px', borderRadius: '8px', border: '1px solid #ddd', cursor: 'pointer', background: currentPage === 1 ? '#f5f5f5' : 'white' }} > 上一页 </button> <span style={{ fontSize: '14px', color: '#333' }}> 第 {currentPage} 页 / 共 {totalPages} 页 </span> <button onClick={() => handlePageChange(currentPage + 1)} disabled={currentPage === totalPages} style={{ padding: '8px 16px', borderRadius: '8px', border: '1px solid #ddd', cursor: 'pointer', background: currentPage === totalPages ? '#f5f5f5' : 'white' }} > 下一页 </button> </div> )} </> )} </div> </div> </div> ); };
20,891
MistakeLibrary
tsx
en
tsx
code
{"qsc_code_num_words": 1594, "qsc_code_num_chars": 20891.0, "qsc_code_mean_word_length": 6.11104141, "qsc_code_frac_words_unique": 0.29109159, "qsc_code_frac_chars_top_2grams": 0.01108716, "qsc_code_frac_chars_top_3grams": 0.01396161, "qsc_code_frac_chars_top_4grams": 0.01077918, "qsc_code_frac_chars_dupe_5grams": 0.24104301, "qsc_code_frac_chars_dupe_6grams": 0.17226157, "qsc_code_frac_chars_dupe_7grams": 0.14433836, "qsc_code_frac_chars_dupe_8grams": 0.11641515, "qsc_code_frac_chars_dupe_9grams": 0.09875783, "qsc_code_frac_chars_dupe_10grams": 0.08541218, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03564892, "qsc_code_frac_chars_whitespace": 0.39844909, "qsc_code_size_file_byte": 20891.0, "qsc_code_num_lines": 552.0, "qsc_code_num_chars_line_max": 178.0, "qsc_code_num_chars_line_mean": 37.84601449, "qsc_code_frac_chars_alphabet": 0.73772579, "qsc_code_frac_chars_comments": 0.02848116, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.39014374, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00205339, "qsc_code_frac_chars_string_length": 0.08750062, "qsc_code_frac_chars_long_word_length": 0.00596147, "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}