Skip to content

Commit 739ccda

Browse files
committed
Created warnings.py. Closes #40.
1 parent af8b3ad commit 739ccda

File tree

5 files changed

+123
-71
lines changed

5 files changed

+123
-71
lines changed

Python/convert.py

Lines changed: 14 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,18 @@
1-
import os, sys, time, shutil, math, json, pathlib, webbrowser
1+
import os, sys, time, shutil, math, pathlib, webbrowser
22
from pathlib import Path
3-
from jsoncomment import JsonComment
43
from playsound import playsound
54

65
from Python import shared_globals as cfg
76
from Python import regex_rules
87
from Python import zips as zips_py
98
from Python import update_progress
109
from Python import palette
10+
from Python import warnings
1111

1212

13-
warnings_file_name = "Warnings.json"
14-
warnings_path = os.path.join("ConversionRules", warnings_file_name)
15-
warnings_available = os.path.isfile(warnings_path)
13+
foo = "bar"
1614

1715
conversion_rules = {}
18-
warning_rules = {}
19-
warnings = []
2016

2117

2218
# TODO: Move to shared_globals.py
@@ -30,35 +26,8 @@ def resource_path(relative_path):
3026
output_folder_path = ".." if getattr(sys, 'frozen', False) else "Output"
3127

3228

33-
def load_conversion_and_warning_rules():
34-
json_parser = JsonComment(json)
35-
36-
json_files_found = 0
37-
try:
38-
for name in os.listdir("ConversionRules"):
39-
if name.endswith(".json") and name != warnings_file_name:
40-
json_files_found += 1
41-
with open(os.path.join("ConversionRules", name)) as f:
42-
conversion_rules.update(json_parser.load(f))
43-
if warnings_available:
44-
with open(warnings_path) as f:
45-
warning_rules.update(json_parser.load(f))
46-
except:
47-
check_github_button_clicked_and_exit(cfg.sg.Popup("The 'ConversionRules' folder wasn't found next to this executable. You can get the missing folder from the Legacy Mod Converter GitHub repo.", title="Missing ConversionRules folder", custom_text="Go to GitHub"))
48-
49-
if json_files_found == 0:
50-
check_github_button_clicked_and_exit(cfg.sg.Popup("The 'ConversionRules' folder didn't contain any JSON files. You can get the JSON files from the Legacy Mod Converter GitHub repo.", title="Missing JSON files", custom_text="Go to GitHub"))
51-
52-
53-
54-
def check_github_button_clicked_and_exit(clicked_github_button):
55-
if clicked_github_button:
56-
webbrowser.open("https://github.com/cortex-command-community/Cortex-Command-Legacy-Mod-Converter")
57-
sys.exit()
58-
59-
6029
def convert():
61-
global output_folder_path, warnings
30+
global output_folder_path
6231

6332
print("") # Only prints a newline.
6433

@@ -84,18 +53,19 @@ def convert():
8453
if cfg.sg.user_settings_get_entry("output_zips"):
8554
zips_py.create_zips(input_folder_path, output_folder_path)
8655

87-
if len(warnings) > 0:
88-
warnings_popup()
89-
90-
warnings = []
56+
elapsed = math.floor(time.time() - time_start)
9157

9258
update_progress.increment_progress() # TODO: This is a temporary solution for zipping not being accounted in the progress.
9359

94-
elapsed = math.floor(time.time() - time_start)
9560
if cfg.sg.user_settings_get_entry("play_finish_sound"):
9661
playsound(resource_path("Media/finish.wav"), block=False)
9762
print("Finished in {} {}".format(elapsed, pluralize("second", elapsed)))
9863

64+
if len(warnings.warning_results) > 0:
65+
warnings.warnings_popup()
66+
67+
warnings.warning_results = []
68+
9969

10070
def get_mod_subfolder(input_folder_path, input_subfolder_path):
10171
if input_folder_path.endswith(".rte"):
@@ -149,12 +119,12 @@ def create_converted_file(input_file_path, output_file_path, input_folder_path):
149119
for line in file_in:
150120
line_number += 1
151121

152-
if warnings_available:
153-
regex_rules.playsound_warning(line, file_path, line_number, warnings)
122+
if warnings.warnings_available:
123+
regex_rules.playsound_warning(line, file_path, line_number)
154124

155-
for old_str, new_str in warning_rules.items():
125+
for old_str, new_str in warnings.warning_rules.items():
156126
if old_str in line:
157-
warnings.append("'{}' line {}: {} -> {}".format(file_path, line_number, old_str, new_str))
127+
warnings.warning_results.append("'{}' line {}: {} -> {}".format(file_path, line_number, old_str, new_str))
158128

