Converting Python scripts to classes

This commit is contained in:
2023-12-25 20:22:31 +01:00
parent 7c5e86e8dc
commit 1a8a986674
12 changed files with 263 additions and 1674 deletions

View File

@@ -15,9 +15,9 @@ const Lang = imports.lang;
const { find_program_in_path } = imports.gi.GLib;
const Gio = imports.gi.Gio;
// let suntimes = require('./scripts/suntimes')
// let location = require('./scripts/location')
// let communication = require('./scripts/communication')
let suntimes = require('./scripts/suntimes')
let location = require('./scripts/location')
let communication = require('./scripts/communication')
/******************** Constants ********************/
@@ -37,7 +37,7 @@ let extension;
let lastLocationUpdate = -1
// The last calculated suntime of the day
let lastDayTime = suntimes.DAYPERIOD.NONE
//let lastDayTime = suntimes.DAYPERIOD.NONE
// Loop state
let looping = true
@@ -100,7 +100,6 @@ CinnamonDynamicWallpaperExtension.prototype = {
// Check for the first startup
if (this.settings.getValue("first_start")) {
this.writeToLogs("First time start")
// Welcome notification
communication.showNotification("Welcome to Cinnamon Dynamic Wallpaper",
@@ -194,7 +193,7 @@ CinnamonDynamicWallpaperExtension.prototype = {
/**
* Estimate the right image based on time period of the day
*/
setImageToTime: function() {
/*setImageToTime: function() {
let times = suntimes.calcTimePeriod(this.latitude, this.longitude)
let now = new Date()
@@ -244,7 +243,7 @@ CinnamonDynamicWallpaperExtension.prototype = {
"\nSunset:\t\t\t\t" + convertToTimeString(timesArray[6][0]) + " - " + convertToTimeString(timesArray[6][1]) +
"\nNight Twilight:\t\t" + convertToTimeString(timesArray[7][0]) + " - " + convertToTimeString(timesArray[7][1]) +
"\nNight:\t\t\t\t" + convertToTimeString(timesArray[8][0]) + " - " + convertToTimeString(timesArray[8][1])
},
},*/
/**
* Get the location of the user

View File

@@ -1,6 +0,0 @@
from enum import Enum
class Source(Enum):
SELECTED = 0 # Load previous selected images
EXTRACT = 1 # Use a custom image set from a heic file
SET = 2 # Use an included image set

View File

@@ -1,6 +0,0 @@
import os
import windowHandler
if __name__ == "__main__":
wh = windowHandler.WindowHandler(os.path.expanduser("~") + "/.config/cinnamon/spices/cinnamon-dynamic-wallpaper@TobiZog/cinnamon-dynamic-wallpaper@TobiZog.json")
wh.showMainWindow()

View File

@@ -1,398 +0,0 @@
import gi, os, glob, json, shutil, threading, subprocess
from data.enum import Source
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GdkPixbuf
CONFIGURATOR_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR = os.path.dirname(CONFIGURATOR_DIR) + "/"
UI_PATH = CONFIGURATOR_DIR + "/" + "image-configurator.glade"
IMAGE_DIR = PROJECT_DIR + "images/"
IMAGE_EXTRACT_DIR = IMAGE_DIR + "extracted/"
IMAGE_SETS_DIR = IMAGE_DIR + "included_image_sets/"
IMAGE_SELECTED_DIR = IMAGE_DIR + "selected/"
IMAGE_DEFAULT_DIR = IMAGE_DIR + "default/"
class WindowHandler:
def __init__(self, pref_path: str) -> None:
########### Class variables ###########
self.pref_path = pref_path
self.time_values = [
"etr_morning_twilight_times",
"etr_sunrise_times",
"etr_morning_times",
"etr_noon_times",
"etr_afternoon_times",
"etr_evening_times",
"etr_sunset_times",
"etr_night_twilight_times",
"etr_night_times"
]
self.img_values = [
"etr_img_morning_twilight",
"etr_img_sunrise",
"etr_img_morning",
"etr_img_noon",
"etr_img_afternoon",
"etr_img_evening",
"etr_img_sunset",
"etr_img_night_twilight",
"etr_img_night"
]
self.img_sets = [
"aurora",
"beach",
"bitday",
"cliffs",
"gradient",
"lakeside",
"mountains",
"sahara"
]
########### Create the folder ###########
try:
os.mkdir(IMAGE_EXTRACT_DIR)
except:
pass
try:
os.mkdir(IMAGE_SELECTED_DIR)
except:
pass
########### GTK stuff ###########
self.builder = Gtk.Builder()
self.builder.add_from_file(UI_PATH)
self.builder.connect_signals(self)
########### Glade Ressources ###########
self.rb_included_image_set = self.builder.get_object("rb_included_image_set")
self.rb_external_image_set = self.builder.get_object("rb_external_image_set")
self.lb_image_set = self.builder.get_object("lb_image_set")
self.cb_image_set = self.builder.get_object("cb_image_set")
self.lb_heic_file = self.builder.get_object("lb_heic_file")
self.fc_heic_file = self.builder.get_object("fc_heic_file")
self.lb_times = [
self.builder.get_object("lb_times_1"),
self.builder.get_object("lb_times_2"),
self.builder.get_object("lb_times_3"),
self.builder.get_object("lb_times_4"),
self.builder.get_object("lb_times_5"),
self.builder.get_object("lb_times_6"),
self.builder.get_object("lb_times_7"),
self.builder.get_object("lb_times_8"),
self.builder.get_object("lb_times_9")
]
self.img_previews = [
self.builder.get_object("img_preview_1"),
self.builder.get_object("img_preview_2"),
self.builder.get_object("img_preview_3"),
self.builder.get_object("img_preview_4"),
self.builder.get_object("img_preview_5"),
self.builder.get_object("img_preview_6"),
self.builder.get_object("img_preview_7"),
self.builder.get_object("img_preview_8"),
self.builder.get_object("img_preview_9")
]
self.cb_previews = [
self.builder.get_object("cb_preview_1"),
self.builder.get_object("cb_preview_2"),
self.builder.get_object("cb_preview_3"),
self.builder.get_object("cb_preview_4"),
self.builder.get_object("cb_preview_5"),
self.builder.get_object("cb_preview_6"),
self.builder.get_object("cb_preview_7"),
self.builder.get_object("cb_preview_8"),
self.builder.get_object("cb_preview_9")
]
# The GtkStack
self.stack_main = self.builder.get_object("stack_main")
self.stack_main.add_named(self.builder.get_object("page_config"), "config")
self.stack_main.add_named(self.builder.get_object("page_load"), "load")
self.stack_main.set_visible_child_name("config")
########### Load predefinitions and settings ###########
for set in self.img_sets:
self.cb_image_set.append_text(set)
self.image_source = Source.SELECTED
# Load preferences
self.loadFromSettings()
def showMainWindow(self):
""" Opens the main window, starts the Gtk main routine
"""
window = self.builder.get_object("main_window")
window.show_all()
self.imageSetVisibility(self.image_source)
self.rb_external_image_set.set_active(self.image_source == Source.EXTRACT)
Gtk.main()
def loadFromSettings(self):
""" Load preferences from the Cinnamon preference file
"""
#try:
# Load the settings
with open(self.pref_path, "r") as pref_file:
pref_data = json.load(pref_file)
# Get all images in the "selected" folder
choosable_images = os.listdir(IMAGE_SELECTED_DIR)
choosable_images.sort()
# Add the founded image names to the ComboBoxes
if pref_data["etr_choosen_image_set"]["value"] == "custom":
for combobox in self.cb_previews:
for option in choosable_images:
combobox.append_text(option)
else:
for i, set in enumerate(self.img_sets):
if set == pref_data["etr_choosen_image_set"]["value"]:
self.cb_image_set.set_active(i)
for i, val in enumerate(self.img_values):
# Bugfix: Load the images only, if there is choosen one
if pref_data[val]['value'] != None:
# Set the preview image
self.changePreviewImage(i, IMAGE_SELECTED_DIR + pref_data[val]['value'])
# Set the ComboBox selection
if pref_data["etr_choosen_image_set"]["value"] == "custom":
self.image_source = Source.EXTRACT
for j, set in enumerate(choosable_images):
if set == pref_data[val]["value"]:
self.cb_previews[i].set_active(j)
else:
self.image_source = Source.SET
# Print the times of the day
for i, val in enumerate(self.time_values):
self.lb_times[i].set_text(pref_data[val]['value'])
def writeToSettings(self):
""" Save preferences to the Cinnamon preference file
"""
# Load the settings
with open(self.pref_path, "r") as pref_file:
pref_data = json.load(pref_file)
# Update the settings
if self.image_source == Source.SET:
pref_data["etr_choosen_image_set"]["value"] = self.cb_image_set.get_active_text()
for i, val in enumerate(self.img_values):
pref_data[val]['value'] = str(i + 1) + ".jpg"
else:
pref_data["etr_choosen_image_set"]["value"] = "custom"
for i, val in enumerate(self.img_values):
image_name = self.cb_previews[i].get_active_text()
pref_data[val]['value'] = image_name
# Write the settings
with open(self.pref_path, "w") as pref_file:
json.dump(pref_data, pref_file, separators=(',', ':'), indent=4)
def changePreviewImage(self, imageId: int, imageURI: str):
""" Exchanges the image in the preview
Args:
imageId (int): The number of the preview (0-8)
imageURI (str): URI to the new image
"""
try:
pixbuf = GdkPixbuf.Pixbuf.new_from_file(imageURI)
pixbuf = pixbuf.scale_simple(300, 200, GdkPixbuf.InterpType.BILINEAR)
self.img_previews[imageId].set_from_pixbuf(pixbuf)
except:
pass
def extractHeifImages(self, imageURI: str):
""" Extract all images in a heif file
Args:
imageURI (str): URI to the heif file
"""
imageURI = imageURI.replace("%20", "\ ")
filename = imageURI[imageURI.rfind("/") + 1:imageURI.rfind(".")]
self.image_source = Source.EXTRACT
self.wipeImages(Source.EXTRACT)
os.system("heif-convert " + imageURI + " " + IMAGE_EXTRACT_DIR + filename + ".jpg")
self.createExtracted()
def wipeImages(self, source: Source):
""" Removes all image of a folder
Args:
source (Source): Choose the folder by selecting the Source
"""
if source == Source.EXTRACT:
dir = IMAGE_EXTRACT_DIR + "*"
elif source == Source.SELECTED:
dir = IMAGE_SELECTED_DIR + "*"
for file in glob.glob(dir):
os.remove(file)
def createExtracted(self):
""" Create the extracted images array
"""
try:
if self.image_source == Source.SELECTED:
self.extracted = os.listdir(IMAGE_SELECTED_DIR)
elif self.image_source == Source.EXTRACT:
self.extracted = os.listdir(IMAGE_EXTRACT_DIR)
self.extracted.sort()
for combobox in self.cb_previews:
for option in self.extracted:
combobox.append_text(option)
except:
pass
self.stack_main.set_visible_child_name("config")
def copyToSelected(self, source: Source):
""" Copies the extracted images to "res/"
"""
# Clean the "selected folder up"
self.wipeImages(Source.SELECTED)
# Estimate the source folder
if source == Source.EXTRACT:
source_folder = IMAGE_EXTRACT_DIR
else:
source_folder = IMAGE_SETS_DIR + self.cb_image_set.get_active_text() + "/"
# Copy it to "selected/"
for image in os.listdir(source_folder):
shutil.copy(source_folder + image, IMAGE_SELECTED_DIR + image)
def imageSetVisibility(self, source: Source):
""" Toggle the visibility of the option in the "Image set" box
Args:
source (Source): Toggle by type of Source
"""
self.image_source = source
self.lb_image_set.set_visible(source == Source.SET)
self.cb_image_set.set_visible(source == Source.SET)
self.lb_heic_file.set_visible(source != Source.SET)
self.fc_heic_file.set_visible(source != Source.SET)
for i in range(0, 9):
self.cb_previews[i].set_visible(source != Source.SET)
########## UI Signals ##########
def onImageSetSelected(self, cb):
""" UI signal if the image set combo box value changed
Args:
cb (GtkComboBox): The active ComboBox
"""
if self.image_source != Source.SELECTED:
set_name = cb.get_active_text()
for i, _ in enumerate(self.img_previews):
self.changePreviewImage(i, IMAGE_SETS_DIR + set_name + "/" + str(i + 1) + ".jpg")
def onRadioImageSet(self, rb):
""" UI signal if the radio buttons are toggled
Args:
rb (GtkRadioButton): The toggled RadioButton
"""
if rb.get_active():
self.imageSetVisibility(Source.SET)
else:
self.imageSetVisibility(Source.EXTRACT)
def onHeifSelected(self, fc):
""" UI signal if the filechooser has a file selected
Args:
fc (filechooser): The selected filechooser
"""
# Get the URI to the file
uri = fc.get_file().get_uri()
uri = uri[7:]
self.stack_main.set_visible_child_name("load")
thread = threading.Thread(target=self.extractHeifImages, args=(uri, ))
thread.daemon = True
thread.start()
def onPreviewComboboxSelected(self, cb):
""" UI signal if one of the preview combobox is selected
Args:
cb (ComboBox): The selected combobox
"""
number = Gtk.Buildable.get_name(cb)
number = number[number.rfind("_") + 1:]
if self.image_source == Source.EXTRACT:
self.changePreviewImage(int(number) - 1, IMAGE_EXTRACT_DIR + cb.get_active_text())
def onApply(self, *args):
""" UI signal if the user presses the "Apply" button
"""
self.writeToSettings()
self.copyToSelected(self.image_source)
Gtk.main_quit()
def onDestroy(self, *args):
""" UI signal if the window is closed by the user
"""
Gtk.main_quit()

View File

@@ -2,7 +2,7 @@
# Imports
import gi, os, subprocess
from scripts.time_bar import create_bar_chart
from scripts.time_bar_chart import Time_Bar_Chart
from scripts.cinnamon_pref_handler import *
from scripts.suntimes import *
from scripts.location import *
@@ -31,36 +31,39 @@ class Preferences:
self.builder.add_from_file(GLADE_URI)
self.builder.connect_signals(self)
self.time_bar_chart = Time_Bar_Chart()
self.cinnamon_prefs = Cinnamon_Pref_Handler()
# Load all settings from file
self.settings_dict = {
PrefenceEnums.EXPAND_OVER_ALL_DISPLAY: read_str_from_preferences(PrefenceEnums.EXPAND_OVER_ALL_DISPLAY),
PrefenceEnums.SHOW_ON_LOCK_SCREEN: read_str_from_preferences(PrefenceEnums.SHOW_ON_LOCK_SCREEN),
PrefenceEnums.IMAGE_SOURCE: read_str_from_preferences(PrefenceEnums.IMAGE_SOURCE),
PrefenceEnums.SELECTED_IMAGE_SET: read_str_from_preferences(PrefenceEnums.SELECTED_IMAGE_SET),
PrefenceEnums.PERIOD_0_IMAGE: read_str_from_preferences(PrefenceEnums.PERIOD_0_IMAGE),
PrefenceEnums.PERIOD_1_IMAGE: read_str_from_preferences(PrefenceEnums.PERIOD_1_IMAGE),
PrefenceEnums.PERIOD_2_IMAGE: read_str_from_preferences(PrefenceEnums.PERIOD_2_IMAGE),
PrefenceEnums.PERIOD_3_IMAGE: read_str_from_preferences(PrefenceEnums.PERIOD_3_IMAGE),
PrefenceEnums.PERIOD_4_IMAGE: read_str_from_preferences(PrefenceEnums.PERIOD_4_IMAGE),
PrefenceEnums.PERIOD_5_IMAGE: read_str_from_preferences(PrefenceEnums.PERIOD_5_IMAGE),
PrefenceEnums.PERIOD_6_IMAGE: read_str_from_preferences(PrefenceEnums.PERIOD_6_IMAGE),
PrefenceEnums.PERIOD_7_IMAGE: read_str_from_preferences(PrefenceEnums.PERIOD_7_IMAGE),
PrefenceEnums.PERIOD_8_IMAGE: read_str_from_preferences(PrefenceEnums.PERIOD_8_IMAGE),
PrefenceEnums.PERIOD_9_IMAGE: read_str_from_preferences(PrefenceEnums.PERIOD_9_IMAGE),
PrefenceEnums.PERIOD_SOURCE: read_str_from_preferences(PrefenceEnums.PERIOD_SOURCE),
PrefenceEnums.LOCATION_REFRESH_INTERVALS: read_int_from_preferences(PrefenceEnums.LOCATION_REFRESH_INTERVALS),
PrefenceEnums.LATITUDE: read_float_from_preferences(PrefenceEnums.LATITUDE),
PrefenceEnums.LONGITUDE: read_float_from_preferences(PrefenceEnums.LONGITUDE),
PrefenceEnums.PERIOD_0_STARTTIME: read_str_from_preferences(PrefenceEnums.PERIOD_0_STARTTIME),
PrefenceEnums.PERIOD_1_STARTTIME: read_str_from_preferences(PrefenceEnums.PERIOD_1_STARTTIME),
PrefenceEnums.PERIOD_2_STARTTIME: read_str_from_preferences(PrefenceEnums.PERIOD_2_STARTTIME),
PrefenceEnums.PERIOD_3_STARTTIME: read_str_from_preferences(PrefenceEnums.PERIOD_3_STARTTIME),
PrefenceEnums.PERIOD_4_STARTTIME: read_str_from_preferences(PrefenceEnums.PERIOD_4_STARTTIME),
PrefenceEnums.PERIOD_5_STARTTIME: read_str_from_preferences(PrefenceEnums.PERIOD_5_STARTTIME),
PrefenceEnums.PERIOD_6_STARTTIME: read_str_from_preferences(PrefenceEnums.PERIOD_6_STARTTIME),
PrefenceEnums.PERIOD_7_STARTTIME: read_str_from_preferences(PrefenceEnums.PERIOD_7_STARTTIME),
PrefenceEnums.PERIOD_8_STARTTIME: read_str_from_preferences(PrefenceEnums.PERIOD_8_STARTTIME),
PrefenceEnums.PERIOD_9_STARTTIME: read_str_from_preferences(PrefenceEnums.PERIOD_9_STARTTIME),
PrefenceEnums.EXPAND_OVER_ALL_DISPLAY: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.EXPAND_OVER_ALL_DISPLAY),
PrefenceEnums.SHOW_ON_LOCK_SCREEN: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.SHOW_ON_LOCK_SCREEN),
PrefenceEnums.IMAGE_SOURCE: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.IMAGE_SOURCE),
PrefenceEnums.SELECTED_IMAGE_SET: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.SELECTED_IMAGE_SET),
PrefenceEnums.PERIOD_0_IMAGE: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_0_IMAGE),
PrefenceEnums.PERIOD_1_IMAGE: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_1_IMAGE),
PrefenceEnums.PERIOD_2_IMAGE: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_2_IMAGE),
PrefenceEnums.PERIOD_3_IMAGE: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_3_IMAGE),
PrefenceEnums.PERIOD_4_IMAGE: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_4_IMAGE),
PrefenceEnums.PERIOD_5_IMAGE: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_5_IMAGE),
PrefenceEnums.PERIOD_6_IMAGE: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_6_IMAGE),
PrefenceEnums.PERIOD_7_IMAGE: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_7_IMAGE),
PrefenceEnums.PERIOD_8_IMAGE: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_8_IMAGE),
PrefenceEnums.PERIOD_9_IMAGE: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_9_IMAGE),
PrefenceEnums.PERIOD_SOURCE: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_SOURCE),
PrefenceEnums.LOCATION_REFRESH_INTERVALS: self.cinnamon_prefs.read_int_from_preferences(PrefenceEnums.LOCATION_REFRESH_INTERVALS),
PrefenceEnums.LATITUDE: self.cinnamon_prefs.read_float_from_preferences(PrefenceEnums.LATITUDE),
PrefenceEnums.LONGITUDE: self.cinnamon_prefs.read_float_from_preferences(PrefenceEnums.LONGITUDE),
PrefenceEnums.PERIOD_0_STARTTIME: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_0_STARTTIME),
PrefenceEnums.PERIOD_1_STARTTIME: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_1_STARTTIME),
PrefenceEnums.PERIOD_2_STARTTIME: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_2_STARTTIME),
PrefenceEnums.PERIOD_3_STARTTIME: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_3_STARTTIME),
PrefenceEnums.PERIOD_4_STARTTIME: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_4_STARTTIME),
PrefenceEnums.PERIOD_5_STARTTIME: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_5_STARTTIME),
PrefenceEnums.PERIOD_6_STARTTIME: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_6_STARTTIME),
PrefenceEnums.PERIOD_7_STARTTIME: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_7_STARTTIME),
PrefenceEnums.PERIOD_8_STARTTIME: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_8_STARTTIME),
PrefenceEnums.PERIOD_9_STARTTIME: self.cinnamon_prefs.read_str_from_preferences(PrefenceEnums.PERIOD_9_STARTTIME),
}
@@ -127,7 +130,7 @@ class Preferences:
elif self.settings_dict[PrefenceEnums.PERIOD_SOURCE] == PeriodSourceEnum.CUSTOMTIMEPERIODS:
self.tb_time_periods.set_active(True)
self.spb_network_location_refresh_time.set_value(read_int_from_preferences(PrefenceEnums.LOCATION_REFRESH_INTERVALS))
self.spb_network_location_refresh_time.set_value(self.cinnamon_prefs.read_int_from_preferences(PrefenceEnums.LOCATION_REFRESH_INTERVALS))
self.etr_latitude.set_text(str(self.settings_dict[PrefenceEnums.LATITUDE]))
self.etr_longitude.set_text(str(self.settings_dict[PrefenceEnums.LONGITUDE]))
@@ -146,7 +149,7 @@ class Preferences:
time_periods_min.append(time_range[0].hour * 60 + time_range[0].minute)
# Create time bar
create_bar_chart(1200, 150, time_periods_min)
self.time_bar_chart.create_bar_chart(1200, 150, time_periods_min)
# Load to the view
pixbuf = GdkPixbuf.Pixbuf.new_from_file("time_bar.svg")
@@ -258,7 +261,7 @@ class Preferences:
def on_apply(self, *args):
# Store all values to the JSON file
for item in self.settings_dict:
write_to_preferences(item, self.settings_dict[item])
self.cinnamon_prefs.write_to_preferences(item, self.settings_dict[item])
# Close the window
self.on_destroy()

View File

@@ -1,19 +1,21 @@
import os, json
from enums.PreferenceEnums import PrefenceEnums
# Location of the Cinnamon preference file since Cinnamon 5.4
pref_location = os.path.expanduser("~") + \
class Cinnamon_Pref_Handler:
def __init__(self) -> None:
# Location of the Cinnamon preference file since Cinnamon 5.4
self.pref_location = os.path.expanduser("~") + \
"/.config/cinnamon/spices/cinnamon-dynamic-wallpaper@TobiZog/cinnamon-dynamic-wallpaper@TobiZog.json"
def write_to_preferences(parameter: PrefenceEnums, value: str):
def write_to_preferences(self, parameter: PrefenceEnums, value: str):
""" Write a preference value to the JSON file
Args:
parameter (PrefenceEnums): Name of the parameter
value (str): Value to write
"""
with open(pref_location, "r") as pref_file:
with open(self.pref_location, "r") as pref_file:
pref_data = json.load(pref_file)
if parameter in pref_data:
@@ -26,11 +28,11 @@ def write_to_preferences(parameter: PrefenceEnums, value: str):
"value": value
}
with open(pref_location, "w") as pref_file:
with open(self.pref_location, "w") as pref_file:
json.dump(pref_data, pref_file, separators=(',', ':'), indent=4)
def read_str_from_preferences(parameter: PrefenceEnums) -> str:
def read_str_from_preferences(self, parameter: PrefenceEnums) -> str:
""" Read a value from the JSON file
Args:
@@ -40,7 +42,7 @@ def read_str_from_preferences(parameter: PrefenceEnums) -> str:
str: Value of the parameter
"""
try:
with open(pref_location, "r") as pref_file:
with open(self.pref_location, "r") as pref_file:
pref_data = json.load(pref_file)
except:
return ""
@@ -50,16 +52,34 @@ def read_str_from_preferences(parameter: PrefenceEnums) -> str:
else:
return ""
def read_int_from_preferences(parameter: PrefenceEnums) -> int:
value = read_str_from_preferences(parameter)
def read_int_from_preferences(self, parameter: PrefenceEnums) -> int:
""" Read a value from the JSON file
Args:
parameter (PrefenceEnums): Name of the parameter to get
Returns:
str: Value of the parameter
"""
value = self.read_str_from_preferences(parameter)
if value == "":
return 0
else:
return int(value)
def read_float_from_preferences(parameter: PrefenceEnums) -> float:
value = read_str_from_preferences(parameter)
def read_float_from_preferences(self, parameter: PrefenceEnums) -> float:
""" Read a value from the JSON file
Args:
parameter (PrefenceEnums): Name of the parameter to get
Returns:
str: Value of the parameter
"""
value = self.read_str_from_preferences(parameter)
if value == "":
return 0.0

View File

@@ -1,129 +0,0 @@
import math
image_code = []
colors = [
"00193d",
"05597f",
"54babf",
"bfe3c2",
"ffbf6b",
"fdb55c",
"f37f73",
"b45bbc",
"7e38ce",
"00285f"
]
bar_pos_x = []
def create_bar_chart(image_width: int, image_height: int, times: list):
""" Create a time bar chart
Args:
image_width (int): Width of the image in pixel
image_height (int): Height of the image in pixel
times (list): List of start times of the periods in minutes since midnight
"""
create_bar(image_width, image_height, times)
create_polylines(image_width, image_height)
create_time_markers(image_width, image_height)
# Write to file
image_code.insert(0, '<svg xmlns="http://www.w3.org/2000/svg" width="%s" height="%s">' % (image_width, image_height))
image_code.append('</svg>')
file = open("time_bar.svg", "w")
for i in image_code:
file.write(i + '\n')
def create_bar(image_width: int, image_height: int, times: list):
""" Generates the code for the horizontal multi-color bar chart
Args:
image_width (int): Total width of the image
image_height (int): Total height of the image
times (list): List of start times of the periods, in minutes
"""
x = 0
y = 40
width = 0
height = image_height - 80
times.append(1440)
# Adding the bar parts
for i in range(1, len(times)):
width = math.ceil((((100 / 1440) * (times[i] - times[i - 1]) / 100) * image_width))
image_code.append(
'<rect fill="#%s" x="%s" y="%s" width="%s" height="%s"/>' % (colors[i - 1], x, y, width, height)
)
bar_pos_x.append(x)
x += width
def create_time_markers(image_width: int, image_height: int):
""" Generates the code for the vertical hour markers
Args:
image_width (int): Total width of the image
image_height (int): Total height of the image
"""
for i in range(0, 8):
image_code.append(
'<line x1="%s" y1="40" x2="%s" y2="%s" stroke="gray" stroke-width="2" />' %
(i * (image_width // 8), i * (image_width // 8), image_height - 40)
)
image_code.append(
'<text x="%s" y="%s" fill="gray" font-size="20" font-family="Liberation Sans">%s</text>' %
(i * (image_width // 8) + 5, image_height - 45, i * 3)
)
def create_polylines(image_width: int, image_height: int):
""" Generates the code for the polylines which connect the images with the bar sections
Args:
image_width (int): Total width of the image
image_height (int): Total height of the image
"""
bar_x_start = 0
bar_pos_x.append(image_width)
for i in range(0, len(bar_pos_x) - 1):
# X-Middle of a bar
bar_mid = bar_x_start + (bar_pos_x[i + 1] - bar_x_start) / 2
# Position of the image in the window
image_x = (image_width - 32) / 10 + ((i // 2) % 5) * image_width / 5
# i == 0, 2, 4, ... => Upper Polylines
if (i % 2 == 0):
polyline_y = 0
else:
polyline_y = image_height
if i == 0 or i == 8:
polyline_x = 30
elif i == 2 or i == 6:
polyline_x = 20
elif i == 1 or i == 9:
polyline_x = image_height - 30
elif i == 3 or i == 7:
polyline_x = image_height - 20
elif i == 5:
polyline_x = image_height - 10
else:
polyline_x = 10
image_code.append(
'<polyline points="%s,%s %s,%s %s,%s %s,%s" stroke="#%s" fill="none" stroke-width="5" />' %
(image_x, polyline_y, image_x, polyline_x, bar_mid, polyline_x, bar_mid, image_height / 2, colors[i])
)
# Store the end point of the bar as start point of the next
bar_x_start = bar_pos_x[i + 1]

View File

@@ -0,0 +1,132 @@
import math
class Time_Bar_Chart:
def __init__(self) -> None:
self.image_code = []
self.colors = [
"00193d",
"05597f",
"54babf",
"bfe3c2",
"ffbf6b",
"fdb55c",
"f37f73",
"b45bbc",
"7e38ce",
"00285f"
]
self.bar_pos_x = []
def create_bar_chart(self, image_width: int, image_height: int, times: list):
""" Create a time bar chart
Args:
image_width (int): Width of the image in pixel
image_height (int): Height of the image in pixel
times (list): List of start times of the periods in minutes since midnight
"""
self.create_bar(image_width, image_height, times)
self.create_polylines(image_width, image_height)
self.create_time_markers(image_width, image_height)
# Write to file
self.image_code.insert(0, '<svg xmlns="http://www.w3.org/2000/svg" width="%s" height="%s">' % (image_width, image_height))
self.image_code.append('</svg>')
file = open("time_bar.svg", "w")
for i in self.image_code:
file.write(i + '\n')
def create_bar(self, image_width: int, image_height: int, times: list):
""" Generates the code for the horizontal multi-color bar chart
Args:
image_width (int): Total width of the image
image_height (int): Total height of the image
times (list): List of start times of the periods, in minutes
"""
x = 0
y = 40
width = 0
height = image_height - 80
times.append(1440)
# Adding the bar parts
for i in range(1, len(times)):
width = math.ceil((((100 / 1440) * (times[i] - times[i - 1]) / 100) * image_width))
self.image_code.append(
'<rect fill="#%s" x="%s" y="%s" width="%s" height="%s"/>' % (self.colors[i - 1], x, y, width, height)
)
self.bar_pos_x.append(x)
x += width
def create_time_markers(self, image_width: int, image_height: int):
""" Generates the code for the vertical hour markers
Args:
image_width (int): Total width of the image
image_height (int): Total height of the image
"""
for i in range(0, 8):
self.image_code.append(
'<line x1="%s" y1="40" x2="%s" y2="%s" stroke="gray" stroke-width="2" />' %
(i * (image_width // 8), i * (image_width // 8), image_height - 40)
)
self.image_code.append(
'<text x="%s" y="%s" fill="gray" font-size="20" font-family="Liberation Sans">%s</text>' %
(i * (image_width // 8) + 5, image_height - 45, i * 3)
)
def create_polylines(self, image_width: int, image_height: int):
""" Generates the code for the polylines which connect the images with the bar sections
Args:
image_width (int): Total width of the image
image_height (int): Total height of the image
"""
bar_x_start = 0
self.bar_pos_x.append(image_width)
for i in range(0, len(self.bar_pos_x) - 1):
# X-Middle of a bar
bar_mid = bar_x_start + (self.bar_pos_x[i + 1] - bar_x_start) / 2
# Position of the image in the window
image_x = (image_width - 32) / 10 + ((i // 2) % 5) * image_width / 5
# i == 0, 2, 4, ... => Upper Polylines
if (i % 2 == 0):
polyline_y = 0
else:
polyline_y = image_height
if i == 0 or i == 8:
polyline_x = 30
elif i == 2 or i == 6:
polyline_x = 20
elif i == 1 or i == 9:
polyline_x = image_height - 30
elif i == 3 or i == 7:
polyline_x = image_height - 20
elif i == 5:
polyline_x = image_height - 10
else:
polyline_x = 10
self.image_code.append(
'<polyline points="%s,%s %s,%s %s,%s %s,%s" stroke="#%s" fill="none" stroke-width="5" />' %
(image_x, polyline_y, image_x, polyline_x, bar_mid, polyline_x, bar_mid, image_height / 2, self.colors[i])
)
# Store the end point of the bar as start point of the next
bar_x_start = self.bar_pos_x[i + 1]

View File

@@ -12,7 +12,8 @@ const St = imports.gi.St;
const Main = imports.ui.main;
const Util = imports.misc.util;
const MessageTray = imports.ui.messageTray;
const UUID = "cinnamon-dynamic-wallpaper@TobiZog";
const DIRECTORY = imports.ui.extensionSystem.extensionMeta[UUID];
@@ -45,7 +46,8 @@ function showNotification(title, text, showOpenSettings = false) {
notification.addButton("open-settings", _("Open settings"));
notification.connect("action-invoked", () =>
Util.spawnCommandLine("xlet-settings extension " + UUID));
Util.spawnCommandLine("/usr/bin/env python3 " +
DIRECTORY.path + "/preferences/preferences.py"));
}
// Put all together

View File

@@ -2,5 +2,13 @@
"first_start": {
"type": "generic",
"default": true
},
"image_source": {
"type": "generic",
"default": "image_set"
},
"period_source": {
"type": "generic",
"default": "network_location"
}
}

View File

@@ -3,12 +3,9 @@
"uuid": "cinnamon-dynamic-wallpaper@TobiZog",
"name": "Cinnamon Dynamic Wallpaper",
"description": "Cinnamon extension for dynamic desktop backgrounds based on time and location",
"version": "1.4",
"version": "2.0",
"multiversion": true,
"cinnamon-version": [
"4.8",
"5.0",
"5.2",
"5.4",
"5.6",
"5.8"