Inconsistent behaviour of jpatcher_get_parentpatcher/box at loadbang

johnpitcairn's icon

I have an object that registers for notification of containing patcher events with:

object_attach_byptr(myobject, patcher);

My notify function is receiving patcher notification correctly.

When a patch containing my object loads, I am able to use the following function to find the patcher's parentpatcher, patcher's box, and patcher's poly~ instance (if in a poly~) from either loadbang_start or loadbang_end notification:

void _get_parent(t_patcher *patcher, t_patcher **parentpatcher, t_box **box, long *instance) {
  t_object *obj = NIL;
  t_object *nextobj = NIL;
  t_object *nextbox = NIL;
  method m;

  *parentpatcher = jpatcher_get_parentpatcher(patcher);
  *box = jpatcher_get_box(patcher);

  if(!*box) {
    // is there an associated object (poly)?
    object_method(patcher, _s_getassoc, &obj);

    if(obj && (m = zgetfn(obj, _s_getindex))) {
      *instance = (long)(*m)(obj, patcher);

      // find the poly~'s parentpatcher and box
      if(m = zgetfn(obj, _s_parentpatcher)) {
        (*m)(obj, parentpatcher);

        if(*parentpatcher) {
          nextbox = jpatcher_get_firstobject(*parentpatcher);

          while(nextbox) {
            if((nextobj = jbox_get_object(nextbox)) == obj) {
              *box = nextbox;
              break;
            }

            nextbox = jbox_get_nextobject(nextbox);
          }
        }
      }
    }
  }
}

After loading, if an abstraction or poly~ containing my object is manually instantiated, duplicated, pasted, or deleted then undo is used, my object receives the newly instantiated patcher loadbang notifications as expected.

But in these cases, the above code fails to find the patcher's parent patcher and box - even at loadbang_end, when presumably everything should be initialized.

Why?

And is there any solution that will work in these cases (preferably at loadbang_start)?