159129
all_lines_list.append(line)
160130

@@ -169,12 +139,5 @@ def create_converted_file(input_file_path, output_file_path, input_folder_path):
169139
# shutil.copyfile(input_file_path, output_file_path)
170140

171141

172-
def warnings_popup():
173-
if warnings_available:
174-
w = max(30, len(max(warnings, key=len)))
175-
h = min(50, len(warnings)) + 1 # + 1 necessary because popup_scrolled adds an extra line.
176-
cfg.sg.popup_scrolled("\n".join(warnings), title="Lines needing manual replacing", size=(w, h), button_color=cfg.sg.theme_button_color(), background_color=cfg.sg.theme_background_color())
177-
178-
179142
def pluralize(word, count):
180143
return word + "s" if count != 1 else word

Python/gui.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from Python import shared_globals as cfg
66
from Python import convert
7+
from Python import warnings
78

89

910
no_path_set_color = "#b35858"
@@ -82,7 +83,7 @@ def init_window():
8283
]
8384

8485
cfg.sg = sg
85-
convert.load_conversion_and_warning_rules()
86+
warnings.load_conversion_and_warning_rules()
8687

8788
window = sg.Window("Legacy Mod Converter", layout, icon=resource_path("Media/legacy-mod-converter.ico"), font=("Helvetica", 16))
8889
cfg.progress_bar = window["-PROGRESS BAR-"]

Python/palette.py

Lines changed: 57 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
import os
1+
import os, sys, io, cv2
22

33
from PIL import Image
4-
import cv2
54

65

76
palette = Image.open(os.path.join("Media", "palette.bmp")).getpalette()
@@ -14,22 +13,63 @@ def is_input_image(full_filename):
1413
def process_image(full_filename, input_image_path, output_image_path):
1514
global palette
1615

17-
# A bmp threw an "Unsupported BMP compression (1)" with Image.open(), so we open it in cv2 first.
18-
# cv2 solution: https://stackoverflow.com/a/52416250/13279557
19-
# cv2 to PIL: https://stackoverflow.com/a/43234001/13279557
20-
# old_img = Image.fromarray(cv2.imread(input_image_path)) # TODO: This may work just as well as the line below for all cases.
21-
old_img = Image.fromarray(cv2.cvtColor(cv2.imread(input_image_path), cv2.COLOR_BGR2RGB))
16+
old_img = get_old_img(input_image_path)
2217

23-
scale = 1
24-
old_img = old_img.resize((int(old_img.width * scale), int(old_img.height * scale)))
18+
# scale = 1
19+
# old_img = old_img.resize((int(old_img.width * scale), int(old_img.height * scale)))
2520

26-
# putpalette() always expects 256 * 3 ints.
27-
for k in range(256 - int(len(palette) / 3)):
28-
for j in range(3):
29-
palette.append(palette[j])
21+
# # putpalette() always expects 256 * 3 ints.
22+
# for k in range(256 - int(len(palette) / 3)):
23+
# for j in range(3):
24+
# palette.append(palette[j])
3025

31-
palette_img = Image.new('P', (1, 1))
32-
palette_img.putpalette(palette)
33-
new_img = old_img.convert(mode="RGB").quantize(palette=palette_img, dither=False)
26+
# palette_img = Image.new('P', (1, 1))
27+
# palette_img.putpalette(palette)
28+
# new_img = old_img.convert(mode="RGB").quantize(palette=palette_img, dither=False)
3429

