Skip to content

Commit

Permalink
Merge pull request #60 from WhenLifeHandsYouLemons/v1.9.1
Browse files Browse the repository at this point in the history
v1.9.1
  • Loading branch information
WhenLifeHandsYouLemons authored Apr 4, 2024
2 parents b3dc7b2 + b9939f3 commit 932d229
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 62 deletions.
46 changes: 31 additions & 15 deletions Encryptext.pyw
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Imports
"""
import sys
from os.path import abspath, join, expanduser
#! from os import getenv # Not useful right now, but could be useful if translations are available
# from os import getenv #! DOESN'T SEEM TO WORK IN EXE MODE
import json
from random import choice, randint
from string import ascii_letters, digits
Expand Down Expand Up @@ -78,7 +78,7 @@ try:
settings[key] = True
except FileNotFoundError:
settings = {
"version": "'Encryptext Offline Mode'",
"version": "'Encryptext Travel Mode'",
"recentFilePaths": [],
"maxRecentFiles": 0,
"otherSettings": {
Expand All @@ -95,7 +95,7 @@ except FileNotFoundError:
}
}

version = settings["version"]
version = f"{'.'.join(settings['version'].split('.')[0:-1])} (build {settings['version'].split('.')[-1]})"
font_scale_factor = settings["otherSettings"]["fontScaleFactor"]

"""
Expand All @@ -111,7 +111,6 @@ class TextLineNumbers(tk.Canvas):
self.textwidget = text_widget

def redraw(self, *args):
'''redraw line numbers'''
self.delete("all")

i = self.textwidget.index("@0,0")
Expand Down Expand Up @@ -157,7 +156,6 @@ class CustomText(tk.Text):

# https://www.reddit.com/r/learnpython/comments/6dndqz/comment/di42keo/
class WrappedLabel(ttk.Label):
"""a type of Label that automatically adjusts the wrap to the size"""
def __init__(self, master=None, **kwargs):
ttk.Label.__init__(self, master, **kwargs)
self.bind("<Configure>", lambda e: self.config(wraplength=self.winfo_width()))
Expand Down Expand Up @@ -213,7 +211,10 @@ class PreferenceWindow(tk.Toplevel):
# Language picker
self.selected_language = tk.StringVar(value=settings["otherSettings"]["language"])
self.language_label = WrappedLabel(self.pref_window, text="Display language: ", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
#! getenv("LANG").split(".")[0] # Can be useful to get the user's default language
# Get the user's default language and also display that in the list
# It doesn't change anything right now, but maybe it will in the future.
#! DOESN'T SEEM TO WORK IN EXE MODE
# getenv("LANG").split(".")[0]
lang_options = ["en_US"]
self.language_val = ttk.Combobox(self.language_label, textvariable=self.selected_language, values=lang_options, state="readonly", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))

Expand Down Expand Up @@ -457,10 +458,14 @@ def quitApp(Event=None):
with open(settings_path, "w") as file:
settings = str(settings).replace("'", '"').replace("False", "false").replace("True", "true")
file.write(str(settings))
except FileNotFoundError: pass
except FileNotFoundError or NameError as e:
if debug:
messagebox.askokcancel("ERROR", f"Error: {e}")
except Exception as e:
messagebox.askokcancel("ERROR", f"Error: {e}")

try:
md_preview_window.destroy()
preview_window.destroy()
pref_window.closeWindow()
finally:
root.destroy()
Expand All @@ -483,10 +488,14 @@ def quitApp(Event=None):
with open(settings_path, "w") as file:
settings = str(settings).replace("'", '"').replace("False", "false").replace("True", "true")
file.write(str(settings))
except FileNotFoundError: pass
except FileNotFoundError or NameError as e:
if debug:
messagebox.showerror("ERROR", f"Error: {e}")
except Exception:
messagebox.showerror("Error", "Unknown error. If this problem persists, please contact the developer at 'https://github.com/WhenLifeHandsYouLemons/Encryptext'.")

try:
md_preview_window.destroy()
preview_window.destroy()
pref_window.closeWindow()
finally:
root.destroy()
Expand Down Expand Up @@ -673,9 +682,9 @@ def openFile(Event=None, current=False, file_path=None):
recent_files.pop()
createMenuBar()
if file_extensions[current_tab] == "md":
global md_preview_window
global preview_window
try:
md_preview_window.deiconify()
preview_window.deiconify()
updatePreview()
except:
preview_window.__init__()
Expand Down Expand Up @@ -729,14 +738,16 @@ def newFile(Event=None):

updatePreview()

def saveFile(Event=None):
def saveFile(Event=None, auto_save=False):
current_tab = getCurrentTab()
if current_tab == -1:
return None

# If it's a new file
if file_save_locations[current_tab] == "":
saveFileAs()
# If it's being saved manually, then try save as
if not auto_save:
saveFileAs()
else:
# Get the text from the current textbox
text = textboxes[current_tab].get("1.0", tk.END)
Expand Down Expand Up @@ -1239,7 +1250,7 @@ def addNewTab(Event=None):
textboxes[-1].bindtags((bindtags[2], bindtags[0], bindtags[1], bindtags[3]))

# Track document changes and update markdown preview
textboxes[-1].bind('<Key>', trackChanges)
textboxes[-1].bind('<<Change>>', trackChanges)
if settings["otherSettings"]["showLineNumbers"] == True and settings["otherSettings"]["highlightActiveLine"] == True:
textboxes[-1].bind("<<Change>>", updateHighlightAndNumbers)
textboxes[-1].bind("<Configure>", updateHighlightAndNumbers)
Expand Down Expand Up @@ -1286,6 +1297,9 @@ def closeCurrentTab(Event=None):
file_format_tags.pop(current_tab)
file_format_tag_nums.pop(current_tab)
saved.pop(current_tab)
frames.pop(current_tab)
if settings["otherSettings"]["showLineNumbers"] == True:
line_number_areas.pop(current_tab)

