Skip to content

Commit

Permalink
implemented location component and accept overwrite location only if …
Browse files Browse the repository at this point in the history
…detected as valid
  • Loading branch information
tappi287 committed Jul 9, 2023
1 parent 78397bd commit 678ca8f
Show file tree
Hide file tree
Showing 6 changed files with 183 additions and 100 deletions.
112 changes: 62 additions & 50 deletions app.py
Expand Up @@ -26,44 +26,82 @@
setup_logging()


def start_eel(npm_serve=True):
def in_restore_mode() -> bool:
""" Return True if App is started in Restore Mode """
if len(sys.argv) > 1 and sys.argv[1] == '-b':
logging.warning('Found restore mode argument. Beginning to restore rFactor 2 settings.')
restore_backup()
logging.warning('\nFinished Restore Mode. Exiting application.')
return True
return False


def prepare_app_start() -> bool:
""" Return True if npm_serve should be used """
logging.info('\n\n\n')
logging.info('#######################################################')
logging.info('################ Starting APP ###########')
logging.info('#######################################################\n\n\n')
logging.info(f'Args: {sys.argv}')

"""
THIS WILL DISABLE ctypes support! But it will make sure "Launch rFactor2"
or basically any executable that is loading DLLs will work.
"""
if sys.platform == "win32":
import ctypes
ctypes.windll.kernel32.SetDllDirectoryA(None)
"""
//
"""

AppSettings.load()
AppSettings.copy_default_presets()
AppSettings.delete_current_settings_presets()

if FROZEN:
npm_serve = False
# Set Exception hook
sys.excepthook = AppExceptionHook.exception_hook
return False
return True

# -- Restore Mode
if len(sys.argv) > 1 and sys.argv[1] == '-b':
logging.warning(f'Found restore mode argument. Beginning to restore rFactor 2 settings.')
restore_backup()
logging.warning('\nFinished Restore Mode. Exiting application.')
return

AppSettings.load()
AppSettings.copy_default_presets()
AppSettings.delete_current_settings_presets()
def _main_app_loop():
# -- Game Controller Greenlet
cg = eel.spawn(controller_greenlet)

# -- Headlights Greenlet
hg = eel.spawn(headlights_greenlet)

# -- rFactor Greenlet
rg = eel.spawn(rfactor_greenlet)

# -- YouTUbe Greenlet
yg = eel.spawn(youtube_greenlet)

# -- Run until window/tab closed
logging.debug('Entering Event Loop')
while not CLOSE_EVENT.is_set():
# Game controller event loop
controller_event_loop()
# rFactor 2 event loop
rfactor_event_loop()
# YouTube live chat event loop
youtube_eventloop()
# Capture exception events
AppExceptionHook.exception_event_loop()

# -- Shutdown Greenlets
logging.debug('Shutting down Greenlets.')
gevent.joinall((cg, hg, rg, yg), timeout=15.0, raise_error=True)


def start_eel(npm_serve=True):
# This will ask for and re-run with admin rights
# if setting needs_admin set.
if AppSettings.needs_admin and not run_as_admin():
return

"""
THIS WILL DISABLE ctypes support! But it will make sure "Launch rFactor2"
or basically any executable that is loading DLLs will work.
"""
if sys.platform == "win32":
import ctypes
ctypes.windll.kernel32.SetDllDirectoryA(None)
"""
//
"""
host = 'localhost'
page = 'index.html'
port = 8123
Expand All @@ -78,7 +116,6 @@ def start_eel(npm_serve=True):
url_port = port
eel.init('web')

# TODO: fetch OSError port in use
edge_cmd = f"{os.path.expandvars('%PROGRAMFILES(x86)%')}\\Microsoft\\Edge\\Application\\msedge.exe"
start_url = f'http://{host}:{url_port}'

Expand All @@ -102,37 +139,12 @@ def start_eel(npm_serve=True):
# Open system default web browser
webbrowser.open_new(start_url)

# -- Game Controller Greenlet
cg = eel.spawn(controller_greenlet)

# -- Headlights Greenlet
hg = eel.spawn(headlights_greenlet)

# -- rFactor Greenlet
rg = eel.spawn(rfactor_greenlet)

# -- YouTUbe Greenlet
yg = eel.spawn(youtube_greenlet)

# -- Run until window/tab closed
logging.debug('Entering Event Loop')
while not CLOSE_EVENT.is_set():
# Game controller event loop
controller_event_loop()
# rFactor 2 event loop
rfactor_event_loop()
# YouTube live chat event loop
youtube_eventloop()
# Capture exception events
AppExceptionHook.exception_event_loop()

