Skip to content

Commit

Permalink
Merge pull request #19 from JP-Carr/new_development
Browse files Browse the repository at this point in the history
New development
  • Loading branch information
why-keith committed Feb 1, 2021
2 parents 172bcce + 8beb82b commit 5ba14d0
Show file tree
Hide file tree
Showing 6 changed files with 328 additions and 180 deletions.
209 changes: 166 additions & 43 deletions DnD_Time_Manager.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,119 @@
import PySimpleGUI as sg
#import console_test as ct
from os import startfile, listdir, rename, mkdir, rmdir
from os.path import abspath, exists
from time import sleep
from error import error
import window_layouts as popup
from database_class import pickler, unpickle
from default_pref import new_pref
from database_class import pickler, unpickle, time_comparison
from database_class import db as db_class
from default_pref import default_pref
from tkinter import Tk
from tkinter.filedialog import askdirectory
from send2trash import send2trash
from urllib.request import urlopen


VERSION="v0.7.0"
VERSION="v0.8.0"


# Functions--------------------------------------------------------------------

def version_compare(ver):
"""
Checks with a given version against that of the program
Parameters
----------
ver : str
The version to be compared (form: "vX.Y.Z").
Returns
-------
up_to_date : bool
Whether the input version is up to date with the current version.
"""
int_ver=[int(ver[1:].split(".")[i]) for i in range(len(ver[1:].split(".")))]
new_int_ver=[int(VERSION[1:].split(".")[i]) for i in range(len(VERSION[1:].split(".")))]

up_to_date=True
for i in range(len(int_ver)):
if int_ver[i]<new_int_ver[i]:
up_to_date=False
break
elif int_ver[i]>new_int_ver[i]:
break

return up_to_date


def update_db(db):
"""
Updates a database created in an old version by porting its attributes
into a new replacement database if required
Parameters
----------
db : <class 'database_class.db'>
The old database to be updated.
Returns
-------
new_db : <class 'database_class.db'>
The new up-to-date database.
"""

try:
db_version=db.version
except AttributeError:
db_version="v0.0.0"
if version_compare(db_version)==False:
try:
print("Updating database from {} to {}".format(db.version, VERSION))
except:
print("Updating database to {}".format(VERSION))

attributes=[a for a in dir(db) if not a.startswith('__') and not callable(getattr(db, a))]
new_db=db_class()
for i in attributes:
try:
setattr(new_db,i, getattr(db,i))
except Exception as e:
error(e)

if "month_raw" not in attributes: #fixes introduction of month_raw
try:
new_db.month_raw=db.month[0]-1
new_db.change_day(1) #forces update
new_db.change_day(-1)
except Exception as e:
error(e)

new_db.version=VERSION
pickler(camp_dir+"/"+campaign+".pkl", new_db)
return new_db

else:
return db

def update_menu():
"""
Updates the elements of the menu bar
Returns
-------
menu_dict : dictionary
The updated menu.
"""

global recent_camps, menu_dict, window

recent_camps=pref["last campaign"][0:3]
menu_dict={
"File": ["New campaign...::new_campaign", "Open...::open_campaign", "Open recent", recent_camps, "Rename campaign::rename_campaign", "Delete campaign::delete_campaign", "Open save directory...::save_directory", "Preferences::preferences"],
"Tools":["Get raw time::raw_time_out"],
"Tools":["Get raw time::raw_time_out", "Set reminder::set_reminder", "View reminders::view_reminders"],
"Help": ["About::about", "ReadMe::readme", "Source Code::source_code"]
}
try:
Expand All @@ -34,14 +124,22 @@ def update_menu():
return menu_dict


# Preferences & campaign loading-----------------------------------------------

if "pref.pkl" in listdir():
pref=unpickle("pref.pkl")
pref=unpickle("pref.pkl")
for key in default_pref:
# print(key)
if key not in pref:
pref[key]=default_pref[key]

else:
pref=new_pref
pref=default_pref
pref["version"]=VERSION
pickler("pref.pkl", pref)
print("new pref file created")


if "campaigns" not in listdir():
mkdir("campaigns")