35-
new_img.save(os.path.splitext(output_image_path)[0] + ".png")
30+
# new_img.save(os.path.splitext(output_image_path)[0] + ".png")
31+
32+
33+
def get_old_img(input_image_path):
34+
# This prevents cv2 from printing warnings to the terminal.
35+
# TODO: Fix the cv2 and PIL bmp reading issue instead of redirecting a warning away from the terminal.
36+
with suppress_stdout_stderr():
37+
# A bmp threw an "Unsupported BMP compression (1)" with Image.open(), so we open it in cv2 first.
38+
# cv2 solution: https://stackoverflow.com/a/52416250/13279557
39+
# cv2 to PIL: https://stackoverflow.com/a/43234001/13279557
40+
# old_img = Image.fromarray(cv2.imread(input_image_path)) # TODO: This may work just as well as the line below for all cases.
41+
old_img = Image.fromarray(cv2.cvtColor(cv2.imread(input_image_path), cv2.COLOR_BGR2RGB))
42+
43+
return old_img
44+
45+
46+
# This stackoverflow's question answers itself in the question with the solution to getting rid of "libpng warning: iCCP: known incorrect sRGB profile".
47+
# https://stackoverflow.com/q/11130156/13279557
48+
class suppress_stdout_stderr(object):
49+
'''
50+
A context manager for doing a "deep suppression" of stdout and stderr in
51+
Python, i.e. will suppress all print, even if the print originates in a
52+
compiled C/Fortran sub-function.
53+
This will not suppress raised exceptions, since exceptions are printed
54+
to stderr just before a script exits, and after the context manager has
55+
exited (at least, I think that is why it lets exceptions through).
56+
57+
'''
58+
def __init__(self):
59+
# Open a pair of null files
60+
self.null_fds = [os.open(os.devnull,os.O_RDWR) for x in range(2)]
61+
# Save the actual stdout (1) and stderr (2) file descriptors.
62+
self.save_fds = [os.dup(1), os.dup(2)]
63+
64+
def __enter__(self):
65+
# Assign the null pointers to stdout and stderr.
66+
os.dup2(self.null_fds[0],1)
67+
os.dup2(self.null_fds[1],2)
68+
69+
def __exit__(self, *_):
70+
# Re-assign the real stdout/stderr back to (1) and (2)
71+
os.dup2(self.save_fds[0],1)
72+
os.dup2(self.save_fds[1],2)
73+
# Close all file descriptors
74+
for fd in self.null_fds + self.save_fds:
75+
os.close(fd)

Python/regex_rules.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import re
22

3+
from Python import warnings
4+
35

46
def regex_replace(all_lines):
57
all_lines = simple_replace(all_lines, "Framerate = (.*)", "SpriteAnimMode = 7")
@@ -81,9 +83,9 @@ def regex_replace_bmps_and_wavs(all_lines):
8183
return all_lines
8284

8385

84-
def playsound_warning(line, file_path, line_number, warnings):
86+
def playsound_warning(line, file_path, line_number):
8587
pattern = "PlaySound(.*)"
8688
message = "No longer supported. Create a SoundContainer with CreateSoundContainer in the appropriate Create function."
8789
matches = re.findall(pattern, line)
8890
if len(matches) > 0 and matches[0].count(",") > 2:
89-
warnings.append("'{}' line {}: {} -> {}".format(file_path, line_number, pattern, message))
91+
warnings.warning_results.append("'{}' line {}: {} -> {}".format(file_path, line_number, pattern, message))

Python/warnings.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import os, sys, json
2+
from jsoncomment import JsonComment
3+
4+
from Python import shared_globals as cfg
5+
from Python import convert
6+
7+
8+
warnings_file_name = "Warnings.json"
9+
warnings_path = os.path.join("ConversionRules", warnings_file_name)
10+
warnings_available = os.path.isfile(warnings_path)
11+
12+
warning_rules = {}
13+
warning_results = []
14+
15+
16+
def load_conversion_and_warning_rules():
17+
json_parser = JsonComment(json)
18+
19+
json_files_found = 0
20+
try:
21+
for name in os.listdir("ConversionRules"):
22+
if name.endswith(".json") and name != warnings_file_name:
23+
json_files_found += 1
24+
with open(os.path.join("ConversionRules", name)) as f:
25+
convert.conversion_rules.update(json_parser.load(f))
26+
if warnings_available:
27+
with open(warnings_path) as f:
28+
warning_rules.update(json_parser.load(f))
29+
except:
30+
check_github_button_clicked_and_exit(cfg.sg.Popup("The 'ConversionRules' folder wasn't found next to this executable. You can get the missing folder from the Legacy Mod Converter GitHub repo.", title="Missing ConversionRules folder", custom_text="Go to GitHub"))
31+
32+
if json_files_found == 0:
33+
check_github_button_clicked_and_exit(cfg.sg.Popup("The 'ConversionRules' folder didn't contain any JSON files. You can get the JSON files from the Legacy Mod Converter GitHub repo.", title="Missing JSON files", custom_text="Go to GitHub"))
34+
35+
36+
def check_github_button_clicked_and_exit(clicked_github_button):
37+
if clicked_github_button:
38+
webbrowser.open("https://github.com/cortex-command-community/Cortex-Command-Legacy-Mod-Converter")
39+
sys.exit()
40+
41+
42+
def warnings_popup():
43+
if warnings_available:
44+
w = max(30, len(max(warning_results, key=len)))
45+
h = min(50, len(warning_results)) + 1 # + 1 necessary because popup_scrolled adds an extra line.
46+
cfg.sg.popup_scrolled("\n".join(warning_results), title="Lines needing manual replacing", size=(w, h), button_color=cfg.sg.theme_button_color(), background_color=cfg.sg.theme_background_color())

0 commit comments

Comments
 (0)