# -- Shutdown Greenlets
logging.debug('Shutting down Greenlets.')
gevent.joinall((cg, hg, rg, yg), timeout=15.0, raise_error=True)
_main_app_loop()


if __name__ == '__main__':
start_eel()
if not in_restore_mode():
start_eel(prepare_app_start())

# -- Shutdown logging
logging.info('\n\n\n')
Expand Down
8 changes: 6 additions & 2 deletions rf2settings/app/app_chat_fn.py
Expand Up @@ -84,9 +84,13 @@ def uninstall_plugin():

@capture_app_exceptions
def get_plugin_version():
plugin_path = Path(_get_rf_location(RFACTOR_PLUGIN_PATH)) / CHAT_PLUGIN_NAME
try:
plugin_path = Path(_get_rf_location(RFACTOR_PLUGIN_PATH)) / CHAT_PLUGIN_NAME
except Exception as e:
logging.error(f'Error location Plugin: {e}')
plugin_path = None

if plugin_path.exists() and plugin_path.is_file():
if plugin_path and plugin_path.exists() and plugin_path.is_file():
version = AppSettings.chat_plugin_version.get(get_file_hash(plugin_path))
logging.debug('Found ChatTransceiver Plugin version: %s', version)
return json.dumps({'result': True, 'version': version})
Expand Down
21 changes: 15 additions & 6 deletions rf2settings/app/app_main_fn.py
Expand Up @@ -27,16 +27,25 @@ def _get_rf_location(sub_path):

@capture_app_exceptions
def overwrite_rf_location(value):
result = False
def reset_location():
AppSettings.rf_overwrite_location = ''
RfactorLocation.overwrite_location(None)

if Path(value).exists() and Path(value).is_dir() and Path(value) != Path('.'):
AppSettings.rf_overwrite_location = Path(value).as_posix()
RfactorLocation.overwrite_location(AppSettings.rf_overwrite_location)
logging.warning('Overwriting rf2 location: %s', Path(value).as_posix())
result = True
RfactorLocation.get_location()
if not RfactorLocation.is_valid:
logging.warning(f'Invalid overwrite location: {value}. Resetting rF2 location.')
reset_location()
result = False
else:
logging.warning('Overwriting rf2 location: %s', Path(value).as_posix())
result = True
else:
reset_location()
logging.warning('Overwriting rf2 location cleared!')
AppSettings.rf_overwrite_location = ''
RfactorLocation.overwrite_location(None)
result = True

AppSettings.save()
return result
Expand Down Expand Up @@ -112,7 +121,7 @@ def run_steamvr():
subprocess.Popen(cmd)
except Exception as e:
return json.dumps({'result': False, 'msg': f'Error launching SteamVR: {e}'})
return json.dumps({'result': True, 'msg': f'Launched SteamVR'})
return json.dumps({'result': True, 'msg': 'Launched SteamVR'})


@capture_app_exceptions
Expand Down
48 changes: 9 additions & 39 deletions vue/src/App.vue
Expand Up @@ -38,22 +38,11 @@
request administrative privileges on start up:
<b-button class="mt-2 mb-2" @click="resetAdmin" size="sm">Reset UAC</b-button>
</b-card-text>
<b-card-text class="mt-3 mb-3">
<h5>rFactor 2 Location</h5>
If you have trouble locating the correct rFactor 2 installation path, enter it manually here and restart the app.
<b-form-group class="mt-2" :state="rfOverwriteLocationValid"
:valid-feedback="'rF2 install detected! ' + rfactorPath"
:invalid-feedback="'Could not detect valid rF2 install ' + rfactorPath">
<b-input-group>
<b-form-input v-model="rfOverwriteLocation" :state="rfOverwriteLocationValid"
:placeholder="rfactorLocationPlaceholder">
</b-form-input>
<b-input-group-append>
<b-button variant="warning" @click="rfOverwriteLocation=''">Reset</b-button>
</b-input-group-append>
</b-input-group>
</b-form-group>
</b-card-text>

<!-- Overwrite rF Location -->
<h5>rFactor 2 Location</h5>
<RfLocation class="mt-3 mb-3" />

