Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion catalog.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"fr": "Lire et modifier la scène ouverte dans Blender grâce à l'extension OpenCode Link : changements typés en un pas d'annulation, inspection du Blender lancé, rendus de vérification et en arrière-plan."
},
"app": { "name": "Blender", "versions": ">=5.3" },
"host": { "protocol": 1, "range": "^0.4.4" },
"host": { "protocol": 1, "range": "^0.4.5" },
"docs": "https://github.com/NeuralNomadsAI/opencode-integrations/blob/main/integrations/blender/plugin/README.md",
"status": "preview",
"sources": { "git": ["github:NeuralNomadsAI/opencode-integrations#main::path:integrations/blender/plugin"] }
Expand Down
4 changes: 2 additions & 2 deletions integrations/blender/host/opencode_link/addon.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,9 +252,9 @@ def _on_change(*_args):


@persistent
def _on_save(*_args):
def _on_save(*args):
if _session is not None:
_session.app.saved()
_session.app.saved(args[0] if args and isinstance(args[0], str) else None)


@persistent
Expand Down
57 changes: 50 additions & 7 deletions integrations/blender/host/opencode_link/blender_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,10 @@ def __init__(self, code_execution_allowed):
self._revision = process_state().__dict__.pop("revision", 0)
self._evaluations = 0
self._saves = 0
self._loads = 0
self._saved_revision = None # the revision at the last save or load of a file
self._steps_since_save = [] # the OpenCode undo steps pushed since then
self._saved_content = None
self._handle = new_script_handle()
self._main = threading.main_thread()
self.background = bool(bpy.app.background)
Expand Down Expand Up @@ -233,12 +236,42 @@ def refresh_document(self):
def document_known(self):
return self._document_known

def saved(self):
"""save_post handler: the document's file name may have changed."""
def saved(self, path=None):
"""save_post handler: the document's file name may have changed. Blender calls it for a copy too (with
the copy's path): the open file then keeps its changes."""
current = getattr(bpy.data, "filepath", "")
if path and current and os.path.normcase(os.path.abspath(path)) != os.path.normcase(os.path.abspath(current)):
return
self._saves += 1
self._saved_revision = self._revision
self._steps_since_save = []
# Saved by an OpenCode run (a code run calling save_mainfile): what the file holds, to tell at the run's
# end whether the run changed anything after saving (settle_save).
self._saved_content = self.content_digest() if self._quiet else None
self.refresh_document()

def settle_save(self):
"""After a run that saved the open file and moved the revision: the document is as saved when its content
is the one saved. Blender's is_dirty says so only at the next event loop in an interface Blender."""
saved, self._saved_content = self._saved_content, None
if saved is not None and self.content_digest() == saved:
self._saved_revision = self._revision

def unsaved(self):
"""What the file lacks, when the document differs from it: the file's name (None: never saved) and the
OpenCode steps since its last save or load. Changes made by hand are not listed."""
if not self.unsaved_changes():
return None
out = {"file": self._read_document()}
if out["file"] is None:
out["never_saved"] = True
steps = self._steps_since_save
if steps:
out["opencode_steps"] = steps[-10:]
if len(steps) > 10:
out["opencode_steps_count"] = len(steps)
return out

def refresh_display(self):
from .handlers.captures import refresh_display

Expand Down Expand Up @@ -323,17 +356,24 @@ def loaded(self):
self.reset_native()
self.refresh_document()
self._revision += 1
self._loads += 1
self._saved_revision = self._revision if bpy.data.filepath else None
self._steps_since_save = []

def loads(self):
"""Documents loaded in this session (a code run that opened a file pushes no step into it)."""
return self._loads

def unsaved_changes(self):
"""Whether the document differs from its file. Blender's is_dirty, except in background mode, where it
stays set after any undo step even across a save and a reload: there, a document unchanged since its
last save or load counts as saved."""
"""Whether the document differs from its file. A document unchanged since its last save or load counts as
saved: Blender's is_dirty lags there (an interface Blender clears it only at its next event loop, after the
code run that saved; a background one keeps it after any undo step, even across a save and a reload).
Otherwise Blender's is_dirty."""
if not bpy.data.filepath:
return True
if not bpy.data.is_dirty:
if self._saved_revision == self._revision:
return False
return not (bpy.app.background and self._saved_revision == self._revision)
return bool(bpy.data.is_dirty)

