test_tool.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import subprocess
  2. import json
  3. import tempfile
  4. import unittest
  5. from pathlib import Path
  6. from unittest.mock import patch
  7. import imageio_ffmpeg
  8. from PIL import Image, ImageOps
  9. from core import Cancelled, Options, FrameConfig, export_frames, geometry, inspect_media, sample_indices, preview_samples
  10. class ExtractionTests(unittest.TestCase):
  11. def setUp(self):
  12. self.temp = tempfile.TemporaryDirectory()
  13. self.root = Path(self.temp.name)
  14. self.gif = self.root / '中文 动画.gif'
  15. images = []
  16. for i in range(7):
  17. image = Image.new('RGBA', (40, 20), (0, 0, 0, 0))
  18. for x in range(10, 30):
  19. for y in range(5, 15):
  20. image.putpixel((x, y), (i * 35, 240 - i * 30, 50, 255))
  21. images.append(image)
  22. image.putpixel((10, 5), (255, 255, 255, 255))
  23. images[0].save(self.gif, save_all=True, append_images=images[1:],
  24. duration=100, disposal=2, loop=0)
  25. def tearDown(self):
  26. self.temp.cleanup()
  27. def test_sampling_and_gif_transparency(self):
  28. info = inspect_media(self.gif)
  29. self.assertEqual(info.count, 7)
  30. self.assertEqual(sample_indices(7, 4), [0, 2, 4, 6])
  31. self.assertEqual(sample_indices(7, 1), [0])
  32. for total in range(1, 40):
  33. for count in range(1, total + 1):
  34. indices = sample_indices(total, count)
  35. self.assertEqual(len(set(indices)), count)
  36. self.assertEqual(indices, sorted(indices))
  37. files = export_frames(self.gif, self.root / '输出', info, Options(count=4, prefix='角色'))
  38. self.assertEqual([f.name for f in files], [f'角色_{i}.png' for i in range(4)])
  39. for path, source_idx in zip(files, [0, 2, 4, 6]):
  40. with Image.open(path) as result:
  41. self.assertEqual(result.getpixel((20, 10)), (source_idx * 35, 240 - source_idx * 30, 50, 255))
  42. self.assertEqual(result.getpixel((0, 0))[3], 0)
  43. def test_crop_resize_and_no_overwrite(self):
  44. info = inspect_media(self.gif)
  45. options = Options(count=3, left=25, right=75, top=25, bottom=75,
  46. scale_axis='width', target=80)
  47. files = export_frames(self.gif, self.root / 'sized', info, options)
  48. with Image.open(files[0]) as result:
  49. self.assertEqual(result.size, (80, 40))
  50. self.assertEqual(result.getpixel((40, 20)), (0, 240, 50, 255))
  51. before = files[0].read_bytes()
  52. with self.assertRaises(ValueError):
  53. export_frames(self.gif, files[0].parent, info, options)
  54. self.assertEqual(before, files[0].read_bytes())
  55. self.assertEqual(geometry(info.size, Options(scale_axis='height', target=33))[1], (66, 33))
  56. def test_invalid_settings_and_cancel_rollback(self):
  57. for options in [Options(left=80, right=20), Options(top=float('nan')),
  58. Options(prefix='../bad'), Options(count=0)]:
  59. with self.assertRaises(ValueError):
  60. options.validate()
  61. info = inspect_media(self.gif)
  62. with self.assertRaises(ValueError):
  63. export_frames(self.gif, self.root / 'bad', info, Options(count=8))
  64. stopped = [False]
  65. with self.assertRaises(Cancelled):
  66. export_frames(self.gif, self.root / 'cancel', info, Options(count=7),
  67. lambda *_: stopped.__setitem__(0, True), lambda: stopped[0])
  68. self.assertEqual(list((self.root / 'cancel').iterdir()), [])
  69. def test_real_webm(self):
  70. video = self.root / '视频.webm'
  71. pixels = b''.join(Image.new('RGB', (40, 20), (i * 30, 100, 150)).tobytes() for i in range(6))
  72. subprocess.run([imageio_ffmpeg.get_ffmpeg_exe(), '-v', 'error', '-f', 'rawvideo',
  73. '-pix_fmt', 'rgb24', '-s', '40x20', '-r', '10', '-i', 'pipe:0',
  74. '-c:v', 'libvpx-vp9', '-lossless', '1', str(video)], input=pixels, check=True)
  75. info = inspect_media(video)
  76. self.assertEqual((info.count, info.size), (6, (40, 20)))
  77. files = export_frames(video, self.root / 'webm', info, Options(count=3, scale_axis='height', target=10))
  78. for path, source_idx in zip(files, [0, 3, 5]):
  79. with Image.open(path) as result:
  80. self.assertEqual(result.size, (20, 10))
  81. self.assertLessEqual(abs(result.getpixel((10, 5))[0] - source_idx * 30), 4)
  82. def test_frame_config_and_mirrored_images(self):
  83. info = inspect_media(self.gif)
  84. options = Options(count=3, prefix='角色', left=25, right=75, top=25, bottom=75,
  85. scale_axis='width', target=160)
  86. config = FrameConfig('RogueTest', -51, -85, source_direction=1)
  87. output = self.root / 'config'
  88. files = export_frames(self.gif, output, info, options, config=config)
  89. self.assertEqual(len(files), 6)
  90. data = json.loads((output / '角色.json').read_text(encoding='utf-8'))
  91. template = json.loads((Path(__file__).parent.parent / 'game/frame/character/Rogue59.json').read_text(encoding='utf-8'))
  92. self.assertEqual(list(data), list(template))
  93. self.assertEqual(data['HEAD_POS'], [-65, -5])
  94. self.assertEqual(data['NAME'], 'RogueTest')
  95. self.assertEqual(data['INTERVAL'], 200)
  96. for action in ('STAND_R', 'STAND_U', 'STAND_L', 'STAND_D', 'R', 'U', 'L', 'D'):
  97. item = data[action]
  98. direction = 0 if action.endswith(('R', 'D')) else 1
  99. self.assertEqual((item['Len'], item['Cx'], item['Cy']), (3, -51 if direction == 1 else -109, -85))
  100. self.assertEqual(item['Cloth']['CX'], [0] * 3)
  101. self.assertEqual(item['Cloth']['CY'], [0] * 3)
  102. self.assertEqual(item['Cloth']['IMG'], [f'角色_{direction}_{i}.png' for i in range(3)])
  103. self.assertTrue(all((output / name).is_file() for name in item['Cloth']['IMG']))
  104. from core import transform
  105. with Image.open(output / '角色_1_0.png') as left, Image.open(output / '角色_0_0.png') as right:
  106. expected = transform(info.first, options)
  107. self.assertEqual(left.tobytes(), expected.tobytes())
  108. self.assertEqual(right.tobytes(), ImageOps.mirror(expected).tobytes())
  109. def test_mirrored_offset_preserves_world_anchor(self):
  110. info = inspect_media(self.gif)
  111. for direction in (0, 1):
  112. for width, cx in ((160, -51), (161, 13), (160, -80)):
  113. with self.subTest(direction=direction, width=width, cx=cx):
  114. options = Options(count=1, scale_axis='width', target=width)
  115. folder = self.root / f'anchor_{direction}_{width}_{cx}'
  116. export_frames(self.gif, folder, info, options,
  117. config=FrameConfig('Anchor', cx, -85, direction))
  118. data = json.loads((folder / 'frame.json').read_text())
  119. original_key, mirror_key = ('R', 'L') if direction == 0 else ('L', 'R')
  120. original, mirrored = data[original_key], data[mirror_key]
  121. self.assertEqual(original['Cx'], cx)
  122. self.assertEqual(mirrored['Cx'], -cx - width)
  123. self.assertEqual(original['Cy'], mirrored['Cy'])
  124. scenes = []
  125. for item in (original, mirrored):
  126. scene = Image.new('RGBA', (600, 300))
  127. with Image.open(folder / item['Cloth']['IMG'][0]) as sprite:
  128. scene.alpha_composite(sprite, (300 + item['Cx'], 150 + item['Cy']))
  129. scenes.append(scene)
  130. # Check actual rendered pixels about the same world anchor,
  131. # including positive offsets and odd output widths.
  132. self.assertEqual(ImageOps.mirror(scenes[0]).tobytes(), scenes[1].tobytes())
  133. def test_config_collision_and_failure_rollback(self):
  134. info = inspect_media(self.gif)
  135. options = Options(count=2)
  136. config = FrameConfig('Test')
  137. output = self.root / 'collision'
  138. output.mkdir()
  139. (output / 'frame.json').write_text('existing', encoding='utf-8')
  140. with self.assertRaises(ValueError):
  141. export_frames(self.gif, output, info, options, config=config)
  142. self.assertEqual(list(output.iterdir()), [output / 'frame.json'])
  143. self.assertEqual((output / 'frame.json').read_text(), 'existing')
  144. with patch('core.json.dump', side_effect=OSError('disk full')):
  145. with self.assertRaises(OSError):
  146. export_frames(self.gif, self.root / 'rollback', info, options, config=config)
  147. self.assertEqual(list((self.root / 'rollback').iterdir()), [])
  148. def test_single_direction_config_without_mirror(self):
  149. info = inspect_media(self.gif)
  150. for direction in (0, 1):
  151. with self.subTest(source_direction=direction):
  152. folder = self.root / f'single_{direction}'
  153. options = Options(count=3, prefix='static', scale_axis='width', target=100)
  154. config = FrameConfig('StaticMonster', -31, -63, direction, mirror=False)
  155. files = export_frames(self.gif, folder, info, options, config=config)
  156. self.assertEqual([p.name for p in files], [f'static_0_{i}.png' for i in range(3)])
  157. self.assertEqual(len(list(folder.glob('*.png'))), 3)
  158. data = json.loads((folder / 'static.json').read_text())
  159. self.assertEqual(data['HEAD_POS'], [-35, 0])
  160. for key in ('STAND_R', 'STAND_U', 'STAND_L', 'STAND_D', 'R', 'U', 'L', 'D'):
  161. self.assertEqual((data[key]['Len'], data[key]['Cx'], data[key]['Cy']), (3, -31, -63))
  162. self.assertEqual(data[key]['Cloth']['IMG'], [p.name for p in files])
  163. self.assertEqual(data[key]['Cloth']['CX'], [0] * 3)
  164. self.assertEqual(data[key]['Cloth']['CY'], [0] * 3)
  165. from core import transform
  166. with Image.open(files[0]) as image:
  167. self.assertEqual(image.tobytes(), transform(info.first, options).tobytes())
  168. def test_gui_config_export_snapshot(self):
  169. import time
  170. from main import App
  171. app = App()
  172. try:
  173. app.update()
  174. app.events.put(('loaded', self.gif, inspect_media(self.gif)))
  175. app.poll()
  176. app.output.set(str(self.root / 'gui_config'))
  177. app.count.set('2')
  178. app.prefix.set('test')
  179. app.preview_offset = [-24, -72]
  180. app.config_toggle.invoke()
  181. with patch('main.messagebox.showinfo'), patch('main.messagebox.showerror') as error:
  182. app.start_button.invoke()
  183. app.preview_offset = [999, 999]
  184. deadline = time.monotonic() + 5
  185. while app.busy and time.monotonic() < deadline:
  186. app.update()
  187. time.sleep(0.01)
  188. self.assertFalse(app.busy)
  189. error.assert_not_called()
  190. data = json.loads((self.root / 'gui_config/test.json').read_text(encoding='utf-8'))
  191. self.assertEqual(data['NAME'], 'test')
  192. self.assertEqual((data['R']['Cx'], data['R']['Cy']), (-24, -72))
  193. self.assertEqual(data['HEAD_POS'], [-5, 0])
  194. self.assertEqual(len(list((self.root / 'gui_config').glob('*.png'))), 4)
  195. self.assertTrue(app.mirror_directions.get())
  196. app.mirror_toggle.invoke()
  197. self.assertEqual(str(app.direction_select.cget('state')), 'disabled')
  198. app.output.set(str(self.root / 'gui_single'))
  199. app.preview_offset = [-24, -72]
  200. with patch('main.messagebox.showinfo'), patch('main.messagebox.showerror') as error:
  201. app.start_button.invoke()
  202. deadline = time.monotonic() + 5
  203. while app.busy and time.monotonic() < deadline:
  204. app.update()
  205. time.sleep(0.01)
  206. self.assertFalse(app.busy)
  207. error.assert_not_called()
  208. single = json.loads((self.root / 'gui_single/test.json').read_text())
  209. self.assertEqual(single['R'], single['L'])
  210. self.assertEqual(single['L']['Cloth']['IMG'], ['test_0_0.png', 'test_0_1.png'])
  211. self.assertEqual(len(list((self.root / 'gui_single').glob('*.png'))), 2)
  212. app.mirror_toggle.invoke()
  213. self.assertEqual(str(app.direction_select.cget('state')), 'readonly')
  214. finally:
  215. app.destroy()
  216. def test_gui_preview_and_export_button(self):
  217. import time
  218. from main import App
  219. app = App()
  220. try:
  221. app.update()
  222. self.assertTrue(app.start_button.winfo_ismapped())
  223. self.assertLess(app.start_button.winfo_rooty() - app.winfo_rooty(), app.winfo_height())
  224. app.events.put(('loaded', self.gif, inspect_media(self.gif)))
  225. app.poll()
  226. app.output.set(str(self.root / 'gui'))
  227. app.prefix.set('界面')
  228. app.count.set('3')
  229. app.crop['左'].set('25')
  230. app.crop['右'].set('75')
  231. app.axis.set('指定宽度')
  232. app.target.set('60')
  233. app.update()
  234. self.assertIn('60 × 60', app.dimensions.get())
  235. app.grid_toggle.invoke()
  236. self.assertEqual((app.photo.width(), app.photo.height()), (60, 60))
  237. self.assertIn('1.5 × 1.5 格', app.dimensions.get())
  238. def check_grid_spacing():
  239. lines = [app.canvas.coords(item) for item in app.canvas.find_withtag('game_grid')]
  240. vertical = [line[0] for line in lines if line[0] == line[2]]
  241. self.assertGreater(len(vertical), 1)
  242. self.assertTrue(all(b - a == 40 for a, b in zip(vertical, vertical[1:])))
  243. check_grid_spacing()
  244. app.target.set('800')
  245. app.update()
  246. self.assertEqual((app.photo.width(), app.photo.height()), (800, 800))
  247. check_grid_spacing()
  248. self.assertLess(app.canvas.xview()[1], 1)
  249. app.scroll_preview('x', 'moveto', 1)
  250. check_grid_spacing()
  251. app.target.set('60')
  252. app.update()
  253. def drag_world(start, end):
  254. left, top = app.canvas.canvasx(0), app.canvas.canvasy(0)
  255. sx, sy = round(start[0] - left), round(start[1] - top)
  256. ex, ey = round(end[0] - left), round(end[1] - top)
  257. app.canvas.event_generate('<ButtonPress-1>', x=sx, y=sy)
  258. app.canvas.event_generate('<B1-Motion>', x=ex, y=ey)
  259. app.canvas.event_generate('<ButtonRelease-1>', x=ex, y=ey)
  260. app.center_view_button.invoke()
  261. reference = app.canvas.coords(app.canvas.find_withtag('reference_cell')[0])
  262. self.assertEqual(reference, [80, 80, 120, 120])
  263. bounds = app.canvas.coords(app.canvas.find_withtag('sprite_bounds')[0])
  264. self.assertEqual(bounds[:2], [100, 100])
  265. drag_world((110, 110), (73, 180))
  266. self.assertEqual(app.preview_offset, [-37, 70])
  267. self.assertIn('X: -37 px', app.offset_status.get())
  268. self.assertIn('Y: +70 px', app.offset_status.get())
  269. self.assertEqual(app.canvas.coords(app.canvas.find_withtag('reference_cell')[0]), reference)
  270. self.assertEqual(app.canvas.coords(app.canvas.find_withtag('sprite_bounds')[0])[:2], [63, 170])
  271. # A redraw or a settings change must not move the reference or reset placement.
  272. app.draw_current()
  273. app.target.set('80')
  274. app.update()
  275. self.assertEqual(app.preview_offset, [-37, 70])
  276. app.reset_position_button.invoke()
  277. self.assertEqual(app.preview_offset, [0, 0])
  278. app.target.set('60')
  279. app.update()
  280. # Leave a nonzero placement active while exporting.
  281. drag_world((110, 110), (140, 150))
  282. self.assertEqual(app.preview_offset, [30, 40])
  283. with patch('main.messagebox.showinfo'), patch('main.messagebox.showerror') as error:
  284. app.start_button.invoke()
  285. deadline = time.monotonic() + 15
  286. while app.busy and time.monotonic() < deadline:
  287. app.update()
  288. time.sleep(0.02)
  289. self.assertFalse(app.busy)
  290. error.assert_not_called()
  291. self.assertEqual(len(list((self.root / 'gui').glob('界面_*.png'))), 3)
  292. with Image.open(self.root / 'gui' / '界面_0.png') as result:
  293. self.assertEqual(result.size, (60, 60))
  294. self.assertEqual(result.getpixel((0, 0))[3], 0)
  295. # Grid enabled in the UI must not change any exported pixel.
  296. from core import transform
  297. expected = transform(app.info.first, app.options())
  298. self.assertEqual(result.tobytes(), expected.tobytes())
  299. finally:
  300. app.destroy()
  301. def test_center_and_pan_view_without_moving_sprite(self):
  302. from main import App
  303. app = App()
  304. try:
  305. app.update()
  306. app.events.put(('loaded', self.gif, inspect_media(self.gif)))
  307. app.poll()
  308. app.axis.set('指定宽度')
  309. app.target.set('144')
  310. app.preview_offset = [-61, -117]
  311. app.grid_toggle.invoke()
  312. app.update()
  313. width, height = app.canvas.winfo_width(), app.canvas.winfo_height()
  314. left, top = app.canvas.canvasx(0), app.canvas.canvasy(0)
  315. # Center both the sprite and reference cell, including negative placement.
  316. self.assertAlmostEqual(left + width / 2, (39 + 183) / 2, delta=1)
  317. self.assertAlmostEqual(top + height / 2, (-17 + 120) / 2, delta=1)
  318. before_sprite = app.canvas.coords(app.canvas.find_withtag('sprite_bounds')[0])
  319. before_offset = app.preview_offset.copy()
  320. before_label = app.offset_status.get()
  321. for button, dx, dy in [(3, 140, 70), (2, -90, -45)]:
  322. old_left, old_top = app.canvas.canvasx(0), app.canvas.canvasy(0)
  323. app.canvas.event_generate(f'<ButtonPress-{button}>', x=150, y=100)
  324. app.canvas.event_generate(f'<B{button}-Motion>', x=150 + dx, y=100 + dy)
  325. app.canvas.event_generate(f'<ButtonRelease-{button}>', x=150 + dx, y=100 + dy)
  326. self.assertAlmostEqual(app.canvas.canvasx(0), old_left - dx, delta=1)
  327. self.assertAlmostEqual(app.canvas.canvasy(0), old_top - dy, delta=1)
  328. self.assertEqual(app.preview_offset, before_offset)
  329. self.assertEqual(app.offset_status.get(), before_label)
  330. self.assertEqual(app.canvas.coords(app.canvas.find_withtag('sprite_bounds')[0]), before_sprite)
  331. held_view = (app.canvas.canvasx(0), app.canvas.canvasy(0))
  332. for _ in range(4):
  333. app.draw_current()
  334. self.assertEqual(held_view, (app.canvas.canvasx(0), app.canvas.canvasy(0)))
  335. app.scroll_preview('x', 'scroll', -1, 'pages')
  336. self.assertLess(app.canvas.canvasx(0), held_view[0])
  337. self.assertEqual(app.preview_offset, before_offset)
  338. app.center_view_button.invoke()
  339. self.assertAlmostEqual(app.canvas.canvasx(0), left, delta=1)
  340. self.assertAlmostEqual(app.canvas.canvasy(0), top, delta=1)
  341. self.assertEqual(app.preview_offset, before_offset)
  342. finally:
  343. app.destroy()
  344. def test_scrollable_settings_and_animation(self):
  345. import time
  346. from main import App
  347. app = App()
  348. def pump_until(predicate, timeout=5):
  349. deadline = time.monotonic() + timeout
  350. while not predicate() and time.monotonic() < deadline:
  351. app.update()
  352. time.sleep(0.005)
  353. self.assertTrue(predicate())
  354. try:
  355. # Reproduce a shorter window with larger system text.
  356. app.tk.call('tk', 'scaling', 1.75)
  357. app.geometry('1000x600')
  358. app.update()
  359. app.settings_canvas.yview_moveto(1)
  360. app.update()
  361. canvas = app.settings_canvas
  362. entry = app.target_entry
  363. # Scaling is no longer the final section; scroll it into view explicitly.
  364. region = [float(value) for value in canvas.cget('scrollregion').split()]
  365. canvas.yview_moveto((canvas.canvasy(entry.winfo_rooty() - canvas.winfo_rooty()) - 20) / region[3])
  366. app.update()
  367. self.assertGreaterEqual(entry.winfo_rooty(), canvas.winfo_rooty())
  368. self.assertLessEqual(entry.winfo_rooty() + entry.winfo_height(), canvas.winfo_rooty() + canvas.winfo_height())
  369. self.assertLessEqual(entry.winfo_rootx() + entry.winfo_width(), canvas.winfo_rootx() + canvas.winfo_width())
  370. self.assertTrue(app.start_button.winfo_ismapped())
  371. app.events.put(('loaded', self.gif, inspect_media(self.gif)))
  372. app.poll()
  373. app.count.set('3')
  374. pump_until(lambda: len(app.samples) == 3)
  375. self.assertEqual(app.sample_sources, [0, 3, 6])
  376. # Confirm scheduled playback advances and wraps at the requested cadence.
  377. positions = []
  378. last = app.sample_position
  379. started = time.monotonic()
  380. while len(positions) < 4 and time.monotonic() - started < 2:
  381. app.update()
  382. if last != app.sample_position:
  383. positions.append((app.sample_position, time.monotonic()))
  384. last = app.sample_position
  385. time.sleep(0.003)
  386. self.assertEqual([p[0] for p in positions], [1, 2, 0, 1])
  387. for before, after in zip(positions, positions[1:]):
  388. self.assertGreaterEqual(after[1] - before[1], 0.09)
  389. self.assertLess(after[1] - before[1], 0.25)
  390. app.play_button.invoke()
  391. paused = app.sample_position
  392. until = time.monotonic() + 0.25
  393. while time.monotonic() < until:
  394. app.update()
  395. time.sleep(0.005)
  396. self.assertEqual(app.sample_position, paused)
  397. app.count.set('2')
  398. app.crop['左'].set('25')
  399. app.crop['右'].set('75')
  400. app.axis.set('指定宽度')
  401. app.target.set('60')
  402. pump_until(lambda: len(app.samples) == 2)
  403. self.assertEqual(app.sample_sources, [0, 6])
  404. self.assertEqual(app.samples[0].size, (60, 60))
  405. self.assertFalse(app.want_play)
  406. app.play_button.invoke()
  407. pump_until(lambda: app.sample_position == 1)
  408. finally:
  409. app.destroy()
  410. if __name__ == '__main__':
  411. unittest.main()