Context Router¶
A Context Router (mode ID ROUTER) holds an ordered list of branches and an
Otherwise. These functions read and change that saved logic by branch UID.
Creating the menu is pme.create_pm() (Menus), its
hotkey is Hotkeys, and the editor is described in
Context Router Editor.
Function |
Purpose |
|---|---|
Returns the saved logic and its digest under |
|
Changes branches by UID, appends branches, and changes Otherwise. |
|
Removes one branch. |
|
Moves one branch before or after another branch. |
|
Puts every branch in a given order. |
See also: Add a Router branch and edit its condition.
Reading a Router¶
For a Router, read_pm(pm_uid) also returns router:
Key |
Type |
Value |
|---|---|---|
|
dict or None |
The saved logic, described under Router logic.
|
|
str |
SHA-256 hex digest of the saved logic text. Pass it as
|
|
list[dict] |
Empty when the saved logic is readable. Otherwise one entry per
problem, each with |
A new Router has no branches, and Otherwise is set to Pass Through:
>>> pme.editing.read_pm(router_uid)["router"]
{'logic': {'version': 2, 'branches': [],
'otherwise': {'name': 'Otherwise',
'target': {'action': None, 'fallback_name': ''},
'pass': True}},
'digest': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
'diagnostics': []}
The returned dictionaries are copies. Changing them does not change the
Router. A new Router has no saved logic text yet; its digest is the digest of an
empty text. A request equal to the logic shown above returns unchanged and
keeps the text empty. A write that changes the logic stores the text and
changes the digest: read again before the next edit.
Common result keys¶
All four editing functions return a dictionary with these keys:
Key |
Type |
Value |
|---|---|---|
|
str |
See Status below. |
|
bool |
|
|
str |
The |
|
bool |
The |
|
dict or None |
|
|
dict or None |
The same structure, read after a write. A copy of |
|
dict or None |
The complete logic that is saved, or would be saved with
|
|
list[dict] |
One entry per problem or warning: |
Status¶
|
Meaning |
|---|---|
|
The saved logic text was read back equal to |
|
|
|
The resulting logic equals the saved logic, for example branches that
are already in the requested order. Nothing was written. A dry run
returns |
|
Nothing was saved. |
|
A write was attempted and the saved text matches neither the old nor
the new logic. Call |
The shared meaning of these values is defined on Results and guards.
Diagnostics¶
Codes returned by every function on this page:
|
Cause, and extra keys |
|---|---|
|
|
|
|
|
PME preferences cannot be read. |
|
The UID does not name exactly one Router. For example
|
|
The saved logic cannot be read. These entries are the
|
|
|
|
The resulting logic breaks a rule. |
|
Warning. A |
|
The save step did not change the saved text: the encoded logic failed
the final check (traceback printed to the console), or the text read
back unchanged after the write. |
|
The write was attempted and the result is not confirmed. |
|
Reading the Router after the write raised. |
|
Refreshing the editor after the write raised. The save stands. The traceback is printed to the console. |
address values are strings, including branch_index and row_index.
Functions¶
- pme.editing.update_router(pm_uid, *, branches=(), otherwise=None, expected_digest=None, dry_run=False)¶
Change branches by UID, append branches, and change Otherwise.
The whole resulting logic, including branches the call does not mention, is checked before the write. If any rule fails, nothing is saved.
- Parameters:
pm_uid (str) – UID of the Router.
branches (list or tuple of dict) – Branch patches, applied as described under Patch rules.
otherwise (dict or None) – Otherwise fields to replace.
Nonekeeps Otherwise.expected_digest (str or None) – The digest from
read_pm()["router"]. The call is rejected withstale_router_digestwhen it differs.dry_run (bool) – Check the request and return the candidate without writing.
- Returns:
The result described under Common result keys.
- Return type:
- Raises:
RuntimeError – Called outside Blender’s main thread, or before PME has finished loading.
Patch rules
Input
Effect
Entry with
branch_uidUpdates that branch. The UID must name a branch of this Router. A UID may appear once per call.
Entry without
branch_uidAppends a new branch at the end with a new UID. Entries append in list order.
Field omitted from an entry
Keeps the saved value. A new branch uses the defaults below.
name,enabled,combine_mode,targetsuppliedReplace the saved value.
targetis replaced as a whole.conditionssuppliedReplaces the branch’s whole condition list. A row with
condition_uidkeeps that UID. A row without one receives a new UID that is not the UID of any row the branch had before the call.Row
enabled,authoring_state,labelomittedTrue,"complete"and"".Branch not mentioned
Unchanged, including its position.
otherwiseomitted orNoneUnchanged.
otherwisesuppliedReplaces only the supplied keys (
name,target,pass).targetis replaced as a whole.A new branch starts with
name"Branch <n>"(n= number of branches after appending),enabledTrue,combine_mode"all", no conditions, andtarget{"action": None, "fallback_name": ""}.Status
committed,validated,unchanged,rejectedorunknown. A request whose resulting logic equals the saved logic, on a new Router too, returnsunchangedwithout writing. Withdry_run=Truethe same request returnsvalidated.Diagnostics
In addition to the common codes:
codeCause, and extra keys
branches_must_be_a_sequencebranchesis not a list or tuple.pathis"branches".otherwise_must_be_a_mappingotherwiseis neither a dict norNone.router_input_must_be_json_valuesA value cannot be converted to JSON: a non-JSON type, a cycle, NaN or infinity.
branch_must_be_a_mappingAn entry of
branchesis not a dict.pathis"branches[<i>]".branch_uid_invalidbranch_uidis not a non-empty string.branch_not_foundbranch_uidnames no branch of this Router.duplicate_branch_editTwo entries name the same
branch_uid.conditions_must_be_a_sequenceconditionsis not a list or tuple.condition_must_be_a_mappingA condition row is not a dict.
pathis"branches[<i>].conditions[<j>]".Example
Set an existing Router’s No Match to Pass Through:
before = pme.editing.read_pm(router_uid)["router"] result = pme.editing.update_router( router_uid, otherwise={"pass": True}, expected_digest=before["digest"], ) assert result["status"] == "committed", result["diagnostics"]
Notes
The caller’s dictionaries are not changed.
New UIDs in a
validatedcandidate are provisional. To save a preview, repeat the samebranchesandotherwisewithdry_run=False. Do not pass the candidate’s new branch UIDs as existing branches.Branch UIDs are unique within one Router. A UID freed by
remove_router_branch()can be given to a later new branch.router_target_menu_unresolvedwarnings can accompanyvalidatedandcommitted.The call does not evaluate conditions, run targets, change the selected menu or the editor’s draft, save Preferences to disk, or add an Undo step.
- pme.editing.remove_router_branch(pm_uid, branch_uid, *, expected_digest=None, dry_run=False)¶
Remove one branch.
- Parameters:
- Returns:
The result described under Common result keys.
- Return type:
- Raises:
RuntimeError – Called outside Blender’s main thread, or before PME has finished loading.
Status
committed,validated,rejectedorunknown.Diagnostics
In addition to the common codes:
codeCause, and extra keys
branch_uid_invalidbranch_uidis not a non-empty string.branch_not_foundbranch_uidnames no branch of this Router.branch_identity_ambiguousTwo saved branches share a UID.
Example
router = pme.editing.read_pm(router_uid)["router"] result = pme.editing.remove_router_branch( router_uid, router["logic"]["branches"][-1]["branch_uid"], expected_digest=router["digest"], ) assert result["status"] == "committed", result["diagnostics"]
Notes
The last remaining branch can be removed.
Other branches, their condition UIDs, and Otherwise are kept.
The call does not run targets, change the selected menu or the editor’s draft, save Preferences to disk, or add an Undo step.
- pme.editing.move_router_branch(pm_uid, branch_uid, *, before_uid=None, after_uid=None, expected_digest=None, dry_run=False)¶
Move one branch immediately before or after another branch of the same Router.
- Parameters:
pm_uid (str) – UID of the Router.
branch_uid (str) – UID of the branch to move.
before_uid (str or None) – UID of the branch to place it before.
after_uid (str or None) – UID of the branch to place it after. Give exactly one of
before_uidandafter_uid.expected_digest (str or None) – The digest from
read_pm()["router"].dry_run (bool) – Check the request and return the candidate without writing.
- Returns:
The result described under Common result keys.
- Return type:
- Raises:
RuntimeError – Called outside Blender’s main thread, or before PME has finished loading.
Status
committed,validated,unchanged,rejectedorunknown. The current position, including an anchor equal tobranch_uid, returnsunchangedwithout writing. Withdry_run=Truethe same request returnsvalidated.Diagnostics
In addition to the common codes:
codeCause, and extra keys
branch_uid_invalidbranch_uidis not a non-empty string.branch_not_foundbranch_uidnames no branch of this Router.branch_identity_ambiguousTwo saved branches share a UID.
exactly_one_branch_anchor_requiredBoth or neither of
before_uidandafter_uidwere given.branch_anchor_uid_invalidThe anchor is not a non-empty string.
branch_anchor_not_foundThe anchor names no branch of this Router.
Example
Give the last branch the highest priority:
snapshot = pme.editing.read_pm(router_uid)["router"] branches = snapshot["logic"]["branches"] result = pme.editing.move_router_branch( router_uid, branches[-1]["branch_uid"], before_uid=branches[0]["branch_uid"], expected_digest=snapshot["digest"], ) print(result["status"], result["diagnostics"])
Notes
Branch contents, condition UIDs and Otherwise are kept.
The digest changes after a write. Read again before the next edit.
The Branch menu’s Move Up, Move Down and Remove Branch in the editor follow the same branch rules. A save from the editor also applies the editor’s own normalization to other saved values.
The call does not run targets, change the selected menu or the editor’s draft, save Preferences to disk, or add an Undo step.
- pme.editing.reorder_router_branches(pm_uid, branch_uids, *, expected_digest=None, dry_run=False)¶
Put every branch in the given order with one write.
- Parameters:
pm_uid (str) – UID of the Router.
branch_uids – Every branch UID of the Router, each exactly once, in the new order. An ordered iterable: a list, a tuple, a generator or
dict.keys().expected_digest (str or None) – The digest from
read_pm()["router"].dry_run (bool) – Check the request and return the candidate without writing.
- Returns:
The result described under Common result keys.
- Return type:
- Raises:
RuntimeError – Called outside Blender’s main thread, or before PME has finished loading.
Status
committed,validated,unchanged,rejectedorunknown. The current order returnsunchangedwithout writing. Withdry_run=Truethe same request returnsvalidated.Diagnostics
In addition to the common codes:
codeCause, and extra keys
branch_uids_must_be_a_sequencebranch_uidsis a string, bytes, or not iterable.pathis"branch_uids".branch_uids_must_be_orderedbranch_uidsis aset,frozensetor another set type, which has no defined order.received_typenames the type. Returned fordry_run=Trueas well.branch_uids_must_list_every_branch_onceThe list is partial, repeats a UID, or contains a value that is not a branch UID.
missinglists branch UIDs not given;unknownlists given values that are not branch UIDs.branch_identity_ambiguousTwo saved branches share a UID.
pathis"logic.branches".Example
router = pme.editing.read_pm(router_uid)["router"] order = [branch["branch_uid"] for branch in router["logic"]["branches"]] result = pme.editing.reorder_router_branches( router_uid, list(reversed(order)), expected_digest=router["digest"], ) assert result["status"] == "committed", result["diagnostics"]
Notes
Branch contents, their UIDs and Otherwise are kept.
The call does not run targets, save Preferences to disk, or add an Undo step.
Router logic¶
read_pm()["router"]["logic"], candidate, and the input of
update_router() use the ContextRouterLogic shape of PME’s
Schema v2 definitions
(ContextRouterLogic, ContextRouterBranch,
ContextRouterConditionRow, PmeLogicConditionRow,
PmeLogicValueSource, ContextRouterTarget,
ContextRouterTargetAction, ContextRouterOtherwise). Values are plain
JSON values.
{'branch_uid': 'branch_1', 'name': 'Edit Mesh', 'enabled': True,
'combine_mode': 'all',
'conditions': [{'condition_uid': 'cond_1', 'enabled': True,
'authoring_state': 'complete', 'label': 'Condition',
'source': {'kind': 'rna_path', 'root': 'context',
'detected_type': 'enum', 'readonly': True,
'segments': [{'kind': 'attr', 'name': 'mode'}],
'owner_type': None},
'op': 'equals', 'value': 'EDIT_MESH', 'value_type': 'enum'}],
'target': {'action': {'type': 'menu', 'value': 'pm_yp6o3mbh', 'opts': {}},
'fallback_name': 'Mesh Tools'}}
Logic object¶
Key |
Type |
Value |
|---|---|---|
|
int |
|
|
list[dict] |
Branches in priority order. The first enabled branch that matches wins. At most 256. |
|
dict |
What happens when no branch matches. See Otherwise. |
Branch¶
Key |
Type |
Value |
|---|---|---|
|
str |
Identity of the branch within this Router, such as |
|
str |
Display name, at most 256 characters. An empty name is saved as
|
|
bool |
|
|
str |
|
|
list[dict] |
Condition rows, at most 256. Condition UIDs are unique within the branch. A branch without an evaluable condition does not match. |
|
dict |
What runs when the branch matches. See Target. |
Condition¶
A row is either a value condition or an event condition. A row with an
event key is an event condition.
Value condition (PmeLogicConditionRow):
Key |
Type |
Value |
|---|---|---|
|
str |
Identity of the row within its branch, such as |
|
bool |
|
|
str |
|
|
str |
Display name, at most 256 characters. An empty label is saved as
|
|
dict or None |
The value to read. See Condition source. |
|
str or None |
Comparison. See Comparison rules. |
|
bool, int, float, str, list[str] or None |
Comparison value. |
|
str or None |
|
In an incomplete row, source, op, value and value_type may be
None or omitted. A supplied value must still have a valid type.
Event condition (ContextRouterEventModifierConditionRow) tests modifier
keys of the event that invoked the Router:
Key |
Type |
Value |
|---|---|---|
|
As for a value condition. |
|
|
str |
Display name. An empty label is saved as |
|
dict |
|
Condition source¶
source (PmeLogicValueSource):
Key |
Type |
Value |
|---|---|---|
|
str |
|
|
str |
|
|
list[dict] |
|
|
str |
|
|
str or None |
Type of the value: |
|
bool |
Whether the value is read-only. |
|
str or None |
RNA type that resolved the path in the editor. Saved as |
|
int |
|
Segments of an rna_path source:
Segment |
Meaning |
|---|---|
|
Attribute access. |
|
Lookup by string key, as |
|
Lookup by index 0 or greater. |
|
Lookup by an index read from an |
C.area.type is
[{"kind": "attr", "name": "area"}, {"kind": "attr", "name": "type"}] with
root context. A computed value that a path cannot express is read through
a Property (pm_property_ref) or a Property Stack (condition_ref).
Comparison rules¶
In a complete row, value_type equals source.detected_type, and op,
value_type and value form one of these combinations:
|
|
|
|---|---|---|
|
|
|
|
|
A value of that type. |
|
|
As for |
|
|
A number. |
|
|
A string. |
|
|
A non-empty list of non-empty identifiers. |
A combination outside this table is rejected with
schema_v2_router_logic_complete_condition_malformed. The comparison
semantics are described under F. Comparison operator and value.
Target¶
Key |
Type |
Value |
|---|---|---|
|
dict or None |
What runs. |
|
str |
Display name kept with the target, at most 256 characters. Required in a supplied target; may be empty. It is not the target’s identity. |
|
dict |
Optional: |
action (ContextRouterTargetAction):
|
|
|
|---|---|---|
|
UID of a menu: Pie Menu, Vector Menu, Regular Menu, Pop-up Dialog, Floating Panel, Stack Key, Sticky Key, Macro Operator or Modal Operator. Not a Router, Property, Property Stack or Panel Group. |
|
|
Python command text, as in a Command slot. Not blank; no NUL character. |
|
|
Hotkey text, as in a Hotkey slot. Not blank. |
Empty. |
|
Layout code, as in a Custom slot. Not blank. |
Empty. |
opts may be omitted. Command and Custom text is saved as given, without
stripping.
Otherwise¶
Key |
Type |
Value |
|---|---|---|
|
str |
Display name, at most 256 characters. An empty name is saved as
|
|
dict |
The target used with Run Otherwise. Same shape as a branch target. |
|
bool |
|
A new Router starts with pass set to True. A Router saved without the
key reads as Run Otherwise. A Router opened from another menu has no next
candidate and runs nothing when no branch matches. See
Otherwise — fallback behavior.
Vocabularies¶
Field |
Values |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Logic validation codes¶
The resulting logic is checked against the rules above. Each failure is one
diagnostic whose code is schema_v2_router_logic_ followed by the suffix
below. In update_router() results, address holds
branch_index, branch_uid and, for a row, row_index; it is empty
for a problem of the logic object or Otherwise. Saved logic that cannot be read
reports the same suffixes with the prefix router_authoring_ in
read_pm()["router"]["diagnostics"].
Suffix |
Cause |
|---|---|
|
The logic object has a key other than |
|
|
|
A branch is not a dict. |
|
More than 256 branches. |
|
|
|
Two branches share a |
|
A branch has a key other than |
|
|
|
|
|
|
|
|
|
|
|
A condition row is not a dict. |
|
More than 256 conditions in one branch. |
|
Two rows of one branch share a |
|
A row has a key that its row type does not accept. |
|
|
|
|
|
|
|
|
|
|
|
A complete row’s |
|
|
|
|
|
Incomplete row: |
|
Incomplete row: |
|
Incomplete row: |
|
Incomplete row: |
|
|
|
|
|
|
|
|
|
|
|
A branch |
|
A target has a key other than |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
A |
|
A |
|
|
|
|
|
|
|
Otherwise |
|
Otherwise |
|
|
|
Otherwise |
The same rules apply to the saved logic of the branch functions: a saved menu
target that is not a valid menu UID makes remove_router_branch(),
move_router_branch() and reorder_router_branches() return
rejected until update_router() replaces that target.