Expand All @@ -63,29 +161,26 @@ def update_menu():
pref["last campaign"].insert(0, campaign)
pref["last campaign"]=list(dict.fromkeys(pref["last campaign"]))
recent_camps=pref["last campaign"][0:3]
#window["menu_bar"].Update(menu_definition=[[i,menu_dict[i]] for i in menu_dict])
pickler("pref.pkl", pref)

print(pref["last campaign"])
print(campaign)
camp_dir="campaigns/"+campaign

db=unpickle(camp_dir+"/"+campaign+".pkl")

#pref["theme"]="Fighter"

db=unpickle(camp_dir+"/"+campaign+".pkl")
db=update_db(db)


################################################################################
#db.reminders=[]

# Window design----------------------------------------------------------------

sg.theme(pref["theme"])
QT_ENTER_KEY1 = 'special 16777220'
QT_ENTER_KEY2 = 'special 16777221'
focused_enter=None

#menu_dict={
# "File": ["New campaign...::new_campaign", "Open...::open_campaign", "Open recent", recent_camps, "Rename campaign::rename_campaign", "Delete campaign::delete_campaign", "Open save directory...::save_directory", "Preferences::preferences"],
# "Help": ["About::about", "ReadMe::readme", "Source Code::source_code"]
# }

menu_dict=update_menu()

main_layout=[
Expand All @@ -107,10 +202,11 @@ def update_menu():
]

updatable=["hour_display", "day_display", "tenday_display", "month_display", "year_display"]+["temp_display", "precip_display"]+["WS_display", "WD_display"]

print("///////////////////////////////////")
window=sg.Window("D&D Time Manager - "+campaign, main_layout, finalize=True, icon="dnd_logo.ico", return_keyboard_events=True)
print("///////////////////////////////////")


# Event loop-------------------------------------------------------------------

while True:
event, values = window.read()
Expand Down Expand Up @@ -138,38 +234,28 @@ def update_menu():
window["log_input"].Update("")

except PermissionError as e:
print("UNABLE TO LOG - PermissionError")
error("Unable to print to {}.txt - PermissionError".format(campaign))

except Exception as e:
print("UNABLE TO LOG")
error("Unable to print to {}.txt".format(campaign)+str(e))


elif event == "Open Log": #opens log file
try:
startfile(abspath("{}/{}.txt".format(camp_dir,campaign)))
# except FileNotFoundError as e:
#error("Unable to open {}.txt".format(campaign)+str(e))

except Exception as e:
print(e)
try:
log=open("{}/{}.txt".format(camp_dir,campaign), "a")
log.close()
startfile(abspath("{}/{}.txt".format(camp_dir,campaign)))

# except PermissionError as e2:
# print("UNABLE TO LOG FILE")
# error("Unable to open {}.txt".format(campaign)+str(e2))

except Exception as e2:
print(e2)
print("UNABLE TO CREATE LOG FILE")
error("Unable to create {}.txt".format(campaign)+str(e2))

elif event == "Submit" or focused_enter=="time": #Sumbits changes to database time and updates day conditions

# focused_enter=None

try:
h=int(window["hour_input"].Get())
Expand All @@ -183,18 +269,29 @@ def update_menu():
db.change_day(d)
pickler(camp_dir+"/"+campaign+".pkl", db)
update_values=["{}:00".format(db.hour), db.day, db.tenday, "{}. {}".format(db.month[0],db.month[1]), db.year]+[db.temperature, db.precipitation]+[db.windspeed, db.wind_dir]
# ct.show_all()
# print("\n")
for i in range(len(updatable)):
window[updatable[i]].Update(update_values[i])
window["hour_input"].Update("0")
window["day_input"].Update("0")

to_remove=[]
for i in db.reminders:

print(i[0])
if time_comparison(db.time_data(),i[1]):
to_remove.append(i)
popup.alert_box(text=i[0], window_name="Reminder", theme=pref["theme"])
for i in to_remove:
print("removing "+i[0])
db.reminders.remove(i)
print(db.reminders)


# Menu Events -----------------------------------------------------------------



# Menu Events -----------------------------------------------------------------------

# File --------------------------------------------------------------------
elif event.endswith("::new_campaign"):
old_campaign=campaign
campaign=popup.create_campaign(first=False, theme=pref["theme"])

if campaign!=None:
Expand All @@ -219,7 +316,8 @@ def update_menu():
update_menu()
pickler("pref.pkl", pref)


