Commit 5505c70a authored by Roman Alifanov's avatar Roman Alifanov

fix friezes + refactoring

parent 1e760ee0
......@@ -51,28 +51,57 @@ class CommandRunner:
threading.Thread(target=process_runner).start()
class ApplicationManager:
@staticmethod
def get_available_applications():
output = subprocess.check_output(["epm", "play", "--list-all"], universal_newlines=True)
return ApplicationManager.parse_applications_output(output)
def get_available_applications(callback):
threading.Thread(target=ApplicationManager._get_available_applications, args=(callback,)).start()
@staticmethod
def _get_available_applications(callback):
process = subprocess.Popen(["epm", "play", "--list-all"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def read_output():
stdout, stderr = process.communicate()
if process.returncode == 0:
applications = ApplicationManager.parse_applications_output(stdout)
GLib.idle_add(callback, applications)
else:
GLib.idle_add(callback, [], stderr) # Pass error message
threading.Thread(target=read_output).start()
@staticmethod
def get_installed_applications(callback):
threading.Thread(target=ApplicationManager._get_installed_applications, args=(callback,)).start()
@staticmethod
def get_installed_applications():
output = subprocess.check_output(["epm", "play", "--list"], universal_newlines=True)
return ApplicationManager.parse_installed_applications_output(output)
def _get_installed_applications(callback):
process = subprocess.Popen(["epm", "play", "--list"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def read_output():
stdout, stderr = process.communicate()
if process.returncode == 0:
installed_apps = ApplicationManager.parse_installed_applications_output(stdout)
GLib.idle_add(callback, installed_apps)
else:
GLib.idle_add(callback, [], stderr) # Pass error message
threading.Thread(target=read_output).start()
@staticmethod
def parse_applications_output(output):
lines = output.splitlines()[1:]
applications = []
for line in lines:
parts = line.split(' - ')
if len(parts) == 2: # Ensure that line has exactly 2 parts
name, dscr = parts
applications.append({'name': name.strip().replace('&', '&'),
'dscr': dscr.strip().replace('&', '&')})
for line in output.splitlines()[1:]: # Пропустить заголовок
parts = line.split(' - ', 1) # Ограничить сплит до 2 частей
if len(parts) == 2:
name, dscr = map(str.strip, parts)
applications.append({
'name': name.replace('&', '&'),
'dscr': dscr.replace('&', '&')
})
else:
# Логгирование некорректной строки для диагностики
print(f"Неправильный формат строки: {line}")
return applications
@staticmethod
......@@ -80,7 +109,6 @@ class ApplicationManager:
lines = output.splitlines()[1:]
return [line.split(' - ')[0].strip().split()[0] for line in lines]
class MainWindow(Gtk.ApplicationWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
......@@ -91,9 +119,8 @@ class MainWindow(Gtk.ApplicationWindow):
self.box1 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.set_child(self.box1)
# Создание элементов UI
self.create_ui_elements()
self.show_loading_message()
self.loading_count = 0 # Track loading operations
self.load_applications()
def create_ui_elements(self):
......@@ -123,45 +150,48 @@ class MainWindow(Gtk.ApplicationWindow):
def show_loading_message(self):
self.loading_label.set_visible(True)
self.preferences_group.set_visible(False) # Скрыть группу настроек во время загрузки
self.loading_count += 1 # Increment loading counter
def hide_loading_message(self):
self.loading_count -= 1 # Decrement loading counter
if self.loading_count == 0:
self.loading_label.set_visible(False)
self.preferences_group.set_visible(True) # Показать группу настроек после загрузки
self.preferences_group.set_visible(True)
def load_applications(self):
def on_done():
self.hide_loading_message() # Скрыть сообщение о загрузке, когда загрузка завершена
# Асинхронная загрузка приложений
GLib.idle_add(self._load_applications_async, on_done)
def _load_applications_async(self, on_done):
# Симуляция долгой операции
def simulate_long_running_op():
self.applications = ApplicationManager.get_available_applications()
GLib.idle_add(self.update_ui) # Обновление UI с новыми данными
GLib.idle_add(on_done)
self.show_loading_message()
ApplicationManager.get_available_applications(self.on_applications_loaded)
threading.Thread(target=simulate_long_running_op).start()
def on_applications_loaded(self, applications, error=None):
if error:
print(f"Error: {error}")
else:
self.applications = applications
self.update_ui()
self.hide_loading_message() # Move this to ensure it waits for installation loading too
def update_ui(self):
# Обновление списка установленных приложений
self.installed_apps = ApplicationManager.get_installed_applications()
self.show_loading_message() # Show loading again for installed apps
ApplicationManager.get_installed_applications(self.on_installed_apps_loaded)
# Удаление текущего preferences_group
if self.preferences_group:
self.content_box.remove(self.preferences_group)
self.preferences_group = None
# Создание нового preferences_group
self.preferences_group = Adw.PreferencesGroup()
self.content_box.append(self.preferences_group)
def on_installed_apps_loaded(self, installed_apps, error=None):
if error:
print(f"Error: {error}")
else:
self.installed_apps = installed_apps
self.clear_preferences_group()
# Добавление новых элементов
self.checkboxes = {}
for app in self.applications:
self.add_application_row(app)
self.hide_loading_message() # Now only hides after both loads are done
def clear_preferences_group(self):
self.content_box.remove(self.preferences_group)
self.preferences_group = Adw.PreferencesGroup()
self.content_box.append(self.preferences_group)
def add_application_row(self, app):
row = Adw.ActionRow(title=app['name'], subtitle=app['dscr'])
checkbox = Gtk.CheckButton()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment