Jump to content

Recommended Posts

Posted · How can a plugin add a custom setting category icon?

I've written a plugin for Cura that creates a new setting category and adds a number of special settings to it. Everything is functioning as intended (after a lot of trial and error) but I haven't figured out how to get Cura to read a custom category icon from the plugin folder.

 

The only way I've been able to get it working is by including a Resources search path, adding the icon to the appropriate folder in a local themes directory and creating a theme.json that just inherits a default theme. The only new file in the directory is my icon but Cura doesn't seem to want to read it without using a new theme. This isn't really a practical solution just to get an icon working. Of course adding the icon directly to the master files works but that's not a good idea either.

 

The settings properties documentation indicates the "icon" property accepts a file path but if that's still true I can't figure out what it's looking for. There's also this comment in the Themes file under getIcon() indicating there's fallback behavior to load icons from a plugin folder.

 

I'd very much appreciate if someone could point me in the right direction. Hopefully there's a simple solution I've missed. Thanks! 

  • Link to post
    Share on other sites

    Posted · How can a plugin add a custom setting category icon?

    Welcome to the club 🙂

     

    I don't know if it's the solution. But I solved my issue with :

    toolItem: UM.ColorImage
      {
        source: Qt.resolvedUrl("type_custom.svg")
        color: UM.Theme.getColor("icon")
      }

    could be a beggining of solution for you

  • Link to post
    Share on other sites

    Posted · How can a plugin add a custom setting category icon?

    Thanks for the reply Cuq! I actually saw your post but since my plugin doesn't need to use qml I don't believe I could really solve it this way without adding more complexity. I did initially attempt to use QUrl but that was pointless. I'm fairly confident now there's no way to use any file path for the setting parameter because when the theme loads it only obtains icons after confirming the existence of a theme.json file. Then it simply looks for an icons folder using that same path.

     

    However... after spending entirely too much time on this and nearly giving up, I found a solution!

     

    I'll try to break it down for the sake of the next person...

     

    Basically, there must be a folder in the plugin directory with a 'theme.json' and an '/icons/default' directory containing any new icons. I'm using other resources so I simply added a 'themes' folder to a 'resources' directory.

     

    The theme.json can contain any necessary data but must at least include metadata with an "inherits" property. Any name is fine because it'll immediately get changed anyway. Stripping it down this much does ensure Cura will throw an error if it's ever used as a normal theme file.

     

    {
        "metadata": {
            "inherits": "cura-light"
        }
    }

     

    Here's my proof of concept to get it working:

     

    # Directory containing theme.json: /resources/themes
    # Directory containing icons: /resources/themes/icons/default
    # "icon" param must be the filename without the extension (e.g. Awesome.svg = "Awesome").
    
    # Additional module requried to force a theme to load from a path
    from UM.Qt.Bindings.Theme import Theme
    
            # Path to 'resources' dir
            resource_path = os.path.join(os.path.dirname(__file__), 'resources')
            self._updateTheme(resource_path)
            
        def _updateTheme(self, theme_path: str) -> None:
            application = CuraApplication.getInstance()
            preferences = application.getPreferences()
    
            # Get name of current theme or set to default if none exist
            preferences.addPreference('general/theme', application.default_theme)
            current_theme_name = preferences.getValue('general/theme')
    
            # Path to 'theme.json'
            resource_theme = os.path.join(theme_path, 'themes', 'theme.json')
    
            with open(resource_theme) as f:
                metadata = json.load(f) # Empty theme used only for metadata
                metadata['metadata']['inherits'] = current_theme_name
            with open(resource_theme, 'w') as f:
                json.dump(metadata, f, indent = 4) # Rewrite with current theme to inherit
    
            # Force load inherited theme so Cura will include local resources
            Theme.getInstance().load(path = os.path.join(theme_path, 'themes'))

     

    The most critical part being the last line which forces the local theme to load. I assume it wasn't intended to be used this way, it would be nice if Cura just honored the items in a plugin's resource path .

     

    This should allow a user to even continue using a custom theme without issue. It could certainly be improved and the theme.json file could even get created by the function so there's no chance of getting deleted.

     

    This is usually about the time I realize fieldOfView had a far more efficient solution to my problem but unless that happens, perhaps the setting parameter documentation should be updated :)

  • Link to post
    Share on other sites

    Posted (edited) · How can a plugin add a custom setting category icon?
    37 minutes ago, JJFX said:

    This is usually about the time I realize fieldOfView had a far more efficient solution to my problem

    Challenge accepted.

     

    I think I would personally go the route of injecting the icon in the _icons dictionary of the theme instance. The following code is untested.

    from UM.Application import Application
    
    theme = Application.getInstance().getTheme()
    detail_level = "default"
    icon_name = "my_category"
    icon_path = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        "icons",
        "my_category.svg"
    )
    
    theme._icons[detail_level][icon_name] = QUrl.fromLocalFile(icon_path)

    This is also "dirty" (since it accesses a "private" variable), but I think creating and self-editing a stub theme file is dirtier. And if your plugin adds settings, it is probably already accessing "private" variables.

     

    I'll admit that your method is creative 😉

    Edited by ahoeben
  • Link to post
    Share on other sites

    Posted · How can a plugin add a custom setting category icon?
    Quote

    Challenge accepted.

     

    Haha! What, was that your bat signal?! I mention your name, go grab a snack and by the time I get back you've already completely put my hours of work to shame.

     

    However, using Application threw an error so I did need to fix something! This works and it's a painfully easy solution... because of course it is!

     

        from PyQt6.QtCore import QUrl # Use PyQt5 for older Cura versions
        from UM.Qt.Bindings.Theme import Theme
    
        theme = Theme.getInstance()
        detail_level = "default"
        icon_name = "test"
    
        icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons", "test.svg")
    
        theme._icons[detail_level][icon_name] = QUrl.fromLocalFile(icon_path)

     

     

    Quote

    This is also "dirty" (since it accesses a "private" variable), but I think creating a stub theme file and changing a user preference is dirtier. And if your plugin adds settings, it is probably already accessing "private" variables.

     

    A bit of a moot point now but I thought my solution was safe specifically because it wasn't changing the user's preference. It should only be reading the existing theme name so it can inherit it through my 'stub' theme file. The only preference it could set was to the default theme if there wasn't an active theme anyway.

     

    Thanks for the help!

  • Link to post
    Share on other sites

    Create an account or sign in to comment

    You need to be a member in order to leave a comment

    Create an account

    Sign up for a new account in our community. It's easy!

    Register a new account

    Sign in

    Already have an account? Sign in here.

    Sign In Now
    • Our picks

      • UltiMaker Cura 5.9 stable released!
        Here comes Cura 5.9 and in this stable release we have lots of material and printer profiles for UltiMaker printers, including the newly released Sketch Sprint. Additionally, scarf seams have been introduced alongside even more print settings and improvements.  Check out the rest of this article to find out the details on all of that and more
          • Like
        • 5 replies
      • Introducing the UltiMaker Factor 4
        We are happy to announce the next evolution in the UltiMaker 3D printer lineup: the UltiMaker Factor 4 industrial-grade 3D printer, designed to take manufacturing to new levels of efficiency and reliability. Factor 4 is an end-to-end 3D printing solution for light industrial applications
          • Heart
          • Thanks
          • Like
        • 4 replies
    ×
    ×
    • Create New...