AutoTest.swift 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. //
  2. // AutoTest.swift
  3. // KdanAuto
  4. //
  5. // Created by 朱东勇 on 2022/11/25.
  6. //
  7. import Foundation
  8. import AppKit
  9. var cacheObjects = NSMutableDictionary()
  10. let operateQueue = OperationQueue()
  11. class AutoTest : NSObject, AutoTestProtocal {
  12. var reportString : NSMutableAttributedString? = nil
  13. public var _status : AutoTestStatus = .Normal
  14. var _fileType : String = "RTF"
  15. var _type : String = "Others"
  16. var _extention : String = "rtf"
  17. var _name : String = "对照测试"
  18. var _params : NSDictionary = [:]
  19. var testFiles : NSArray = NSArray()
  20. var convertFiles : NSMutableArray = NSMutableArray()
  21. var convertProgress : Double = 0.0
  22. var compareFinishedFiles : NSMutableArray = NSMutableArray()
  23. var compareProgress : Double = 0.0
  24. var testlog : (_ msg:String, _ progress:Double) -> () = {(msg, progress) in
  25. }
  26. class func autoTestFor(_ fileType:NSString ,type:NSString) -> AutoTest? {
  27. let key = String(fileType) + "." + String(type)
  28. if cacheObjects.value(forKey: key) != nil {
  29. let object = cacheObjects.value(forKey: key)
  30. return object as? AutoTest
  31. }
  32. // if let cacheObject as AutoTest {
  33. // return cacheObject
  34. // }
  35. let fileTypes = testTypeInfo[fileType] as! NSArray
  36. let clsname = "KdanAuto"//Bundle.main.infoDictionary! ["CFBundleExecutable"]
  37. for item in fileTypes {
  38. let cItem = item as! NSDictionary
  39. let cType = cItem["Type"] as! NSString
  40. let cExtention = cItem["Extention"] as! NSString
  41. let cName = cItem["Name"] as! NSString
  42. let cParams = cItem["Params"] as? NSDictionary
  43. if (cType.isEqual(to: type)) {
  44. let className = String((clsname )+"."+(cItem["Class"] as! String))
  45. let cl = NSClassFromString(className) as! AutoTest.Type
  46. let object = cl.shared()
  47. object?._fileType = fileType as String
  48. object?._type = String(cType)
  49. object?._extention = String(cExtention)
  50. object?._name = String(cName)
  51. if nil != cParams {
  52. object?._params = cParams ?? [:];
  53. }
  54. cacheObjects.setValue(object, forKey: key)
  55. return object
  56. }
  57. }
  58. let object = AutoTest.shared()
  59. object?._fileType = fileType as String
  60. object?._type = String(cType)
  61. object?._extention = ""
  62. object?._name = "对照测试"
  63. cacheObjects.setValue(object, forKey: key)
  64. return object
  65. }
  66. class func shared() -> AutoTest? {
  67. return AutoTest()
  68. }
  69. func fileType() -> String {
  70. return _fileType
  71. }
  72. func type() -> String {
  73. return _type
  74. }
  75. func name() -> String {
  76. return _name
  77. }
  78. func extention() -> String {
  79. return _extention
  80. }
  81. func params() -> NSDictionary {
  82. return _params
  83. }
  84. func keys() -> NSArray {
  85. return ["快照"]
  86. }
  87. func selectedKeys() -> NSArray {
  88. let userDefaults = UserDefaults.standard
  89. let key = self.fileType() + "." + self.type() + ".selectedKeys"
  90. if userDefaults.value(forKey: key) != nil {
  91. return userDefaults.value(forKey: key) as! NSArray
  92. }
  93. self.setSelectedKeys(self.keys())
  94. return self.keys()
  95. }
  96. func setSelectedKeys(_ keys: NSArray) {
  97. let userDefaults = UserDefaults.standard
  98. let key = self.fileType() + "." + self.type() + ".selectedKeys"
  99. userDefaults.setValue(keys, forKey: key)
  100. userDefaults.synchronize()
  101. }
  102. func needCompareTest() -> Bool {
  103. return self.selectedKeys().contains("快照")
  104. }
  105. func status() -> AutoTestStatus {
  106. return _status
  107. }
  108. func setStatus(_ status:AutoTestStatus) {
  109. _status = status
  110. }
  111. // Auto Test
  112. func autoTest(_ complention:@escaping (_ object:AutoTest, _ report:NSAttributedString?) -> ()) {
  113. self.compareFinishedFiles.removeAllObjects();
  114. self.convertFiles.removeAllObjects()
  115. NSLog(String("转换\(self.type())"))
  116. let needCompare = self.selectedKeys().contains("快照")
  117. if !needCompare {
  118. // 未勾选 ”快照“ 选项
  119. self._status = .Finished
  120. complention(self, self.reportString)
  121. return
  122. }
  123. clearCacheFiles()
  124. if hasOriginFile() {
  125. //目录中有需要执行对照的文件
  126. DispatchQueue.global().async {
  127. autoreleasepool {
  128. self._status = .Process
  129. self.reportString = NSMutableAttributedString.init(string: "\n【\(String(self.fileType())) - \(self.name())】快照比对开始!\n",
  130. attributes:[.foregroundColor : NSColor.blue])
  131. let files = DataModel.shared.originFilesFor(self.fileType(), type: self.type()) as [String]
  132. self.testFiles = NSArray(array: files);
  133. let checkDirectory = self.checkFileDirectory()
  134. let originDirectory = self.originFileDirectory()
  135. let resultDirectory = self.resultFileDirectory()
  136. if (files.count > 0) {
  137. try? FileManager.default.createDirectory(atPath: checkDirectory, withIntermediateDirectories: true);
  138. try? FileManager.default.createDirectory(atPath: resultDirectory, withIntermediateDirectories: true);
  139. }
  140. var tDegree = Double(0);
  141. var tCount = Int(0)
  142. var fileIndex = 0
  143. var compareIndex = 0;
  144. var convertFinished = false;
  145. // 用 Block 递归调用形式,确保转档单任务执行
  146. var convertFileBlock = { (files:[String]) in }
  147. convertFileBlock = { (files:[String]) in
  148. if (fileIndex >= files.count) {
  149. convertFinished = true;
  150. return
  151. }
  152. //
  153. let fileName = files[fileIndex];
  154. autoreleasepool {
  155. let checkDirectory = self.checkFileDirectory()
  156. let originDirectory = self.originFileDirectory()
  157. let resultDirectory = self.resultFileDirectory()
  158. let fName = NSString(string: fileName).deletingPathExtension
  159. let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  160. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+self.extention())
  161. // let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  162. // self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】开始转换文件 \"\(fName)\"\n",
  163. // attributes:[.foregroundColor : NSColor.blue]))
  164. // ...
  165. // 执行异步转换过程
  166. let index = self.testFiles.index(of: fileName);
  167. if (index != NSNotFound) {
  168. self.convertProgress = Double(index) / Double(self.testFiles.count)
  169. }
  170. self.convertFiles.add(fileName);
  171. self.testlog("开始转换:"+fileName, (self.compareProgress + self.convertProgress)/2.0)
  172. self.process(originPath, resultPath: resultPath) { status in
  173. DispatchQueue.global().async {
  174. Thread.sleep(forTimeInterval: 0.3)
  175. fileIndex += 1;
  176. convertFileBlock(files)
  177. self.compareResult(fileName, resultPath: resultPath, status: status, needCompare: needCompare) { degree in
  178. autoreleasepool {
  179. if (degree >= 0.0) {
  180. tDegree += degree;
  181. tCount += 1;
  182. }
  183. compareIndex += 1;
  184. if (convertFinished && compareIndex >= files.count) {
  185. //所有任务已经执行完成
  186. TestDegreeManager.shared().set(((tCount != 0) ? tDegree/Double(tCount) : 0.0),
  187. fileType: self.fileType(),
  188. type: self.type())
  189. self._status = .Finished
  190. DispatchQueue.main.async {
  191. complention(self, self.reportString);
  192. }
  193. }
  194. }
  195. };
  196. }
  197. }
  198. }
  199. }
  200. // 启动第0号任务
  201. convertFileBlock(files);
  202. }
  203. }
  204. }else {
  205. _status = .Normal
  206. DispatchQueue.main.async {
  207. autoreleasepool {
  208. complention(self, nil)
  209. }
  210. }
  211. }
  212. }
  213. func process(_ originPath:String, resultPath:String, complention:@escaping (_ status:Int) -> ()) {
  214. return process(originPath, resultPath: resultPath, params: self.params(), complention: complention)
  215. }
  216. func process(_ originPath:String, resultPath:String, params:NSDictionary, complention:@escaping (_ status:Int) -> ()) {
  217. FileConverter.shared().converter(originPath, inDesPath: resultPath, params: params) { status in
  218. // 修复转 PNG 实际图片为 JPG 问题, 导致无法匹配问题
  219. if (NSArray(array: ["png", "PNG"]).contains(NSString(string: resultPath).pathExtension)) {
  220. let items = (FileManager.default.subpaths(atPath: resultPath) ?? []) as [String]
  221. for item in items {
  222. if NSArray(array: ["jpg", "JPG"]).contains(NSString(string:item).pathExtension) {
  223. let path = NSString(string: resultPath).appendingPathComponent(item);
  224. try? FileManager.default.moveItem(atPath: path,
  225. toPath: NSString(string: path).deletingPathExtension+".png");
  226. }
  227. }
  228. }
  229. complention(status)
  230. }
  231. }
  232. func compareResult(_ fileName:String, resultPath:String, status:Int, needCompare:Bool, complention:@escaping (_ degree:Double) -> ()) {
  233. NSLog("开始识别:\(fileName)")
  234. self.testlog("开始对比:"+fileName, (self.convertProgress + self.compareProgress)/2.0)
  235. let checkDirectory = self.checkFileDirectory()
  236. // let originDirectory = self.originFileDirectory()
  237. let resultDirectory = self.resultFileDirectory()
  238. let fName = NSString(string: fileName).deletingPathExtension
  239. var isDirectory = ObjCBool(false)
  240. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) && status == 1 {
  241. // compare screenshoot between result file with check file
  242. if needCompare {
  243. let items = NSMutableArray()
  244. if (isDirectory.boolValue) {
  245. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  246. for item in NSArray(array: searchItems) {
  247. let ext = NSString(string: item as! String).pathExtension.lowercased()
  248. if (NSArray(array: [self.extention()]).contains(ext)) {
  249. let fileName = NSString(string: fName+"."+self.extention()+"/\(item as! String)").deletingPathExtension
  250. items.add(fileName)
  251. }
  252. }
  253. }else {
  254. items.add(fName)
  255. }
  256. var subDegree = Double(0);
  257. var subCount = Int(0)
  258. var itemIndex = 0;
  259. // let maxProcessCount = min(3, max(items.count, 1))
  260. var processItemBlock = {(items:NSMutableArray) in
  261. }
  262. processItemBlock = {(items:NSMutableArray) in
  263. if (itemIndex >= items.count) {
  264. // if (itemIndex >= (items.count + (maxProcessCount - 1))) {
  265. if subCount != 0 {
  266. subDegree = subDegree/Double(subCount)
  267. }else {
  268. subDegree = 0.0
  269. }
  270. TestDegreeManager.shared().set(subDegree,
  271. fileType: self.fileType(),
  272. type: self.type(),
  273. fileName: fileName)
  274. DispatchQueue.global().async {
  275. autoreleasepool {
  276. // 执行下一个文件转档
  277. complention(subDegree)
  278. NSLog("结束识别:\(fileName)");
  279. let index = self.testFiles.index(of: fileName);
  280. if (index != NSNotFound) {
  281. self.compareProgress = Double(index) / Double(self.testFiles.count)
  282. }
  283. self.compareFinishedFiles.add(fileName);
  284. self.testlog("对比完成:"+fileName, (self.compareProgress + self.convertProgress)/2.0)
  285. }
  286. }
  287. // }
  288. return
  289. }
  290. DispatchQueue.global().async {
  291. autoreleasepool {
  292. let item = items[itemIndex]
  293. NSLog("\(itemIndex):\(item)")
  294. let subFileName = item as! String
  295. let subResultPath = NSString(string: resultDirectory).appendingPathComponent(subFileName+"."+self.extention())
  296. objc_sync_enter(self)
  297. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subFileName+".\(self.extention())")\"快照生成中\n",
  298. attributes:[.foregroundColor : NSColor.black]))
  299. objc_sync_exit(self)
  300. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  301. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  302. ProcessThumbnal.process(subResultPath, desPath: rComparePath, outputSize: CGSize.init(width: 2048, height: 2048)) { processSuccess in
  303. autoreleasepool {
  304. if ( processSuccess &&
  305. FileManager.default.fileExists(atPath: rComparePath)) {
  306. var isDirectory = ObjCBool(false)
  307. if FileManager.default.fileExists(atPath: rComparePath, isDirectory: &isDirectory) && isDirectory.boolValue {
  308. // 单个文件生成批量快照目录情形
  309. let subImages = try! FileManager.default.contentsOfDirectory(atPath: rComparePath)
  310. var compareCount = 0;
  311. for sImageName in subImages {
  312. let subImageName = sImageName
  313. autoreleasepool {
  314. let pathCompotent = "/"+subImageName
  315. ImageProcess.compareJPEG(String(rComparePath+pathCompotent), checkPath: String(cComparePath+pathCompotent), processCover: true, complention: { degree in
  316. NSLog(String("文件夹,\(subFileName+".jpg"+pathCompotent)"))
  317. TestDegreeManager.shared().set(degree, fileType: self.fileType(), type: self.type(),
  318. fileName: fileName, refFilePath: subFileName+".jpg"+pathCompotent)
  319. if degree == -1 {
  320. objc_sync_enter(self)
  321. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath+pathCompotent)\"快照对比失败,生成快照失败或无比对文件\n",
  322. attributes:[.foregroundColor : NSColor.red]))
  323. objc_sync_exit(self)
  324. }else {
  325. var color = NSColor.black
  326. if fabs(degree-100.0) >= 0.01 {
  327. color = NSColor.red
  328. }
  329. subDegree += degree
  330. subCount += 1
  331. objc_sync_enter(self)
  332. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath+pathCompotent)\"快照对比完成,图像相似度 \(degree)%\n",
  333. attributes:[.foregroundColor : color]))
  334. objc_sync_exit(self)
  335. }
  336. compareCount += 1
  337. if (compareCount >= subImages.count) {
  338. DispatchQueue.global().async {
  339. autoreleasepool {
  340. itemIndex += 1
  341. processItemBlock(items)
  342. }
  343. }
  344. }
  345. })
  346. }
  347. }
  348. if (subImages.count == 0) {
  349. // complention
  350. DispatchQueue.global().async {
  351. autoreleasepool {
  352. itemIndex += 1
  353. processItemBlock(items)
  354. }
  355. }
  356. return
  357. }
  358. }else {
  359. // 单个文件生成单个快照文件情形
  360. ImageProcess.compareJPEG(rComparePath, checkPath: cComparePath, processCover: true, complention: { degree in
  361. NSLog(String("非文件夹,\(subFileName+".jpg")"))
  362. TestDegreeManager.shared().set(degree, fileType: self.fileType(), type: self.type(),
  363. fileName: fileName, refFilePath: subFileName+".jpg")
  364. if degree == -1 {
  365. objc_sync_enter(self)
  366. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath)\"快照对比失败,生成快照失败或无比对文件\n",
  367. attributes:[.foregroundColor : NSColor.red]))
  368. objc_sync_exit(self)
  369. }else {
  370. var color = NSColor.black
  371. if fabs(degree-100.0) >= 0.01 {
  372. color = NSColor.red
  373. }
  374. subDegree += degree
  375. subCount += 1
  376. objc_sync_enter(self)
  377. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath)\"快照对比完成,图像相似度 \(degree)%\n",
  378. attributes:[.foregroundColor : color]))
  379. objc_sync_exit(self)
  380. }
  381. // complention
  382. DispatchQueue.global().async {
  383. autoreleasepool {
  384. itemIndex += 1
  385. processItemBlock(items)
  386. }
  387. }
  388. })
  389. }
  390. }else {
  391. objc_sync_enter(self)
  392. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath)\"快照生成失败\n",
  393. attributes:[.foregroundColor : NSColor.red]))
  394. objc_sync_exit(self)
  395. // complention
  396. DispatchQueue.global().async {
  397. autoreleasepool {
  398. itemIndex += 1
  399. processItemBlock(items)
  400. }
  401. }
  402. }
  403. }
  404. }
  405. }
  406. }
  407. }
  408. processItemBlock(items)
  409. // while (itemIndex < (maxProcessCount - 1)) {
  410. // itemIndex += 1;
  411. // processItemBlock(items)
  412. // }
  413. return
  414. }
  415. }else {
  416. if (status == 0) {
  417. objc_sync_enter(self)
  418. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"转档失败!\n",
  419. attributes:[.foregroundColor : NSColor.red]))
  420. objc_sync_exit(self)
  421. }else if (status == -1 || status == -2) {
  422. objc_sync_enter(self)
  423. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"文档无法打开!\n",
  424. attributes:[.foregroundColor : NSColor.red]))
  425. objc_sync_exit(self)
  426. }else if (status == -3) {
  427. objc_sync_enter(self)
  428. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"转档中 Crash!\n",
  429. attributes:[.foregroundColor : NSColor.red]))
  430. objc_sync_exit(self)
  431. }
  432. }
  433. DispatchQueue.global().async {
  434. autoreleasepool {
  435. // 执行下一个文件转档
  436. NSLog("结束识别:\(fileName)");
  437. objc_sync_exit(self)
  438. let index = self.testFiles.index(of: fileName);
  439. if (index != NSNotFound) {
  440. self.compareProgress = Double(index) / Double(self.testFiles.count)
  441. }
  442. self.compareFinishedFiles.add(fileName);
  443. objc_sync_exit(self)
  444. self.testlog("对比完成:"+fileName, (self.compareProgress + self.convertProgress)/2.0)
  445. complention(0)
  446. }
  447. }
  448. }
  449. ///
  450. func testReport() -> NSAttributedString? {
  451. return reportString
  452. }
  453. func degree() -> Double {
  454. return TestDegreeManager.shared().degreeFor(self.fileType(), type: self.type())
  455. }
  456. // func testReportOfFile(_ fileName:String) -> NSAttributedString? {
  457. //
  458. // }
  459. func degreeOfFile(_ fileName:String) -> Double {
  460. return TestDegreeManager.shared().degreeFor(self.fileType(), type: self.type(), fileName: fileName)
  461. }
  462. func degreeOfFile(_ fileName:String, refFilePath:String?) -> Double {
  463. if refFilePath != nil {
  464. return TestDegreeManager.shared().degreeFor(self.fileType(), type: self.type(), fileName: fileName, refFilePath: refFilePath)
  465. }else {
  466. return degreeOfFile(fileName)
  467. }
  468. }
  469. // Update Refrence image
  470. func canUpdateRefImage() -> Bool {
  471. let files = DataModel.shared.originFilesFor(_fileType, type: _type) as [String]
  472. let checkDirectory = self.checkFileDirectory()
  473. // let originDirectory = self.originFileDirectory()
  474. let resultDirectory = self.resultFileDirectory()
  475. for fileName:String in files {
  476. let fName = NSString(string: fileName).deletingPathExtension
  477. // let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  478. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  479. // let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  480. var isDirectory = ObjCBool(false)
  481. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  482. // compare screenshoot between result file with check file
  483. let items = NSMutableArray()
  484. if (isDirectory.boolValue) {
  485. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  486. for item in NSArray(array: searchItems) {
  487. let ext = NSString(string: item as! String).pathExtension.lowercased()
  488. if NSArray(array: [_extention]).contains(ext) {
  489. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  490. items.add(fileName)
  491. }
  492. }
  493. }else {
  494. items.add(fName)
  495. }
  496. for item in NSArray(array: items) {
  497. let subFileName = item as! String
  498. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  499. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  500. if FileManager.default.fileExists(atPath: rComparePath) {
  501. if !FileManager.default.fileExists(atPath: cComparePath) {
  502. return true
  503. }
  504. let rfs = try! FileManager.default.attributesOfItem(atPath: rComparePath)[FileAttributeKey.size] as! NSNumber
  505. let cfs = try! FileManager.default.attributesOfItem(atPath: cComparePath)[FileAttributeKey.size] as! NSNumber
  506. if rfs.int64Value != cfs.int64Value {
  507. return true
  508. }
  509. }
  510. }
  511. }
  512. }
  513. return false
  514. }
  515. func updateRefImage() {
  516. let files = DataModel.shared.originFilesFor(_fileType, type: _type) as [String]
  517. for fileName in files {
  518. updateRefImage(fileName)
  519. }
  520. }
  521. func canUpdateRefImage(_ fileName:String) -> Bool {
  522. let checkDirectory = self.checkFileDirectory()
  523. // let originDirectory = self.originFileDirectory()
  524. let resultDirectory = self.resultFileDirectory()
  525. let fName = NSString(string: fileName).deletingPathExtension
  526. // let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  527. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  528. // let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  529. var isDirectory = ObjCBool(false)
  530. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  531. // compare screenshoot between result file with check file
  532. let items = NSMutableArray()
  533. if (isDirectory.boolValue) {
  534. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  535. for item in NSArray(array: searchItems) {
  536. let ext = NSString(string: item as! String).pathExtension.lowercased()
  537. if NSArray(array: [_extention]).contains(ext) {
  538. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  539. items.add(fileName)
  540. }
  541. }
  542. }else {
  543. items.add(fName)
  544. }
  545. for item in NSArray(array: items) {
  546. let subFileName = item as! String
  547. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  548. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  549. if FileManager.default.fileExists(atPath: rComparePath) {
  550. if !FileManager.default.fileExists(atPath: cComparePath) {
  551. return true
  552. }
  553. let rfs = try! FileManager.default.attributesOfItem(atPath: rComparePath)[FileAttributeKey.size] as! NSNumber
  554. let cfs = try! FileManager.default.attributesOfItem(atPath: cComparePath)[FileAttributeKey.size] as! NSNumber
  555. if rfs.int64Value != cfs.int64Value {
  556. return true
  557. }
  558. }
  559. }
  560. }
  561. return false
  562. }
  563. func updateRefImage(_ fileName:String) {
  564. let checkDirectory = self.checkFileDirectory()
  565. // let originDirectory = self.originFileDirectory()
  566. let resultDirectory = self.resultFileDirectory()
  567. let fName = NSString(string: fileName).deletingPathExtension
  568. // let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  569. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  570. // let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  571. var isDirectory = ObjCBool(false)
  572. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  573. // compare screenshoot between result file with check file
  574. let items = NSMutableArray()
  575. if (isDirectory.boolValue) {
  576. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  577. for item in NSArray(array: searchItems) {
  578. let ext = NSString(string: item as! String).pathExtension.lowercased()
  579. if NSArray(array: [_extention]).contains(ext) {
  580. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  581. items.add(fileName)
  582. }
  583. }
  584. }else {
  585. items.add(fName)
  586. }
  587. for item in NSArray(array: items) {
  588. let subFileName = item as! String
  589. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  590. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  591. if FileManager.default.fileExists(atPath: rComparePath) {
  592. if FileManager.default.fileExists(atPath: cComparePath) {
  593. try! FileManager.default.removeItem(atPath: cComparePath)
  594. }
  595. try! FileManager.default.createDirectory(atPath: NSString(string: cComparePath).deletingLastPathComponent,
  596. withIntermediateDirectories: true)
  597. try! FileManager.default.copyItem(atPath: rComparePath, toPath: cComparePath)
  598. }
  599. }
  600. }
  601. }
  602. func compareFiles() -> NSArray? {
  603. let items = NSMutableArray()
  604. let files = DataModel.shared.originFilesFor(_fileType, type: _type) as [String]
  605. for fileName in files {
  606. let sItems = compareFiles(fileName)
  607. if sItems != nil && sItems!.count != 0 {
  608. items.addObjects(from: sItems as! [Any])
  609. }
  610. }
  611. return items
  612. }
  613. func compareFiles(_ fileName: String) -> NSArray? {
  614. let files = NSMutableArray()
  615. let checkDirectory = self.checkFileDirectory()
  616. // let originDirectory = self.originFileDirectory()
  617. let resultDirectory = self.resultFileDirectory()
  618. let fName = NSString(string: fileName).deletingPathExtension
  619. // let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  620. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  621. // let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  622. var isDirectory = ObjCBool(false)
  623. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  624. // compare screenshoot between result file with check file
  625. let items = NSMutableArray()
  626. if (isDirectory.boolValue) {
  627. let searchItems = try? FileManager.default.contentsOfDirectory(atPath: resultPath)
  628. for item in NSArray(array: searchItems ?? []) {
  629. let ext = NSString(string: item as! String).pathExtension.lowercased()
  630. if (NSArray(array: [_extention]).contains(ext) &&
  631. !NSString(string: item as! String).contains("_cover.png")) {
  632. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  633. items.add(fileName)
  634. }
  635. }
  636. }else {
  637. items.add(fName)
  638. }
  639. let nitems = items.sortedArray { str1, str2 in
  640. let s1 = NSString(string: str1 as! String).deletingPathExtension
  641. let s2 = NSString(string: str2 as! String).deletingPathExtension
  642. if (NSString(string: s1).length != NSString(string: s2).length) {
  643. if (NSString(string: s1).length > NSString(string: s2).length) {
  644. return .orderedDescending
  645. }else {
  646. return .orderedAscending
  647. }
  648. }
  649. return NSString(string: s1).compare(s2)
  650. }
  651. for item in nitems {
  652. let subFileName = item as! String
  653. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  654. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  655. let fileInfo = NSMutableDictionary.fileInfoWith(fileName,
  656. refFilePath: subFileName+".jpg",
  657. resultPath: rComparePath,
  658. comparePath: cComparePath,
  659. objc: self)
  660. files.add(fileInfo)
  661. }
  662. }
  663. return files
  664. }
  665. /// Path
  666. func originFileDirectory() -> String {
  667. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kOriginPathComponent)")
  668. }
  669. func resultFileDirectory() -> String {
  670. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kResultPathComponent)")
  671. }
  672. func checkFileDirectory() -> String {
  673. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kCheckPathComponent)")
  674. }
  675. // check File Exist
  676. func hasOriginFile() -> Bool {
  677. if FileManager.default.fileExists(atPath: self.originFileDirectory()) {
  678. let files = try? FileManager.default.subpathsOfDirectory(atPath: self.originFileDirectory())
  679. return (files ?? []).count > 0
  680. }
  681. return false
  682. }
  683. func hasResultFile() -> Bool {
  684. if FileManager.default.fileExists(atPath: self.resultFileDirectory()) {
  685. let files = try? FileManager.default.subpathsOfDirectory(atPath: self.resultFileDirectory())
  686. return (files ?? []).count > 0
  687. }
  688. return false
  689. }
  690. ///
  691. func clearCacheFiles() {
  692. reportString = NSMutableAttributedString.init();
  693. let resultDirectory = self.resultFileDirectory()
  694. var isDirectory = ObjCBool(false)
  695. if FileManager.default.fileExists(atPath: resultDirectory, isDirectory: &isDirectory) && isDirectory.boolValue {
  696. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultDirectory)
  697. for item in NSArray(array: searchItems) {
  698. let path = NSString(string: resultDirectory).appendingPathComponent(item as! String)
  699. if FileManager.default.fileExists(atPath: path) {
  700. try! FileManager.default.removeItem(atPath: path)
  701. }
  702. }
  703. }
  704. }
  705. }
  706. extension AutoTest {
  707. func stringToImage(_ string:String) ->NSImage? {
  708. let length = Int(string.lengthOfBytes(using: .utf8)/2)
  709. let bytes = malloc(length)!
  710. for i in 0..<length {
  711. let index = i
  712. let subString = String(NSString(string: string).substring(with: NSMakeRange(Int(index * 2), 2)))
  713. bytes.storeBytes(of: UInt8(hexForString(subString)), as: UInt8.self)
  714. }
  715. let data = Data.init(bytes: bytes, count: length)
  716. let image = NSImage.init(data: data)
  717. return image
  718. }
  719. func hexForString(_ string:String) -> UInt8 {
  720. let chars = string.utf8CString
  721. if (string.lengthOfBytes(using: .utf8) >= 2) {
  722. return UInt8(intvalueForChar(chars[0]) * 16 + intvalueForChar(chars[1]))
  723. }
  724. return UInt8(0)
  725. }
  726. func intvalueForChar(_ char:CChar) -> UInt8 {
  727. let iValue = char
  728. // 0 ~ 9s
  729. if iValue >= 48 && iValue <= 57 {
  730. return UInt8(iValue - 48)
  731. }else if iValue >= 65 && iValue <= 70 {
  732. return UInt8(iValue - 65 + 10)
  733. }else if iValue >= 97 && iValue <= 102 {
  734. return UInt8(iValue - 97 + 10)
  735. }
  736. return UInt8(0)
  737. }
  738. }
  739. extension AutoTest {
  740. func isEqual(to object: AutoTest) -> Bool {
  741. return (NSString(string: self.className).isEqual(to: object.className) &&
  742. NSString(string: self.fileType()).isEqual(to: object.fileType()) &&
  743. NSString(string: self.type()).isEqual(to: object.type()) &&
  744. NSString(string: self.extention()).isEqual(to: object.extention()))
  745. }
  746. }