<template #footer>
<span class="small">
Please make sure that a rFactor 2 Steam installation is present on your machine and that you have at least
Expand Down Expand Up @@ -90,6 +79,7 @@
import './assets/app.scss'
import MainPage from "./components/MainPage.vue";
import AppUpdater from "@/components/Updater";
import RfLocation from "@/components/RfLocation.vue";
import {createPopperLite as createPopper, flip, preventOverflow} from "@popperjs/core";
import {getEelJsonObject} from "@/main";
// --- </ Prepare receiving App Exceptions
Expand Down Expand Up @@ -127,9 +117,7 @@ export default {
dragActive: false,
error: '',
rfactorVersion: '',
rfactorPath: '',
rfOverwriteLocation: null,
rfOverwriteLocationValid: null,
rfactorPath: ''
}
},
methods: {
Expand Down Expand Up @@ -172,10 +160,6 @@ export default {
console.log('App found rF version:', this.rfactorVersion)
}
},
getRfLocationValid: async function () {
let r = await getEelJsonObject(window.eel.rf_is_valid()())
if (r !== undefined) { this.rfOverwriteLocationValid = r }
},
setException: function (event) {
this.setError(event.detail)
},
Expand Down Expand Up @@ -212,16 +196,8 @@ export default {
},
components: {
AppUpdater,
MainPage
},
watch: {
rfOverwriteLocation: async function (newValue) {
let r = await getEelJsonObject(window.eel.overwrite_rf_location(newValue)())
if (r !== undefined) {
await this.getRfVersion() // Update rF location
await this.getRfLocationValid() // Update rf install valid state
}
},
MainPage,
RfLocation
},
mounted() {
// Setup the dnd listeners.
Expand All @@ -243,12 +219,6 @@ export default {
this.$eventHub.$on('play-audio', this.playAudio)
},
computed: {
rfactorLocationPlaceholder: function () {
if (this.rfactorPath !== '') { return 'Auto detected: ' + this.rfactorPath }
return 'Path eg. D:\\Steam\\steamapps\\common\\rFactor 2\\'
}
},
beforeDestroy() {
window.removeEventListener('rfactor-live-event', this.$refs.main.updateRfactorLiveState)
window.removeEventListener('rfactor-status-event', this.$refs.main.updateRfactorStatus)
Expand Down
81 changes: 81 additions & 0 deletions vue/src/components/RfLocation.vue
@@ -0,0 +1,81 @@
<template>
<b-card-text>
If you have multiple rFactor 2 installation paths or trouble with outdated Steam files. You can enter the
installation path manually here and restart the app.<br />
This will disable auto detection of the rFactor installation.
<b-form-group class="mt-2" :state="rfOverwriteLocationValid"
:valid-feedback="'rF2 install detected! ' + rfactorPath"
:invalid-feedback="'Could not detect valid rF2 install ' + rfOverwriteLocation">
<b-input-group>
<b-form-input v-model="rfOverwriteLocation" :state="rfOverwriteLocationValid"
:placeholder="rfactorLocationPlaceholder">
</b-form-input>
<b-input-group-append>
<b-button variant="warning" @click="rfOverwriteLocation=''">Reset</b-button>
</b-input-group-append>
</b-input-group>
</b-form-group>
</b-card-text>
</template>

<script>
import {getEelJsonObject} from "@/main";
export default {
name: 'RfLocation',
data: function () {
return {
dragActive: false,
error: '',
rfactorVersion: '',
rfactorPath: '',
rfOverwriteLocation: null,
rfOverwriteLocationValid: null,
}
},
methods: {
getRfVersion: async function () {
let r = await getEelJsonObject(window.eel.get_rf_version()())
if (r !== undefined) {
let version = r.version
this.rfactorPath = r.location
version = version.replace('.', '')
version = version.replace('\n', '')
this.rfactorVersion = version
}
},
getRfLocationValid: async function () {
let r = await getEelJsonObject(window.eel.rf_is_valid()())
if (r !== undefined) {
this.rfOverwriteLocationValid = r
}
}
},
watch: {
rfOverwriteLocation: async function (newValue) {
let r = await getEelJsonObject(window.eel.overwrite_rf_location(newValue)())
if (r !== undefined) {
await this.getRfVersion() // Update rF location
await this.getRfLocationValid() // Update rf install valid state
this.rfOverwriteLocationValid = r
}
},
},
computed: {
rfactorLocationPlaceholder: function () {
if (this.rfactorPath !== '') {
return 'Auto detected: ' + this.rfactorPath
}
return 'Path eg. D:\\Steam\\steamapps\\common\\rFactor 2\\'
}
},
created() {
this.getRfVersion()
}
}
</script>

<style scoped>
</style>

0 comments on commit 678ca8f

Please sign in to comment.