else:
campaign=old_campaign


elif event.endswith("::open_campaign"):
Expand All @@ -239,10 +337,11 @@ def update_menu():
campaign=file.split(".")[0]
camp_dir="campaigns/"+campaign
db=unpickle(path+"/"+file)
db=update_db(db)
update_values=["{}:00".format(db.hour), db.day, db.tenday, "{}. {}".format(db.month[0],db.month[1]), db.year]+[db.temperature, db.precipitation]+[db.windspeed, db.wind_dir]
break
except Exception as e:
print(e)
error(e)

else:
for i in range(len(updatable)):
Expand Down Expand Up @@ -320,7 +419,8 @@ def update_menu():
camp_dir="campaigns/"+campaign

window.set_title("D&D Time Manager - "+campaign)
db=unpickle(camp_dir+"/"+campaign+".pkl")
db=unpickle(camp_dir+"/"+campaign+".pkl")
db=update_db(db)
update_values=["{}:00".format(db.hour), db.day, db.tenday, "{}. {}".format(db.month[0],db.month[1]), db.year]+[db.temperature, db.precipitation]+[db.windspeed, db.wind_dir]

for i in range(len(updatable)):
Expand Down Expand Up @@ -350,13 +450,33 @@ def update_menu():

db.RAW=raw_weather
pickler(camp_dir+"/"+campaign+".pkl", db)

# Tools--------------------------------------------------------------------

elif event.endswith("::raw_time_out"):
print(db.day_raw,db.hour)
popup.alert_box(text=" {} hours, {} days\n(This value can be accessed from the error log)".format(db.hour,db.day_raw), window_name="Raw Time", sound=False, theme=pref["theme"])
error("Raw time request - {} hours, {} days".format(db.hour,db.day_raw), sound=False)

elif event.endswith("::set_reminder"):
time_data=(window["hour_display"].get(), window["day_display"].get(), window["month_display"].get(), window["year_display"].get() )
remind_data=popup.set_reminder(time_data, theme=pref["theme"])
if remind_data !=False:
db.reminders.append(remind_data)
pickler(camp_dir+"/"+campaign+".pkl", db)
print(db.reminders)

elif event.endswith("::view_reminders"):
time_data=(window["hour_display"].get(), window["day_display"].get(), window["month_display"].get(), window["year_display"].get() )
if popup.view_reminders(db, time_data, theme=pref["theme"])=="set_reminder":
remind_data=popup.set_reminder(time_data, theme=pref["theme"])
if remind_data !=False:
db.reminders.append(remind_data)
print(db.reminders)
pickler(camp_dir+"/"+campaign+".pkl", db)

# Help---------------------------------------------------------------------

elif event.endswith("::about"):
about_text="D&D Time Manager\n Version: {}".format(VERSION)
popup.alert_box(text=about_text, window_name="About", button_text="Close", sound=False, theme=pref["theme"])
Expand All @@ -381,19 +501,20 @@ def update_menu():
else:
startfile("https://github.com/JP-Carr/DnD_Time_Manager")


# Recent campaigns---------------------------------------------------------

elif event in recent_camps:
print(event)
if event!=campaign:
print(0)
# print(0)

try:
#camp_dir="campaigns/"+event
for file in listdir("campaigns/"+event):
if file.endswith(".pkl"):
camp_dir="campaigns/"+event
campaign=file.split(".")[0]
db=unpickle(camp_dir+"/"+file)
db=update_db(db)
update_values=["{}:00".format(db.hour), db.day, db.tenday, "{}. {}".format(db.month[0],db.month[1]), db.year]+[db.temperature, db.precipitation]+[db.windspeed, db.wind_dir]
break
except FileNotFoundError:
Expand All @@ -402,7 +523,7 @@ def update_menu():
popup.alert_box("Unable to load campaign \"{}\"".format(event), theme=pref["theme"])

except Exception as e:
print(e)
error(e)

else:
for i in range(len(updatable)):
Expand All @@ -420,6 +541,8 @@ def update_menu():

# else:
# print (event)

# End of loop------------------------------------------------------------------

pref["theme"]=pref["new_theme"]
pickler("pref.pkl", pref)
Expand Down
Loading

0 comments on commit 5ba14d0

Please sign in to comment.