MFCApplication1Dlg.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  1. 
  2. // MFCApplication1Dlg.cpp: 实现文件
  3. //
  4. #include "pch.h"
  5. #include "framework.h"
  6. #include "MFCApplication1.h"
  7. #include "MFCApplication1Dlg.h"
  8. #include "afxdialogex.h"
  9. #include "CvxText.h"
  10. #include "BaseUtility.h"
  11. #include "libpdf.h"
  12. #include "AssignWords.h"
  13. #include "lib_common_depence.h"
  14. #include <direct.h>
  15. #include <io.h>
  16. #include "Buffers.h"
  17. #include "Config.h"
  18. #include <curl/curl.h>
  19. #if defined(GNUC)
  20. #pragma GCC diagnostic push
  21. #pragma GCC diagnostic ignored “-Wdeprecated-declarations”
  22. #elif defined(_MSC_VER)
  23. #pragma warning(disable : 4996)
  24. #endif
  25. #include <json/json.h>
  26. #ifdef _DEBUG
  27. #pragma comment(lib, "libpdfd.lib")
  28. #pragma comment(lib, "lib_common_depence_d.lib")
  29. #else
  30. #pragma comment(lib, "libpdf.lib")
  31. #pragma comment(lib, "lib_common_depence.lib")
  32. #endif
  33. #ifdef _DEBUG
  34. #define new DEBUG_NEW
  35. #endif
  36. #define SAFETY_CLOSE_HANDLE( handle ) \
  37. if( NULL != handle ) \
  38. { \
  39. CloseHandle( handle ); \
  40. handle = NULL; \
  41. }
  42. #define SAFETY_EXIT_THREAD( hThread, Timeout ) \
  43. if( NULL != hThread ) \
  44. { \
  45. if( WaitForSingleObject( hThread, Timeout ) == WAIT_TIMEOUT ) \
  46. TerminateThread( hThread, -1 ); \
  47. CloseHandle( hThread ); \
  48. hThread = NULL; \
  49. }
  50. // 用于应用程序“关于”菜单项的 CAboutDlg 对话框
  51. class CAboutDlg : public CDialogEx
  52. {
  53. public:
  54. CAboutDlg();
  55. // 对话框数据
  56. #ifdef AFX_DESIGN_TIME
  57. enum { IDD = IDD_ABOUTBOX };
  58. #endif
  59. protected:
  60. virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
  61. // 实现
  62. protected:
  63. DECLARE_MESSAGE_MAP()
  64. };
  65. CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
  66. {
  67. }
  68. void CAboutDlg::DoDataExchange(CDataExchange* pDX)
  69. {
  70. CDialogEx::DoDataExchange(pDX);
  71. }
  72. BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
  73. END_MESSAGE_MAP()
  74. // CMFCApplication1Dlg 对话框
  75. vector<string> g_vecFileList;//扫描文件列表
  76. int g_scanCount = 0;//扫描文件个数
  77. HANDLE _threadProcess = NULL;
  78. DWORD WINAPI ProcessThread(void *param)
  79. {
  80. CMFCApplication1Dlg* pWnd = (CMFCApplication1Dlg*)theApp.m_pMainWnd;
  81. std::vector<tuple<string, string>> oneList;
  82. std::vector<tuple<string, string>> twoList;
  83. std::vector<tuple<string, string>> errorList;
  84. std::vector<tuple<string, string>> fourList;
  85. int row = 0;
  86. int ret = AssignWordsFromTest(UnicodeToGB2312(pWnd->m_strTextPath), oneList, twoList, errorList, fourList, row);
  87. if (ret < 0)
  88. {
  89. static wchar_t* erroArry[] = { L"未找到答案文件,请校验\r\n", L"题干和答案行数不一致,请确认\r\n",
  90. L"题目文件中第%d行为空,请校验\r\n", L"答案文件中第%d行为空,请校验\r\n" };
  91. wstring erro = L"未知错误";
  92. wchar_t erro2[64] = { 0 };
  93. wchar_t erro3[64] = { 0 };
  94. _stprintf(erro2, erroArry[2], row);
  95. _stprintf(erro3, erroArry[3], row);
  96. switch (ret)
  97. {
  98. default:
  99. break;
  100. case -1:erro = erroArry[0]; break;
  101. case -2:erro = erroArry[1]; break;
  102. case -3:erro = erro2; break;
  103. case -4:erro = erro3; break;
  104. }
  105. SendMessage(pWnd->m_hWnd, WM_SHOWINFO, (WPARAM)erro.c_str(), 1);
  106. return 0L;
  107. }
  108. if (ret == 0)
  109. {
  110. for (auto& iter : errorList)
  111. {
  112. wstring erroInfo;
  113. erroInfo.append(L"题目:");
  114. erroInfo.append(CA2T(std::get<0>(iter).c_str()));
  115. erroInfo.append(L"标准答案:");
  116. erroInfo.append(CA2T(std::get<1>(iter).c_str()));
  117. erroInfo.append(L"有问题\r\n");
  118. SendMessage(pWnd->m_hWnd, WM_SHOWINFO, (WPARAM)erroInfo.c_str(), 0);
  119. }
  120. }
  121. HMODULE module = GetModuleHandle(0);
  122. TCHAR pFileName[MAX_PATH + 2] = { 0 };
  123. GetModuleFileName(module, pFileName, MAX_PATH);
  124. CString csFullPath(pFileName);
  125. int nPos = csFullPath.ReverseFind(_T('\\'));
  126. CString strFileDir = csFullPath.Left(nPos);
  127. CString strFilePath = strFileDir + L"\\config.ini";
  128. WCHAR wgray[10];
  129. GetPrivateProfileString(L"USER", L"GrayPix", L"100", wgray, 10, strFilePath);
  130. int nLineGrayPix = _wtoi(wgray);
  131. auto CovertPdfFunc = [&](std::vector<tuple<string, string>>& vctFiles, int col, int& pageNum){
  132. std::string strPage1;
  133. for (size_t i = 0; i < vctFiles.size(); i += max_line * col)
  134. {
  135. std::vector<tuple<string, string>> vecSmall;
  136. auto last = std::min(vctFiles.size(), i + max_line * col);
  137. vecSmall.insert(vecSmall.begin(), vctFiles.begin() + i, vctFiles.begin() + last);
  138. std::string strPagePath;
  139. dataCollectionPaper(col, pageNum, 30, nLineGrayPix, false, vecSmall, pWnd->m_strPdfDir, strPagePath);
  140. if (strPage1.length() == 0)
  141. {
  142. strPage1 = strPagePath;
  143. }
  144. else
  145. {
  146. CString strPdfPath;
  147. strPdfPath.Format(L"%s/pdf/%d.pdf", pWnd->m_strPdfDir, pageNum);
  148. PdfNewFromImage({ strPage1, strPagePath }, TstringToGB2312(strPdfPath.GetBuffer()));
  149. strPage1 = "";
  150. CString strMsg = L"";
  151. strMsg.Format(L"%s\r\n", strPdfPath);
  152. SendMessage(pWnd->m_hWnd, WM_SHOWINFO, (WPARAM)strMsg.GetBuffer(), 0);
  153. strMsg.ReleaseBuffer();
  154. }
  155. pageNum++;
  156. }
  157. if (strPage1.length() > 0)
  158. {
  159. CString strPdfPath;
  160. strPdfPath.Format(L"%s/pdf/%d.pdf", pWnd->m_strPdfDir, pageNum);
  161. PdfNewFromImage({ strPage1 }, TstringToGB2312(strPdfPath.GetBuffer()));
  162. CString strMsg = L"";
  163. strMsg.Format(L"%s\r\n", strPdfPath);
  164. SendMessage(pWnd->m_hWnd, WM_SHOWINFO, (WPARAM)strMsg.GetBuffer(), 0);
  165. strMsg.ReleaseBuffer();
  166. }
  167. };
  168. int pageNum = _wtoi(pWnd->m_strPageNumber);
  169. CovertPdfFunc(oneList, 1, pageNum);
  170. CovertPdfFunc(twoList, 2, pageNum);
  171. //通知发送消息到窗口
  172. CString strErrorMsg = L"";
  173. strErrorMsg.Format(L"PDF生成完成!\r\n");
  174. SendMessage(pWnd->m_hWnd, WM_SHOWINFO, (WPARAM)strErrorMsg.GetBuffer(), 1);
  175. strErrorMsg.ReleaseBuffer();
  176. return 0L;
  177. }
  178. const static std::string request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting";
  179. static std::string handwriting_result;
  180. /**
  181. * curl发送http请求调用的回调函数,回调函数中对返回的json格式的body进行了解析,解析结果储存在全局的静态变量当中
  182. * @param 参数定义见libcurl文档
  183. * @return 返回值定义见libcurl文档
  184. */
  185. static size_t callback(void *ptr, size_t size, size_t nmemb, void *stream)
  186. {
  187. char * pData = (char *)ptr;
  188. handwriting_result.append(pData, size * nmemb);
  189. // 获取到的body存放在ptr中,先将其转换为string格式
  190. //handwriting_result = std::string((char *)ptr, size * nmemb);
  191. return size * nmemb;
  192. }
  193. /**
  194. * 手写文字识别
  195. * @return 调用成功返回0,发生错误返回其他错误码
  196. */
  197. int handwriting(string strImage, std::string &json_result, const std::string &access_token)
  198. {
  199. handwriting_result = "";
  200. std::string url = request_url + "?access_token=" + access_token;
  201. CURL *curl = NULL;
  202. CURLcode result_code;
  203. int is_success;
  204. curl = curl_easy_init();
  205. if (curl)
  206. {
  207. curl_easy_setopt(curl, CURLOPT_URL, url.data());
  208. curl_easy_setopt(curl, CURLOPT_POST, 1);
  209. curl_httppost *post = NULL;
  210. curl_httppost *last = NULL;
  211. curl_formadd(&post, &last, CURLFORM_COPYNAME, "image", CURLFORM_COPYCONTENTS, strImage.c_str(), CURLFORM_END);
  212. curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
  213. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
  214. result_code = curl_easy_perform(curl);
  215. if (result_code != CURLE_OK)
  216. {
  217. fprintf(stderr, "curl_easy_perform() failed: %s\n",
  218. curl_easy_strerror(result_code));
  219. is_success = 1;
  220. return is_success;
  221. }
  222. UTF8toANSI(handwriting_result);
  223. json_result = handwriting_result;
  224. curl_easy_cleanup(curl);
  225. is_success = 0;
  226. }
  227. else
  228. {
  229. fprintf(stderr, "curl_easy_init() failed.");
  230. is_success = 1;
  231. }
  232. return is_success;
  233. }
  234. void ParseJson(std::string& strJson, vector<std::tuple<cv::Rect, std::string>>& vec)
  235. {
  236. Json::Features features;
  237. Json::Reader reader(features);
  238. Json::Value root;
  239. if (!reader.parse(strJson, root))
  240. {
  241. return;
  242. }
  243. Json::Value words_result = root["words_result"];
  244. if (!words_result.isArray())
  245. {
  246. return;
  247. }
  248. for (int i = 0; i < words_result.size(); i++)
  249. {
  250. Json::Value row = words_result[i];
  251. Json::Value location = row["location"];
  252. cv::Rect rc = cv::Rect(location["left"].asInt(), location["top"].asInt(), location["width"].asInt(), location["height"].asInt());
  253. vec.push_back(make_tuple(rc, row["words"].asString()));
  254. }
  255. }
  256. int IdentifyCallback(result::spinfo& pinfo, void* param)
  257. {
  258. CMFCApplication1Dlg* pWnd = (CMFCApplication1Dlg*)theApp.m_pMainWnd;
  259. if (pinfo.choiceRes.size() < 3 || pinfo.vecUrlAPath.size() == 0)
  260. {
  261. pWnd->PostMessage(WM_PROCESS, NULL, NULL);
  262. pWnd->FormatScanMsg("矫正图像失败原图为:%s", pinfo.vecUrlPath.size() > 0 ? pinfo.vecUrlPath[0].c_str() : "图像为空");
  263. }
  264. std::string strChoiceRes;
  265. for (auto& row : pinfo.choiceRes)
  266. {
  267. for (auto& col : row.vecRes)
  268. {
  269. strChoiceRes.append(col ? "1" : "0");
  270. }
  271. }
  272. int length = strChoiceRes.length();
  273. int number = 0;
  274. for (int i = 0; i < length; ++i)
  275. {
  276. if (strChoiceRes[i] == '1') // 其中注意if的判断两个条件相等的符号
  277. number += pow(2, length - 1 - i);
  278. }
  279. string strToken = CT2A(CConfig::Instance()->m_strToken);
  280. string strResult;
  281. string strEncode = GetImageEncodeString(pinfo.vecUrlAPath[0]);
  282. handwriting(strEncode, strResult, strToken);
  283. vector<std::tuple<cv::Rect, std::string>> vecTranslate;
  284. ParseJson(strResult, vecTranslate);
  285. std::string strJsonDir = CT2A(CConfig::Instance()->m_strMode);
  286. strJsonDir.append("/");
  287. strJsonDir.append(std::to_string(number));
  288. strJsonDir.append(".json");
  289. std::string strSaveDir = CT2A(CConfig::Instance()->m_strCut);
  290. cutPaper(number, strJsonDir, pinfo.vecUrlAPath[0], strSaveDir, vecTranslate);
  291. g_scanCount++;
  292. pWnd->PostMessage(WM_PROCESS, NULL, NULL);
  293. pWnd->FormatScanMsg("生成切割图像:%s", std::to_string(number).c_str());
  294. return 0;
  295. }
  296. enum EnumSearFileType {
  297. file,//扫描文件
  298. dir,//扫描文件夹
  299. };
  300. void GetImages(CString strPath)
  301. {
  302. queue<CString> queuePath;
  303. queuePath.push(strPath);
  304. EnumSearFileType serchType = file;
  305. CFileFind finder;
  306. do
  307. {
  308. bool bFinished = finder.FindFile(queuePath.front() + _T("\\*.JPG"));
  309. while (serchType == file && bFinished)
  310. {
  311. bFinished = finder.FindNextFile();
  312. if (finder.IsDirectory())continue;
  313. CString strPath = finder.GetFilePath();
  314. g_vecFileList.push_back(UnicodeToGB2312(strPath));
  315. }
  316. serchType = dir;
  317. bFinished = finder.FindFile(queuePath.front() + _T("\\*.*"));
  318. while (bFinished)
  319. {
  320. bFinished = finder.FindNextFile();
  321. if (finder.IsDirectory() && !finder.IsDots())
  322. {
  323. queuePath.push(finder.GetFilePath());
  324. }
  325. }
  326. queuePath.pop();
  327. serchType = file;
  328. } while (queuePath.size() > 0);
  329. }
  330. string GetBatchId()
  331. {
  332. SYSTEMTIME st;
  333. GetLocalTime(&st);
  334. char chBuf[24] = { 0 };
  335. sprintf(chBuf, "%02d%02d%02d%02d%02d%02d",
  336. st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
  337. return chBuf;
  338. }
  339. HANDLE _threadScan = NULL;
  340. char* g_strIdentifyMsg[7] = { "正常","内部error","批次号异常","保存路径异常","模板为空","图像列表异常","图像列表不是模板整数倍" };
  341. DWORD WINAPI ScanThread(void *param)
  342. {
  343. g_scanCount = 0;
  344. g_vecFileList.clear();
  345. GetImages(CConfig::Instance()->m_strImg);
  346. CMFCApplication1Dlg* pWnd = (CMFCApplication1Dlg*)theApp.m_pMainWnd;
  347. pWnd->PostMessage(WM_PROCESS, NULL, NULL);
  348. pWnd->FormatScanMsg("启动扫描线程......");
  349. auto exitfun = [&]() {
  350. pWnd->FormatScanMsg("扫描线程退出。");
  351. SendMessage(pWnd->m_hWnd, WM_SHOWSCANINFO, 0, 1);
  352. };
  353. preinfo::templatesInfo temeplatInfo;
  354. preinfo::SubjChiInfo sujChiInfo;
  355. std::string strTempDir = CT2A(CConfig::Instance()->m_strCut);
  356. /*if (_access(strTempDir.c_str(), 0) == -1)
  357. {
  358. _mkdir(strTempDir.c_str());
  359. }*/
  360. int nRet = PareseModeJson(temeplatInfo);
  361. if (nRet)
  362. {
  363. pWnd->FormatScanMsg("模板解析失败!");
  364. exitfun();
  365. return 0;
  366. }
  367. //生成批次号
  368. string strBatchId = GetBatchId();
  369. pWnd->FormatScanMsg("创建批次id:%s", strBatchId.c_str());
  370. nRet = api_processing_images(strBatchId.c_str(),
  371. strTempDir.c_str(),
  372. temeplatInfo,
  373. sujChiInfo,
  374. g_vecFileList,
  375. LOG_AUTO,
  376. false,
  377. OLNS,
  378. IdentifyCallback,
  379. NULL);
  380. ////启动算法扫描功能
  381. if (nRet != RT_OK)
  382. {
  383. if (nRet >= 0 && nRet <= 6)
  384. pWnd->FormatScanMsg("扫描失败,错误描述:%s, errorCode:%d", g_strIdentifyMsg[nRet], nRet);
  385. else
  386. pWnd->FormatScanMsg("扫描失败,errorCode:%d", nRet);
  387. }
  388. exitfun();
  389. return 0L;
  390. }
  391. CMFCApplication1Dlg::CMFCApplication1Dlg(CWnd* pParent /*=nullptr*/)
  392. : CDialogEx(IDD_MFCAPPLICATION1_DIALOG, pParent)
  393. , m_strMsg(_T("")), m_strScanMsg(_T(""))
  394. {
  395. m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
  396. }
  397. void CMFCApplication1Dlg::DoDataExchange(CDataExchange* pDX)
  398. {
  399. CDialogEx::DoDataExchange(pDX);
  400. DDX_Text(pDX, IDC_EDIT_MSG, m_strMsg);
  401. DDX_Text(pDX, IDC_EDIT_SCANMSG, m_strScanMsg);
  402. }
  403. BEGIN_MESSAGE_MAP(CMFCApplication1Dlg, CDialogEx)
  404. ON_WM_SYSCOMMAND()
  405. ON_WM_PAINT()
  406. ON_WM_QUERYDRAGICON()
  407. ON_BN_CLICKED(IDOK, &CMFCApplication1Dlg::OnBnClickedOk)
  408. ON_MESSAGE(WM_SHOWINFO, OnShowInfo)
  409. ON_MESSAGE(WM_SHOWSCANINFO, OnShowScanInfo)
  410. ON_MESSAGE(WM_PROCESS, OnProcessInfo)
  411. ON_BN_CLICKED(IDCANCEL, &CMFCApplication1Dlg::OnBnClickedCancel)
  412. ON_BN_CLICKED(IDC_BTN_TXT, &CMFCApplication1Dlg::OnBnClickedBtnTxt)
  413. ON_BN_CLICKED(IDC_BTN_PDF, &CMFCApplication1Dlg::OnBnClickedBtnPdf)
  414. ON_BN_CLICKED(IDC_BTN_MODEPATH, &CMFCApplication1Dlg::OnBnClickedBtnModepath)
  415. ON_BN_CLICKED(IDC_BTN_IMGPATH, &CMFCApplication1Dlg::OnBnClickedBtnImgpath)
  416. ON_BN_CLICKED(IDC_BTN_CUTPATH, &CMFCApplication1Dlg::OnBnClickedBtnCutpath)
  417. ON_BN_CLICKED(ID_BTN_SCAN, &CMFCApplication1Dlg::OnBnClickedBtnScan)
  418. END_MESSAGE_MAP()
  419. // CMFCApplication1Dlg 消息处理程序
  420. BOOL CMFCApplication1Dlg::OnInitDialog()
  421. {
  422. CDialogEx::OnInitDialog();
  423. // 将“关于...”菜单项添加到系统菜单中。
  424. // IDM_ABOUTBOX 必须在系统命令范围内。
  425. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
  426. ASSERT(IDM_ABOUTBOX < 0xF000);
  427. CMenu* pSysMenu = GetSystemMenu(FALSE);
  428. if (pSysMenu != nullptr)
  429. {
  430. BOOL bNameValid;
  431. CString strAboutMenu;
  432. bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
  433. ASSERT(bNameValid);
  434. if (!strAboutMenu.IsEmpty())
  435. {
  436. pSysMenu->AppendMenu(MF_SEPARATOR);
  437. pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
  438. }
  439. }
  440. // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
  441. // 执行此操作
  442. SetIcon(m_hIcon, TRUE); // 设置大图标
  443. SetIcon(m_hIcon, FALSE); // 设置小图标
  444. CConfig::Instance()->LoadFromINI();
  445. GetDlgItem(IDC_EDIT_TXT)->SetWindowText(CConfig::Instance()->m_strTxt);
  446. GetDlgItem(IDC_EDIT_PDF)->SetWindowText(CConfig::Instance()->m_strPdf);
  447. GetDlgItem(IDC_EDIT_MODEPATH)->SetWindowText(CConfig::Instance()->m_strMode);
  448. GetDlgItem(IDC_EDIT_IMGPATH)->SetWindowText(CConfig::Instance()->m_strImg);
  449. GetDlgItem(IDC_EDIT_CUTPATH)->SetWindowText(CConfig::Instance()->m_strCut);
  450. return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
  451. }
  452. void CMFCApplication1Dlg::OnSysCommand(UINT nID, LPARAM lParam)
  453. {
  454. if ((nID & 0xFFF0) == IDM_ABOUTBOX)
  455. {
  456. CAboutDlg dlgAbout;
  457. dlgAbout.DoModal();
  458. }
  459. else
  460. {
  461. CDialogEx::OnSysCommand(nID, lParam);
  462. }
  463. }
  464. // 如果向对话框添加最小化按钮,则需要下面的代码
  465. // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序,
  466. // 这将由框架自动完成。
  467. void CMFCApplication1Dlg::OnPaint()
  468. {
  469. if (IsIconic())
  470. {
  471. CPaintDC dc(this); // 用于绘制的设备上下文
  472. SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
  473. // 使图标在工作区矩形中居中
  474. int cxIcon = GetSystemMetrics(SM_CXICON);
  475. int cyIcon = GetSystemMetrics(SM_CYICON);
  476. CRect rect;
  477. GetClientRect(&rect);
  478. int x = (rect.Width() - cxIcon + 1) / 2;
  479. int y = (rect.Height() - cyIcon + 1) / 2;
  480. // 绘制图标
  481. dc.DrawIcon(x, y, m_hIcon);
  482. }
  483. else
  484. {
  485. CDialogEx::OnPaint();
  486. }
  487. }
  488. //当用户拖动最小化窗口时系统调用此函数取得光标
  489. //显示。
  490. HCURSOR CMFCApplication1Dlg::OnQueryDragIcon()
  491. {
  492. return static_cast<HCURSOR>(m_hIcon);
  493. }
  494. void CMFCApplication1Dlg::OnBnClickedOk()
  495. {
  496. ((CEdit*)GetDlgItem(IDC_EDIT_TXT))->GetWindowText(m_strTextPath);
  497. ((CEdit*)GetDlgItem(IDC_EDIT_PDF))->GetWindowText(m_strPdfDir);
  498. ((CEdit*)GetDlgItem(IDC_EDIT_PAGE_NUMBER))->GetWindowText(m_strPageNumber);
  499. if (m_strTextPath.GetLength() == 0)
  500. {
  501. AfxMessageBox(L"语料库文件未选择");
  502. return;
  503. }
  504. if (m_strPdfDir.GetLength() == 0)
  505. {
  506. AfxMessageBox(L"PDF文件夹未选择");
  507. return;
  508. }
  509. m_strPageNumber.Trim();
  510. if (m_strPageNumber.GetLength() == 0)
  511. {
  512. AfxMessageBox(L"启始页码未输入");
  513. return;
  514. }
  515. if (m_strPageNumber.SpanIncluding(_T("0123456789")) != m_strPageNumber)
  516. {
  517. AfxMessageBox(L"启始页码不是数字");
  518. return;
  519. }
  520. if (_wtoi(m_strPageNumber.GetBuffer()) > 20000)
  521. {
  522. AfxMessageBox(L"启始页码小于20000");
  523. return;
  524. }
  525. GetDlgItem(IDOK)->EnableWindow(FALSE);
  526. m_strMsg = "";
  527. CString strJsonDir(m_strPdfDir);
  528. strJsonDir.Append(L"\\json");
  529. if (!PathIsDirectory(strJsonDir))
  530. {
  531. ::CreateDirectory(strJsonDir, 0);
  532. }
  533. CString strPdfDir(m_strPdfDir);
  534. strPdfDir.Append(L"\\pdf");
  535. if (!PathIsDirectory(strPdfDir))
  536. {
  537. ::CreateDirectory(strPdfDir, 0);
  538. }
  539. SAFETY_EXIT_THREAD(_threadProcess, 100);
  540. _threadProcess = CreateThread(NULL, 0, ProcessThread, NULL, 0, NULL);
  541. //CDialogEx::OnOK();
  542. }
  543. void CMFCApplication1Dlg::UpdateMsg(CString strMsg)
  544. {
  545. m_strMsg += strMsg;
  546. UpdateData(FALSE);
  547. }
  548. void CMFCApplication1Dlg::UpdateScanMsg(CString strMsg)
  549. {
  550. m_strScanMsg += strMsg;
  551. UpdateData(FALSE);
  552. }
  553. LRESULT CMFCApplication1Dlg::OnShowInfo(WPARAM wParam, LPARAM lParam)
  554. {
  555. wchar_t* p = (wchar_t*)wParam;
  556. CString str;
  557. str.Format(_T("%s"), p);
  558. m_strMsg += str;
  559. UpdateData(FALSE);
  560. if (lParam == 1)
  561. {
  562. GetDlgItem(IDOK)->EnableWindow(TRUE);
  563. }
  564. return 0;
  565. }
  566. LRESULT CMFCApplication1Dlg::OnShowScanInfo(WPARAM wParam, LPARAM lParam)
  567. {
  568. if (lParam == 1)
  569. {
  570. GetDlgItem(ID_BTN_SCAN)->EnableWindow(TRUE);
  571. return 0;
  572. }
  573. wchar_t* p = (wchar_t*)wParam;
  574. CString str;
  575. str.Format(_T("%s"), p);
  576. m_strScanMsg += str;
  577. UpdateData(FALSE);
  578. return 0;
  579. }
  580. LRESULT CMFCApplication1Dlg::OnProcessInfo(WPARAM wParam, LPARAM lParam)
  581. {
  582. CString strProcess = _T("--");
  583. if (g_vecFileList.size())
  584. {
  585. float fProcess = (float)g_scanCount / (float)g_vecFileList.size();
  586. strProcess.Format(L"%0.0lf%%", fProcess*100);
  587. }
  588. SetDlgItemText(IDC_EDIT_SCANPROCESS, strProcess);
  589. return 0;
  590. }
  591. void CMFCApplication1Dlg::OnBnClickedCancel()
  592. {
  593. SAFETY_EXIT_THREAD(_threadProcess, 100);
  594. SAFETY_EXIT_THREAD(_threadScan, 100);
  595. CConfig::Instance()->SaveSetting();
  596. CDialogEx::OnCancel();
  597. }
  598. void CMFCApplication1Dlg::SelectFolder(HWND hwnd, CString& lpszFolder)
  599. {
  600. TCHAR szFolderPath[MAX_PATH];
  601. szFolderPath[0] = 0;
  602. BROWSEINFO sInfo;
  603. ::ZeroMemory(&sInfo, sizeof(BROWSEINFO));
  604. sInfo.pidlRoot = 0;
  605. sInfo.lpszTitle = _T("请选择一个文件夹");
  606. sInfo.ulFlags = BIF_DONTGOBELOWDOMAIN | BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE | BIF_EDITBOX;
  607. sInfo.lpfn = NULL;
  608. sInfo.hwndOwner = hwnd;
  609. LPITEMIDLIST lpidlBrowse = ::SHBrowseForFolder(&sInfo);
  610. if (lpidlBrowse != NULL) {
  611. if (::SHGetPathFromIDList(lpidlBrowse, szFolderPath)) {
  612. lpszFolder = szFolderPath;
  613. lpszFolder.Replace('\\', '/');
  614. }
  615. ::CoTaskMemFree(lpidlBrowse);
  616. }
  617. }
  618. void CMFCApplication1Dlg::SelectFile(CString& lpszFile)
  619. {
  620. CString OpenFilter = _T("文本文件(*.txt)|*.txt;|");
  621. CFileDialog FileOpen(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, OpenFilter);
  622. if (IDOK == FileOpen.DoModal())
  623. {
  624. lpszFile = FileOpen.GetPathName();
  625. lpszFile.Replace('\\', '/');
  626. }
  627. }
  628. void CMFCApplication1Dlg::OnBnClickedBtnTxt()
  629. {
  630. CEdit* pEdit = (CEdit*)GetDlgItem(IDC_EDIT_TXT);
  631. if (!pEdit)
  632. {
  633. return;
  634. }
  635. CString strText;
  636. SelectFile(strText);
  637. if (strText.GetLength() == 0)
  638. {
  639. return;
  640. }
  641. pEdit->SetWindowText(strText);
  642. CConfig::Instance()->m_strTxt = strText;
  643. }
  644. void CMFCApplication1Dlg::OnBnClickedBtnPdf()
  645. {
  646. CEdit* pEdit = (CEdit*)GetDlgItem(IDC_EDIT_PDF);
  647. if (!pEdit)
  648. {
  649. return;
  650. }
  651. CString strText;
  652. SelectFolder(GetSafeHwnd(), strText);
  653. if (strText.GetLength() == 0)
  654. {
  655. return;
  656. }
  657. pEdit->SetWindowText(strText);
  658. CConfig::Instance()->m_strPdf = strText;
  659. }
  660. void CMFCApplication1Dlg::OnBnClickedBtnModepath()
  661. {
  662. CEdit* pEdit = (CEdit*)GetDlgItem(IDC_EDIT_MODEPATH);
  663. if (!pEdit)
  664. {
  665. return;
  666. }
  667. CString strText;
  668. SelectFolder(GetSafeHwnd(), strText);
  669. if (strText.GetLength() == 0)
  670. {
  671. return;
  672. }
  673. pEdit->SetWindowText(strText);
  674. CConfig::Instance()->m_strMode = strText;
  675. }
  676. void CMFCApplication1Dlg::OnBnClickedBtnImgpath()
  677. {
  678. CEdit* pEdit = (CEdit*)GetDlgItem(IDC_EDIT_IMGPATH);
  679. if (!pEdit)
  680. {
  681. return;
  682. }
  683. CString strText;
  684. SelectFolder(GetSafeHwnd(), strText);
  685. if (strText.GetLength() == 0)
  686. {
  687. return;
  688. }
  689. pEdit->SetWindowText(strText);
  690. CConfig::Instance()->m_strImg = strText;
  691. }
  692. void CMFCApplication1Dlg::OnBnClickedBtnCutpath()
  693. {
  694. CEdit* pEdit = (CEdit*)GetDlgItem(IDC_EDIT_CUTPATH);
  695. if (!pEdit)
  696. {
  697. return;
  698. }
  699. CString strText;
  700. SelectFolder(GetSafeHwnd(), strText);
  701. if (strText.GetLength() == 0)
  702. {
  703. return;
  704. }
  705. pEdit->SetWindowText(strText);
  706. CConfig::Instance()->m_strCut = strText;
  707. }
  708. void CMFCApplication1Dlg::OnBnClickedBtnScan()
  709. {
  710. ((CEdit*)GetDlgItem(IDC_EDIT_MODEPATH))->GetWindowText(m_strModePath);
  711. ((CEdit*)GetDlgItem(IDC_EDIT_IMGPATH))->GetWindowText(m_strImgPath);
  712. ((CEdit*)GetDlgItem(IDC_EDIT_CUTPATH))->GetWindowText(m_strCutPath);
  713. if (m_strModePath.GetLength() == 0)
  714. {
  715. AfxMessageBox(L"模板文件夹未选择");
  716. return;
  717. }
  718. if (m_strImgPath.GetLength() == 0)
  719. {
  720. AfxMessageBox(L"答题卡文件夹未选择");
  721. return;
  722. }
  723. if (m_strCutPath.GetLength() == 0)
  724. {
  725. AfxMessageBox(L"切割生成文件夹未选择");
  726. return;
  727. }
  728. GetDlgItem(ID_BTN_SCAN)->EnableWindow(FALSE);
  729. m_strScanMsg = "";
  730. CString strNormal(m_strCutPath);
  731. strNormal.Append(L"/normal");
  732. if (!PathIsDirectory(strNormal))
  733. {
  734. ::CreateDirectory(strNormal, 0);
  735. }
  736. CString strAbnormal(m_strCutPath);
  737. strAbnormal.Append(L"/abnormal");
  738. if (!PathIsDirectory(strAbnormal))
  739. {
  740. ::CreateDirectory(strAbnormal, 0);
  741. }
  742. CString strNormalSmall(m_strCutPath);
  743. strNormalSmall.Append(L"/normal_small");
  744. if (!PathIsDirectory(strNormalSmall))
  745. {
  746. ::CreateDirectory(strNormalSmall, 0);
  747. }
  748. CString strAbnormalSmall(m_strCutPath);
  749. strAbnormalSmall.Append(L"/abnormal_small");
  750. if (!PathIsDirectory(strAbnormalSmall))
  751. {
  752. ::CreateDirectory(strAbnormalSmall, 0);
  753. }
  754. SAFETY_EXIT_THREAD(_threadScan, 100);
  755. _threadScan = CreateThread(NULL, 0, ScanThread, NULL, 0, NULL);
  756. }
  757. void CMFCApplication1Dlg::FormatScanMsg(const char *szFmt, ...)
  758. {
  759. if (!szFmt)
  760. return;
  761. va_list ap;
  762. va_start(ap, szFmt);
  763. size_t nLength = _vsnprintf(nullptr, 0, szFmt, ap) + 1;
  764. CBuffers buffer;
  765. char* szLogMsg = buffer.GetBuf(nLength);
  766. _vsnprintf(szLogMsg, nLength, szFmt, ap);
  767. va_end(ap);
  768. SYSTEMTIME st;
  769. GetLocalTime(&st);
  770. char chBuf[24] = { 0 };
  771. sprintf(chBuf, "%02d-%02d-%02d %02d:%02d:%02d ",
  772. st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
  773. CString strMsg;
  774. // 扫描异常
  775. strMsg.Format(L"%s %s\r\n", GB2312ToTstring(chBuf).c_str(), GB2312ToTstring(szLogMsg).c_str());
  776. SendMessage(WM_SHOWSCANINFO, (WPARAM)strMsg.GetBuffer(), 0);
  777. }