ActiveView.Modified Event callback

I am in the middle of writing a tool to actively swap the viewport wallpaper by matching the viewport name to a file name in a folder. It was working great until I restarted Rhino. I must have done something else to break it but I can not, for the life of me, figure it out. It is based on @dale Fugier’s
example

I realize that a view.modified event triggers many times when just manipulating a view. So this may not be the best for what I am trying to do. I will explore better ways to trigger the function later. It would be great if there were an OnViewNameChanged or something like that, where it only changes when the Viewport is renamed or set to another saved view.

It appears to create the event handler. But nothing happens when I modify a view.
Any help would be much appreciated. Than you.

################################################################################
# Based on SampleEventHandler.py from Robert McNeel & Associates by Dale Fugier.

# https://github.com/mcneel/rhino-developer-samples/blob/6/rhinopython/SampleEventHandler.py
################################################################################
import System
import Rhino
import scriptcontext as sc
import rhinoscriptsyntax as rs

from os import path, listdir


################################################################################
# SampleEventHandler class
################################################################################


class SampleEventHandler():
    
    # Initializer
    def __init__(self):
        # Enable the event handlers
        Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.Modified += self.OnViewModified
        self.Enabled = True
    
    # Disables the event handlers
    def Disable(self):
        Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.Modified -= self.OnViewModified
        self.Enabled = False
    
    # Returns the enabled state
    def IsEnabled(self):
        return self.Enabled
    
    
    def OnViewModified(self, sender, e):
        
        # set image directory
        image_dir = path.abspath("PATH TO IMAGES HERE")
        extensions = tuple(".jpg", ".png", ".JPG", ".PNG")
        
        images = [f for f in listdir(image_dir) if f.endswith(extensions)]
        
        print(images)
        
        lower_list = map(str.lower, images)

        vName = e.View.ActiveViewport.Name
        print("View Name: {0}".format(vName))
        if (vName + ".jpg") in lower_list:
            img = lower_list.index(vName + ".jpg")
        if (vName + ".png") in lower_list:
            img = lower_list.index(vName + ".png")
        
        if img > -1 :
            print("Image found at index {0}".format(img))
            img_path = path.join(image_dir, (vName + ".jpg"))
            print(img_path)
            Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.WallpaperFilename(vName, img_path)
            
            Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.WallpaperHidden(VName, False)
            print("Found matching image: {0}\n".format(img_path))
        
        else:
            print("image match not found. Hiding wallpaper")
            Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.WallpaperHidden(VName, True)
        
        
################################################################################
# TestSampleEventHandler function
################################################################################
def TestSampleEventHandler():
    # See if we already have a handler
    if sc.sticky.has_key('sample_event_handler'):
        # Delete the handler
        handler = sc.sticky.pop('sample_event_handler', None)
        if handler:
            handler.Disable()
            handler = None
            print ' SampleEventHandler disabled'  
    else:
        # Create handler
        handler = SampleEventHandler()
        # Add the handler to the sticky dictionary so it
        # survives when the main function ends.
        sc.sticky['sample_event_handler'] = handler       
        print ' SampleEventHandler enabled'  
    
################################################################################
# Check to see if this file is being executed as the 'main' python
# script instead of being used as a module by some other python script
# This allows us to use the module which ever way we want.
################################################################################
if __name__ == '__main__':
    TestSampleEventHandler()   


Of course, I find the error immediately.
The list of images is not created with that list comprehension and .endswith

images = [f for f in listdir(image_dir) if f.endswith(extensions)]

Removing the tuple and just going after “.jpg”, for example, fixes it.
I’ll look for some other way to match filenames regardless of extension.

I’d still love to hear alternatives and best practices regarding callbacks and event listeners etc.

Ok, that first post was trash.
Here is my working version:

################################################################################
# Based on SampleEventHandler.py from Robert McNeel & Associates by Dale Fugier.

# https://github.com/mcneel/rhino-developer-samples/blob/6/rhinopython/SampleEventHandler.py
################################################################################
import System
import Rhino
import scriptcontext as sc
import rhinoscriptsyntax as rs

from os import path, listdir


################################################################################
# ViewChangedEventHandler class
################################################################################


class ViewChangedEventHandler():
    
    # Initializer
    def __init__(self):
        # Enable the event handlers
        Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.Modified += self.OnViewModified
        self.Enabled = True
    
    # Disables the event handlers
    def Disable(self):
        Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.Modified -= self.OnViewModified
        self.Enabled = False
    
    # Returns the enabled state
    def IsEnabled(self):
        return self.Enabled
    
    
    def OnViewModified(self, sender, e):
        
        # set image directory
        image_dir = path.abspath("C:\\Users\\jonah.hawk\\IDrive-Sync\\Dev\\Rhino\\Python\\ViewBG")
        print(image_dir)
        extensions = [".jpg", ".png", ".JPG", ".PNG"]
        images = [f for f in listdir(image_dir) if f.endswith(".jpg")]
        # print(images)
        
        lower_list = map(str.lower, images)
        print(lower_list)

        vName = e.View.ActiveViewport.Name
        print("View Name: {0}".format(vName))
        jpg_img = (vName.lower() + ".jpg")
        print(jpg_img)
        jpg_ind = lower_list.index(jpg_img)
        print(jpg_ind)
        
        if jpg_ind > -1:
            img = jpg_ind
            print(jpg_ind)
        elif png_img > -1:
            img = png_img
            print(img)
        else:
            img = -1
            print(img)
        
        if img > -1 :
            print("Image found at index {0}".format(img))
            img_path = path.join(image_dir, images[img])
            print(img_path)
            rs.Wallpaper(vName, img_path)
            rs.WallpaperHidden(vName, False)
        else:
            print("image match not found. Hiding wallpaper")
            s.WallpaperHidden(vName, True)
        
        
################################################################################
# TestSampleEventHandler function
################################################################################
def Test_ViewChangedEventHandler():
    # See if we already have a handler
    if sc.sticky.has_key('viewchanged_event_handler'):
        # Delete the handler
        handler = sc.sticky.pop('viewchanged_event_handler', None)
        if handler:
            handler.Disable()
            handler = None
            print(' viewchanged EventHandler disabled')
    else:
        # Create handler
        handler = ViewChangedEventHandler()
        # Add the handler to the sticky dictionary so it
        # survives when the main function ends.
        sc.sticky['viewchanged_event_handler'] = handler
        print(' viewchanged EventHandler enabled')
    
################################################################################
# Check to see if this file is being executed as the 'main' python
# script instead of being used as a module by some other python script
# This allows us to use the module which ever way we want.
################################################################################
if __name__ == '__main__':
    Test_ViewChangedEventHandler()