updatePreview()

Expand Down Expand Up @@ -1325,6 +1339,8 @@ def captureSpecialKeys(Event=None):
cur_key = Event.keysym
mod_key = Event.state

# print(Event, cur_key, mod_key)

# Run function based on what key was pressed
if cur_key == "s":
saveFile()
Expand Down
1 change: 1 addition & 0 deletions Original Files/build_number.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
20
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
3 changes: 1 addition & 2 deletions encryptext_installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from shutil import rmtree
import sys
from subprocess import run, PIPE
from time import sleep
import json
from cryptography.fernet import Fernet as F
from random import choice, randint
Expand All @@ -13,7 +12,7 @@
# https://github.com/rsalmei/alive-progress
from alive_progress import alive_bar, styles

version = "1.9.0"
version = "INSERT VERSION NUMBER HERE"

print("\nStarting installer...")
print("Please wait...")
Expand Down
131 changes: 86 additions & 45 deletions installer_creator.py
Original file line number Diff line number Diff line change
@@ -1,69 +1,110 @@
#!/usr/bin/python'

from os import rename, path, remove
from shutil import rmtree
from shutil import rmtree, copy
import hashlib
import PyInstaller.__main__

version = "1.9.0"
version = "1.9.1"
testing = False

def update_build_number():
with open("Original Files/build_number.txt", "r") as file:
build_number = int(file.read().strip())
build_number += 1
with open("Original Files/build_number.txt", "w") as file:
file.write(str(build_number))
return build_number

build_number = update_build_number()
version = f"{version}.{build_number}"

# Compute hash of the input string
def computeHash(input_string):
def computeHash(input_string: str) -> str:
hash_object = hashlib.sha256()
hash_object.update(input_string.encode('utf-8'))

return hash_object.hexdigest()

def modifyInstallerFile(add: bool) -> None:
if add:
# Add the computed hash and version number
with open("encryptext_installer.py", "r+") as file:
installer_file = file.read()
installer_parts = installer_file.split("INSERT COMPUTED HASH HERE")
installer_file = hash_str.join(installer_parts)
installer_parts = installer_file.split("INSERT VERSION NUMBER HERE")
installer_file = version.join(installer_parts)

file.seek(0)
file.write(installer_file)
file.truncate()
else:
# Remove the computed hash and version number
with open("encryptext_installer.py", "r+") as file:
installer_file = file.read()
installer_parts = installer_file.split(hash_str)
installer_file = "INSERT COMPUTED HASH HERE".join(installer_parts)
installer_parts = installer_file.split(version)
installer_file = "INSERT VERSION NUMBER HERE".join(installer_parts)

file.seek(0)
file.write(installer_file)
file.truncate()

# Open the key.txt file and read in the key
with open("Original Files/key.txt", "r") as file:
key = file.read().strip()
# Compute the hash of the key
hash_str = computeHash(key)

# Add the computed hash
with open("encryptext_installer.py", "r+") as file:
installer_file = file.read()
installer_parts = installer_file.split("INSERT COMPUTED HASH HERE")
installer_file = hash_str.join(installer_parts)
file.seek(0)
file.write(installer_file)
file.truncate()

# Creates an executable file
PyInstaller.__main__.run([
'encryptext_installer.py',
'--onefile',
'--clean',
'--log-level',
'ERROR',
'--icon',
'app_icon.ico',
'--add-data',
'app_icon.ico;.',
'--add-data',
'Encryptext.pyw;.',
"--collect-all",
"tkinterweb",
"--collect-all",
"alive_progress",
"--collect-all",
"grapheme"
])

# Remove the computed hash
with open("encryptext_installer.py", "r+") as file:
installer_file = file.read()
installer_parts = installer_file.split(hash_str)
installer_file = "INSERT COMPUTED HASH HERE".join(installer_parts)
file.seek(0)
file.write(installer_file)
file.truncate()
# Add hash and version
modifyInstallerFile(True)

# Move the exe out of the dist folder
try:
remove(f"encryptext_installer_v{version}_64bit.exe")
except FileNotFoundError: pass
rename(path.join("dist", "encryptext_installer.exe"), f"encryptext_installer_v{version}_64bit.exe")
# Creates an executable file
PyInstaller.__main__.run([
'encryptext_installer.py',
'--onefile',
'--clean',
'--log-level',
'ERROR',
'--icon',
'app_icon.ico',
'--add-data',
'app_icon.ico;.',
'--add-data',
'Encryptext.pyw;.',
"--collect-all",
"tkinterweb",
"--collect-all",
"alive_progress",
"--collect-all",
"grapheme"
])
except Exception as e:
print("Stopped for:", e)

# Remove hash and version
modifyInstallerFile(False)

# Remove pyinstaller folders and files
rmtree("dist")
rmtree("build")
remove("encryptext_installer.spec")

exit()

# Remove hash and version
modifyInstallerFile(False)

# Move the exe out of the dist folder
if testing:
rename(path.join("dist", "encryptext_installer.exe"), f"builds/testing/encryptext_installer_v{version}_64bit.exe")
else:
copy(path.join("dist", "encryptext_installer.exe"), f"builds/testing/encryptext_installer_v{version}_64bit_release.exe")
version = '.'.join(version.split('.')[0:-1])
rename(path.join("dist", "encryptext_installer.exe"), f"builds/release/encryptext_installer_v{version}_64bit.exe")

# Remove pyinstaller folders and files
rmtree("dist")
Expand Down

0 comments on commit 932d229

Please sign in to comment.