@contextlib.contextmanager
def quiet(self):
Expand Down Expand Up @@ -416,6 +456,9 @@ def _with_window(self, fn):
def undo_push(self, message):
self._with_window(lambda: bpy.ops.ed.undo_push(message=message[:63]))
op_watch.undo_stack_made()
# A barrier marks a start; a failure step is undone at once by the restoration: neither is a change.
if not message.startswith(("OpenCode: before ", "OpenCode: failed ")):
self._steps_since_save = (self._steps_since_save + [message[:63]])[-50:]

def undo(self):
epoch = self.script_epoch()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
schema_version = "1.0.0"

id = "opencode_link"
version = "0.4.4"
version = "0.4.5"
name = "OpenCode Link"
tagline = "Lets OpenCode work on this Blender session"
maintainer = "NeuralNomads"
Expand Down
23 changes: 20 additions & 3 deletions integrations/blender/host/opencode_link/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,9 @@ def _state(self):
state["quarantined"] = True
if self.quarantine:
state["quarantine"] = self.quarantine
unsaved = self.app.unsaved() if hasattr(self.app, "unsaved") else None
if unsaved:
state["unsaved"] = unsaved # the file on disk lacks changes of the open document
return state

def _context(self, params):
Expand All @@ -381,6 +384,9 @@ def _context(self, params):
output = self.app.native_context(params["query"])
if self.quarantined:
output["quarantined"] = True
unsaved = self.app.unsaved() if hasattr(self.app, "unsaved") else None
if unsaved:
output["unsaved"] = unsaved
return output
reads = params.get("reads", [])
if not isinstance(reads, list) or len(reads) > MAX_READS:
Expand Down Expand Up @@ -852,6 +858,7 @@ def _guarded(self, run, label, barrier):
# depsgraph updates all, which say nothing. It changed the document only when its content differs after.
content = self.app.content_digest() if not barrier and hasattr(self.app, "content_digest") else None
saves = self.app.saves() if hasattr(self.app, "saves") else 0
loads = self.app.loads() if hasattr(self.app, "loads") else 0
value = error = trace = restored = step = None
with self.app.quiet():
if barrier:
Expand All @@ -872,7 +879,11 @@ def _guarded(self, run, label, barrier):
else:
changed = self.app.evaluations() > evaluations or (digest is not None and self.app.change_digest() != digest)
saved = (self.app.saves() if hasattr(self.app, "saves") else 0) > saves
if changed and barrier and error is None and not saved:
# The run opened another file: the barrier was the old document's; the new one is as loaded.
replaced = (self.app.loads() if hasattr(self.app, "loads") else 0) > loads
if replaced:
changed = True
elif changed and barrier and error is None and not saved:
step = "OpenCode: %s" % label
self.app.undo_push(step)
elif changed and barrier and error is None:
Expand All @@ -884,8 +895,10 @@ def _guarded(self, run, label, barrier):
restored = before is not None and self._restore(before, label)
if not restored:
self._quarantine("failed %s: %s" % (label, error))
if changed:
self.app.bump_revision()
if changed and not replaced:
self.app.bump_revision() # a load already moved the revision
if saved and hasattr(self.app, "settle_save"):
self.app.settle_save() # nothing changed after the save: the document is as saved
return _Run(value=value, error=error, trace=trace, changed=changed, restored=restored, undo_step=step,
stdout=out.getvalue(), stderr=err.getvalue(), revision_before=revision, saved=saved)

Expand All @@ -910,6 +923,7 @@ def _execute_code(self, params):
# modified: inspections and runs after a save leave the file saved; a change is reported, never undone.
read_only = params.get("read_only") is True
rotations = self.app.rotation_snapshot() if hasattr(self.app, "rotation_snapshot") else None
unsaved_before = self.app.unsaved() if hasattr(self.app, "unsaved") else None
notes, hint = [], []

def run():
Expand Down Expand Up @@ -947,6 +961,9 @@ def finish(deferred=None, deferred_error=None):
output["undo_step"] = done.undo_step
if done.saved:
output["saved"] = True
# What that save wrote of OpenCode's: the steps the file lacked before the run (none: an empty list).
output["saved_steps"] = (unsaved_before or {}).get("opencode_steps", []) + (
["OpenCode: code (this run)"] if done.changed else [])
if warnings:
output["warnings"] = warnings
if done.error:
Expand Down
2 changes: 1 addition & 1 deletion integrations/blender/host/ops.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"addon": "opencode_link",
"version": "0.4.4",
"version": "0.4.5",
"protocol": 1,
"method": "apply",
"wire": "params.operations: [{op, args}] with every op below (an edit batch); unknown ops and fields are refused",
Expand Down
Loading
Loading