Files
lightgui_python/lightgui/project_io.py

185 lines
6.2 KiB
Python

"""Project file handling: New / Open / Save / Save As for .fdj files.
Builds on lightgui.model.Project (whose save_text/load_text reproduce
the C writer's .fdj layout byte for byte). This module adds the IDE
side: the current path, dirty tracking, file dialogs, and the
confirm-before-discard check. The wrapped Project object is replaced
in place on New/Open so the canvas and Inspector keep their reference
to the same object.
"""
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk # noqa: E402
from lightgui.model import Project # noqa: E402
FDJ_FILTER_NAME = "LightGUI project (*.fdj)"
FDJ_EXTENSION = ".fdj"
def is_fdj_path(path):
return bool(path) and str(path).lower().endswith(FDJ_EXTENSION)
def ensure_fdj_path(path):
path = str(path)
if not path.lower().endswith(FDJ_EXTENSION):
path += FDJ_EXTENSION
return path
def _replace_contents(target, source):
"""Copy *source* Project state into *target* in place (same
object identity, so canvas/Inspector references stay valid)."""
target.__dict__.clear()
target.__dict__.update(source.__dict__)
class ProjectFile:
"""One open project file: the Project, its path, and its dirty
flag. Dirty is set by the app whenever the canvas, Inspector or
project itself changes; loading/saving clears it.
"""
def __init__(self, project=None):
self.project = project if project is not None else Project()
self.path = None
self.dirty = False
# --- state ------------------------------------------------------------
@property
def title(self):
"""Display title: the file basename, or 'Untitled'."""
if self.path:
return self.path.rsplit("/", 1)[-1]
return "Untitled"
def mark_dirty(self):
self.dirty = True
def mark_clean(self):
self.dirty = False
# --- New / Open / Save --------------------------------------------------
def new(self):
"""Replace the project with a fresh empty one (in place)."""
_replace_contents(self.project, Project())
self.path = None
self.dirty = False
return self.project
def open_path(self, path):
"""Load the .fdj file at *path* (in place). Raises ValueError
from the model loader on a bad file; the old project is left
untouched when loading fails."""
project = Project.load_file(path)
_replace_contents(self.project, project)
self.path = path
self.dirty = False
return self.project
def save(self):
"""Save to the current path. Raises ValueError when there is
no path yet (the caller then runs save_as)."""
if not self.path:
raise ValueError("no file name — use Save As")
self.project.save_file(self.path)
self.dirty = False
return self.path
def save_as(self, path):
path = ensure_fdj_path(path)
self.project.save_file(path)
self.path = path
self.dirty = False
return path
# --- dialogs ---------------------------------------------------------------
def confirm_discard(self, parent=None):
"""True when it is OK to throw the current project away
(not dirty, or the user confirmed)."""
if not self.dirty:
return True
dialog = Gtk.MessageDialog(
parent=parent, flags=Gtk.DialogFlags.MODAL,
type=Gtk.MessageType.QUESTION,
buttons=Gtk.ButtonsType.YES_NO,
message_format="Discard unsaved changes to %s?"
% self.title)
response = dialog.run()
dialog.destroy()
return response == Gtk.ResponseType.YES
def open_dialog(self, parent=None):
"""File -> Open: pick a .fdj file and load it. Returns True
on a successful load, False on cancel or a bad file (the
error is reported on *parent* via a message dialog when the
file was picked but failed to load)."""
dialog = Gtk.FileChooserDialog(
title="Open Project", parent=parent,
action=Gtk.FileChooserAction.OPEN,
buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT))
self._add_fdj_filter(dialog)
if self.path:
dialog.set_filename(self.path)
response = dialog.run()
path = dialog.get_filename() if response == Gtk.ResponseType.ACCEPT \
else None
dialog.destroy()
if path is None:
return False
try:
self.open_path(path)
except ValueError as exc:
self._show_error(parent, "Could not open %s:\n%s"
% (path, exc))
return False
return True
def save_dialog(self, parent=None):
"""File -> Save As: pick a path and save there. Returns True
on success, False on cancel."""
dialog = Gtk.FileChooserDialog(
title="Save Project As", parent=parent,
action=Gtk.FileChooserAction.SAVE,
buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_SAVE, Gtk.ResponseType.ACCEPT))
self._add_fdj_filter(dialog)
dialog.set_do_overwrite_confirmation(True)
if self.path:
dialog.set_filename(self.path)
else:
dialog.set_current_name("Untitled.fdj")
response = dialog.run()
path = dialog.get_filename() if response == Gtk.ResponseType.ACCEPT \
else None
dialog.destroy()
if path is None:
return False
self.save_as(path)
return True
@staticmethod
def _add_fdj_filter(dialog):
file_filter = Gtk.FileFilter()
file_filter.set_name(FDJ_FILTER_NAME)
file_filter.add_pattern("*.fdj")
dialog.add_filter(file_filter)
all_filter = Gtk.FileFilter()
all_filter.set_name("All files")
all_filter.add_pattern("*")
dialog.add_filter(all_filter)
@staticmethod
def _show_error(parent, message):
dialog = Gtk.MessageDialog(
parent=parent, flags=Gtk.DialogFlags.MODAL,
type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK,
message_format="%s" % message)
dialog.run()
dialog.destroy()