Skip to content

Commit

Permalink
Merge pull request OpenShot#4553 from ferdnyc/no-autocreate-dirs
Browse files Browse the repository at this point in the history
Don't autocreate user dirs immediately when importing classes.info
  • Loading branch information
ferdnyc authored Dec 9, 2021
2 parents 87f6bc0 + 4f0b596 commit 8b3f9cd
Show file tree
Hide file tree
Showing 11 changed files with 231 additions and 211 deletions.
31 changes: 14 additions & 17 deletions src/classes/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@
import traceback
import json

from PyQt5.QtCore import PYQT_VERSION_STR
from PyQt5.QtCore import QT_VERSION_STR
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtCore import PYQT_VERSION_STR, QT_VERSION_STR, pyqtSlot
from PyQt5.QtWidgets import QApplication, QStyleFactory, QMessageBox


Expand Down Expand Up @@ -72,35 +70,33 @@ def show(self):


class OpenShotApp(QApplication):
""" This class is the primary QApplication for OpenShot.
mode=None (normal), mode=unittest (testing)"""
"""The primary QApplication subclass for OpenShot."""

def __init__(self, *args, mode=None):
QApplication.__init__(self, *args)
self.mode = mode or "normal"
def __init__(self, *args, **kwargs):
self.mode = kwargs.pop("mode", None)
super().__init__(*args, **kwargs)
self.args = super().arguments()
self.errors = []

try:
# Import modules
from classes import info, sentry
from classes import info
from classes.logger import log, reroute_output

# Log the session's start
if mode != "unittest":
if self.mode != "unittest":
import time
log.info("-" * 48)
log.info(time.asctime().center(48))
log.info('Starting new session'.center(48))

log.debug("Starting up in {} mode".format(self.mode))
log.debug("Command line: {}".format(self.args))
log.debug("Command line: %s", self.args)

from classes import settings, project_data, updates
from classes import settings, project_data, updates, sentry
import openshot

# Re-route stdout and stderr to logger
if mode != "unittest":
if self.mode != "unittest":
reroute_output()

except ImportError as ex:
Expand Down Expand Up @@ -137,7 +133,7 @@ def __init__(self, *args, mode=None):
openshot.Settings.Instance().PATH_OPENSHOT_INSTALL = info.PATH

# Check to disable sentry
if not self.settings.get('send_metrics'):
if self.mode == "unittest" or not self.settings.get('send_metrics'):
sentry.disable_tracing()

def show_environment(self, info, openshot):
Expand Down Expand Up @@ -262,7 +258,7 @@ def gui(self):
# Create main window
from windows.main_window import MainWindow
log.debug("Creating main interface window")
self.window = MainWindow(mode=self.mode)
self.window = MainWindow()

# Clear undo/redo history
self.window.updateStatusChanged(False, False)
Expand All @@ -276,7 +272,7 @@ def gui(self):
self.window.RecoverBackup.emit()
return

log.info('Process command-line arguments: %s' % args)
log.info('Process command-line arguments: %s', args[1:])

# Auto load project if passed as argument
if args[1].endswith(".osp"):
Expand Down Expand Up @@ -338,3 +334,4 @@ def onLogTheEnd():
import logging
log = logging.getLogger(".")
log.debug('Failed to write session ended log', exc_info=1)

70 changes: 44 additions & 26 deletions src/classes/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,27 +66,14 @@
# User files
BACKUP_FILE = os.path.join(BACKUP_PATH, "backup.osp")
USER_DEFAULT_PROJECT = os.path.join(USER_PATH, "default.osp")

# Create user paths if they do not exist
# (this is where temp files are stored... such as cached thumbnails)
for folder in [
USER_PATH, BACKUP_PATH, RECOVERY_PATH, THUMBNAIL_PATH, CACHE_PATH,
BLENDER_PATH, TITLE_PATH, TRANSITIONS_PATH, PREVIEW_CACHE_PATH,
USER_PROFILES_PATH, USER_PRESETS_PATH, USER_TITLES_PATH, EMOJIS_PATH,
PROTOBUF_DATA_PATH, YOLO_PATH]:
try:
if not os.path.exists(os.fsencode(folder)):
os.makedirs(folder, exist_ok=True)
except PermissionError:
# Fail gracefully if we have no permission to create these folders
# This happens on build servers, such as Launchpad (imported by Sphinx)
print(f"Failed to create `{folder}` folder due to permissions (ignoring exception)")

# Migrate USER_DEFAULT_PROJECT from former name
LEGACY_DEFAULT_PROJECT = USER_DEFAULT_PROJECT.replace(".osp", ".project")
if all([os.path.exists(LEGACY_DEFAULT_PROJECT), not os.path.exists(USER_DEFAULT_PROJECT)]):
print("Migrating default project file to new name")
os.rename(LEGACY_DEFAULT_PROJECT, USER_DEFAULT_PROJECT)

# Back up "default" values for user paths
_path_defaults = {
k: v for k, v in locals().items()
if k.endswith("_PATH")
and v.startswith(USER_PATH)
}

try:
from PyQt5.QtCore import QSize
Expand Down Expand Up @@ -122,11 +109,6 @@
# Web backend selection, overridable at launch
WEB_BACKEND = 'auto'

# Languages
CMDLINE_LANGUAGE = None
CURRENT_LANGUAGE = 'en_US'
SUPPORTED_LANGUAGES = ['en_US']

# Sentry.io error reporting rate (0.0 TO 1.0)
# 0.0 = no error reporting to Sentry
# 0.5 = 1/2 of errors reported to Sentry
Expand All @@ -138,13 +120,18 @@
ERROR_REPORT_RATE_UNSTABLE = 0.0
ERROR_REPORT_STABLE_VERSION = None

# Languages
CMDLINE_LANGUAGE = None
CURRENT_LANGUAGE = 'en_US'
SUPPORTED_LANGUAGES = ['en_US']

try:
from language import openshot_lang
language_path = ":/locale/"
except ImportError:
language_path = os.path.join(PATH, 'language')
print("Compiled translation resources missing!")
print("Loading translations from: {}".format(language_path))
print(f"Loading translations from: {language_path}")

# Compile language list from :/locale resource
try:
Expand Down Expand Up @@ -209,10 +196,41 @@
}
}

def setup_userdirs():
"""Create user paths if they do not exist (this is where
temp files are stored... such as cached thumbnails)"""
for folder in _path_defaults.values():
if not os.path.exists(os.fsencode(folder)):
os.makedirs(folder, exist_ok=True)

# Migrate USER_DEFAULT_PROJECT from former name
if all([
os.path.exists(LEGACY_DEFAULT_PROJECT),
not os.path.exists(USER_DEFAULT_PROJECT),
]):
print("Migrating default project file to new name")
os.rename(LEGACY_DEFAULT_PROJECT, USER_DEFAULT_PROJECT)


def reset_userdirs():
"""Reset all info.FOO_PATH attributes back to their initial values,
as they may have been modified by the runtime code (retargeting
info.THUMBNAIL_PATH to a project assets directory, for example)"""
for k, v in _path_defaults.items():
globals()[k] = v


def get_default_path(varname):
"""Return the default value of the named info.FOO_PATH attribute,
even if it's been modified"""
return _path_defaults.get(varname, None)


def website_language():
"""Get the current website language code for URLs"""
return {
"zh_CN": "zh-hans/",
"zh_TW": "zh-hant/",
"en_US": ""}.get(CURRENT_LANGUAGE,
"%s/" % CURRENT_LANGUAGE.split("_")[0].lower())

6 changes: 2 additions & 4 deletions src/classes/json_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,7 @@ def read_from_file(self, file_path, path_mode="ignore"):
msg = "Couldn't load {} file".format(self.data_type)
log.error(msg, exc_info=1)
raise Exception(msg) from ex
msg = ()
log.warning(msg)
raise Exception(msg)
raise Exception("Unknown error (should be unreachable)")

def write_to_file(self, file_path, data, path_mode="ignore", previous_path=None):
""" Save JSON settings to a file """
Expand All @@ -229,7 +227,7 @@ def write_to_file(self, file_path, data, path_mode="ignore", previous_path=None)
except Exception as ex:
msg = "Couldn't save {} file:\n{}\n{}".format(self.data_type, file_path, ex)
log.error(msg)
raise Exception(msg)
raise ex

def replace_string_to_absolute(self, match):
"""Replace matched string for converting paths to relative paths"""
Expand Down
22 changes: 14 additions & 8 deletions src/classes/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,19 @@ def filter(self, record):
#
# Create rotating file handler
#
fh = logging.handlers.RotatingFileHandler(
os.path.join(info.USER_PATH, 'openshot-qt.log'),
encoding="utf-8",
maxBytes=25*1024*1024, backupCount=3)
fh.setLevel(info.LOG_LEVEL_FILE)
fh.setFormatter(file_formatter)

log.addHandler(fh)
if os.path.exists(info.USER_PATH):
fh = logging.handlers.RotatingFileHandler(
os.path.join(info.USER_PATH, 'openshot-qt.log'),
encoding="utf-8",
maxBytes=25*1024*1024, backupCount=3)
fh.setLevel(info.LOG_LEVEL_FILE)
fh.setFormatter(file_formatter)
log.addHandler(fh)
else:
class DummyHandler:
def setLevel(self, level):
return True
fh = DummyHandler()

#
# Create typical stream handler which logs to stderr
Expand Down Expand Up @@ -120,3 +125,4 @@ def set_level_file(level=logging.INFO):
def set_level_console(level=logging.INFO):
"""Adjust the minimum log level for output to the terminal"""
sh.setLevel(level)

Loading

0 comments on commit 8b3f9cd

Please sign in to comment.