<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: Palette to get data from python keeps looping in Fusion API and Scripts Forum</title>
    <link>https://forums.autodesk.com/t5/fusion-api-and-scripts-forum/palette-to-get-data-from-python-keeps-looping/m-p/12753924#M1482</link>
    <description>&lt;P&gt;&lt;a href="https://forums.autodesk.com/t5/user/viewprofilepage/user-id/6486599"&gt;@info83PHN&lt;/a&gt;&amp;nbsp;no problem &lt;span class="lia-unicode-emoji" title=":slightly_smiling_face:"&gt;🙂&lt;/span&gt;&lt;BR /&gt;&lt;BR /&gt;Also if you want to display the palette right away when the add-in is started, you can execute its command definition which will simulate user clicking the button.&lt;BR /&gt;&lt;BR /&gt;Add this at the end of your run method:&lt;/P&gt;&lt;LI-CODE lang="general"&gt;showPaletteCmdDef.execute() &lt;/LI-CODE&gt;&lt;P&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;/P&gt;</description>
    <pubDate>Sun, 05 May 2024 18:00:50 GMT</pubDate>
    <dc:creator>j4n.vokurka</dc:creator>
    <dc:date>2024-05-05T18:00:50Z</dc:date>
    <item>
      <title>Palette to get data from python keeps looping</title>
      <link>https://forums.autodesk.com/t5/fusion-api-and-scripts-forum/palette-to-get-data-from-python-keeps-looping/m-p/12747655#M1479</link>
      <description>&lt;P&gt;Trying to modified the palette / python code to :&lt;/P&gt;&lt;P&gt;1. Click the palette html button to activate the python script&lt;/P&gt;&lt;P&gt;2. python script to get some data from the Components&lt;/P&gt;&lt;P&gt;3. python feed the data back to the palette&lt;/P&gt;&lt;P&gt;4. palette to display the returned message.&lt;/P&gt;&lt;P&gt;added bonus would be to have the palette window display when the add-on is run.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Problem - palette displays, but when clicking on the button, it loops with the number returned from python updating all the time.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;I stripped out the code for the "&lt;SPAN&gt;Send Info to HTML" add-on dropdown menu, as I want the python script to return the required info once the palette html button is clicked.&lt;/SPAN&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;The palette code is :&lt;/P&gt;&lt;LI-CODE lang="general"&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
    &amp;lt;head&amp;gt;
    &amp;lt;/head&amp;gt;
    &amp;lt;body&amp;gt;
        &amp;lt;p&amp;gt;Click the button below to send data to Fusion.&amp;lt;/p&amp;gt;
        &amp;lt;button type='button' onclick='sendInfoToFusion()'&amp;gt;Click to send info to Fusion&amp;lt;/button&amp;gt; 
        &amp;lt;p id='p1'&amp;gt;Ready to run.&amp;lt;/p&amp;gt;
        &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;
	
    &amp;lt;/body&amp;gt;
    &amp;lt;script&amp;gt;
        function sendInfoToFusion(){

			// arg1 = 'ReadVolumes' will tell the python script which data I want returned to display on the palette.

            var args = {
                arg1 : "ReadVolumes",
            };
            adsk.fusionSendData('send', JSON.stringify(args));
        }
        
        window.fusionJavaScriptHandler = {handle: function(action, data){
            try {
                if (action == 'send') {
					document.getElementById('p1').innerHTML = data;
				}
				else if (action == 'debugger') {
                    debugger;
				}
				else {
					return 'Unexpected command type: ' + action;
                }
            } catch (e) {
                console.log(e);
                console.log('exception caught with command: ' + action + ', data: ' + data);
            }
            return 'OK';
        }};
    &amp;lt;/script&amp;gt;
&amp;lt;/html&amp;gt;&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;The python code is :&lt;/P&gt;&lt;LI-CODE lang="python"&gt;import adsk.core, adsk.fusion, adsk.cam, traceback
import json

# global set of event handlers to keep them referenced for the duration of the command
handlers = []
_app = adsk.core.Application.cast(None)
_ui = adsk.core.UserInterface.cast(None)
num = 0


# Event handler for the commandExecuted event - show palette, create handlers

class ShowPaletteCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            # Create and display the palette.
            palette = _ui.palettes.itemById('myPalette')
            if not palette:
                palette = _ui.palettes.add('myPalette', 'My Palette', 'palette.html', True, True, True, 300, 200)

                # Dock the palette to the right side of Fusion window.
                palette.dockingState = adsk.core.PaletteDockingStates.PaletteDockStateRight
    
                # Add handler to HTMLEvent of the palette.
                onHTMLEvent = MyHTMLEventHandler()
                palette.incomingFromHTML.add(onHTMLEvent)   
                handlers.append(onHTMLEvent)
    
                # Add handler to CloseEvent of the palette.
                onClosed = MyCloseEventHandler()
                palette.closed.add(onClosed)
                handlers.append(onClosed)   
            else:
                palette.isVisible = True                               
        except:
            _ui.messageBox('Command executed failed: {}'.format(traceback.format_exc()))


# Event handler for the commandCreated event.
class ShowPaletteCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()              
    def notify(self, args):
        try:
            command = args.command
            onExecute = ShowPaletteCommandExecuteHandler()
            command.execute.add(onExecute)
            handlers.append(onExecute)                                     
        except:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))     


# Event handler for the commandExecuted event.
class SendInfoCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            # Send information to the palette. This will trigger an event in the javascript
            # within the html so that it can be handled.
            palette = _ui.palettes.itemById('myPalette')
            if palette:
                global num
                num += 1
                palette.sendInfoToHTML('send', 'Message has been sent ' + str(num) + ' times')                        
        except:
            _ui.messageBox('Command executed failed: {}'.format(traceback.format_exc()))


# Event handler for the commandCreated event.
class SendInfoCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()              
    def notify(self, args):
        try:
            command = args.command
            onExecute = SendInfoCommandExecuteHandler()
            command.execute.add(onExecute)
            handlers.append(onExecute)                                     
        except:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))     


# Event handler for the palette close event.
class MyCloseEventHandler(adsk.core.UserInterfaceGeneralEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            _ui.messageBox('Close button is clicked.') 
        except:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


# Event handler for the palette HTML event.                
class MyHTMLEventHandler(adsk.core.HTMLEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            global num
            num += 1
            palette = _ui.palettes.itemById('myPalette')
            palette.sendInfoToHTML('send', 'It has been sent ' + str(num) + ' times')

        except:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))           

                
def run(context):
    try:
        global _ui, _app
        _app = adsk.core.Application.get()
        _ui  = _app.userInterface
        
        # Add a command that displays the panel.
        showPaletteCmdDef = _ui.commandDefinitions.itemById('showPalette')
        if not showPaletteCmdDef:
            showPaletteCmdDef = _ui.commandDefinitions.addButtonDefinition('showPalette', 'Show Custom Palette', 'Show the custom palette', '')
            # Connect to Command Created event.
            onCommandCreated = ShowPaletteCommandCreatedHandler()
            showPaletteCmdDef.commandCreated.add(onCommandCreated)
            handlers.append(onCommandCreated)
        
        panel = _ui.allToolbarPanels.itemById('SolidScriptsAddinsPanel')
        cntrl = panel.controls.itemById('showPalette')
        if not cntrl:
            panel.controls.addCommand(showPaletteCmdDef)
    except:
        if _ui:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


def stop(context):
    try:        
        # Delete the palette created by this add-in.
        palette = _ui.palettes.itemById('myPalette')
        if palette:
            palette.deleteMe()
        # Delete controls and associated command definitions created by this add-ins
        panel = _ui.allToolbarPanels.itemById('SolidScriptsAddinsPanel')
        cmd = panel.controls.itemById('showPalette')
        if cmd:
            cmd.deleteMe()
        cmdDef = _ui.commandDefinitions.itemById('showPalette')
        if cmdDef:
            cmdDef.deleteMe() 
    except:
        if _ui:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Thu, 02 May 2024 08:01:34 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/fusion-api-and-scripts-forum/palette-to-get-data-from-python-keeps-looping/m-p/12747655#M1479</guid>
      <dc:creator>info83PHN</dc:creator>
      <dc:date>2024-05-02T08:01:34Z</dc:date>
    </item>
    <item>
      <title>Re: Palette to get data from python keeps looping</title>
      <link>https://forums.autodesk.com/t5/fusion-api-and-scripts-forum/palette-to-get-data-from-python-keeps-looping/m-p/12753682#M1480</link>
      <description>&lt;P&gt;That occurs because you are perpetually calling the&amp;nbsp;&lt;SPAN&gt;sendInfoToHTML method.&amp;nbsp;&lt;BR /&gt;&lt;BR /&gt;Short explanation: button is pressed in palette =&amp;gt;&amp;nbsp;&lt;/SPAN&gt;&lt;SPAN&gt;incomingFromHTML is triggerred =&amp;gt; &lt;/SPAN&gt;&lt;SPAN&gt;sendInfoToHTML() is used in handler =&amp;gt;&amp;nbsp;&lt;SPAN&gt;incomingFromHTML is triggerred again - cycle is born.&lt;BR /&gt;&lt;BR /&gt;To tackle this you have to check the json data you receive from the palette and determine what has happened and if you want to react to that or not.&lt;BR /&gt;&lt;BR /&gt;I have adjusted the python and javascript code because there are a lot of handlers I think you don't need right now. The logic you need starts on line 63.&lt;BR /&gt;&lt;BR /&gt;palette:&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="general"&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
    &amp;lt;head&amp;gt;
    &amp;lt;/head&amp;gt;
    &amp;lt;body&amp;gt;
        &amp;lt;p&amp;gt;Click the button below to send data to Fusion.&amp;lt;/p&amp;gt;
        &amp;lt;button type='button' onclick='sendInfoToFusion()'&amp;gt;Click to send info to Fusion&amp;lt;/button&amp;gt; 
        &amp;lt;p id='p1'&amp;gt;Ready to run.&amp;lt;/p&amp;gt;
        &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;
	
    &amp;lt;/body&amp;gt;
    &amp;lt;script&amp;gt;
        function sendInfoToFusion(){

			// arg1 = 'ReadVolumes' will tell the python script which data I want returned to display on the palette.

            var args = {
                data : "ButtonPressed",
            };
            adsk.fusionSendData('send', JSON.stringify(args));
        }
        
        window.fusionJavaScriptHandler = {handle: function(action, data){
            try {
                if (action == 'send') {
					document.getElementById('p1').innerHTML = data;
				}
				else if (action == 'debugger') {
                    debugger;
				}
				else {
					return 'Unexpected command type: ' + action;
                }
            } catch (e) {
                console.log(e);
                console.log('exception caught with command: ' + action + ', data: ' + data);
            }
            return 'OK';
        }};
    &amp;lt;/script&amp;gt;
&amp;lt;/html&amp;gt;&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;SPAN&gt;&lt;SPAN&gt;&lt;BR /&gt;python:&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="general"&gt;import adsk.core, adsk.fusion, adsk.cam, traceback
import json

# global set of event handlers to keep them referenced for the duration of the command
handlers = []
_app = adsk.core.Application.cast(None)
_ui = adsk.core.UserInterface.cast(None)
num = 0


# Event handler for the commandCreated event.
class ShowPaletteCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()              
    def notify(self, args):
        try:
            command = args.command
            onExecute = ShowPaletteCommandExecuteHandler()
            command.execute.add(onExecute)
            handlers.append(onExecute)                                     
        except:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))     


# Event handler for the commandExecuted event - show palette, create handlers
class ShowPaletteCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            # Create and display the palette.
            palette = _ui.palettes.itemById('myPalette')
            if not palette:
                palette = _ui.palettes.add('myPalette', 'My Palette', 'palette.html', True, True, True, 300, 200)

                # Dock the palette to the right side of Fusion window.
                palette.dockingState = adsk.core.PaletteDockingStates.PaletteDockStateRight
    
                # Add handler to HTMLEvent of the palette.
                onHTMLEvent = MyHTMLEventHandler()
                palette.incomingFromHTML.add(onHTMLEvent)   
                handlers.append(onHTMLEvent)
    
                # Add handler to CloseEvent of the palette.
                onClosed = MyCloseEventHandler()
                palette.closed.add(onClosed)
                handlers.append(onClosed)   
            else:
                palette.isVisible = True                               
        except:
            _ui.messageBox('Command executed failed: {}'.format(traceback.format_exc()))



# Event handler for the palette HTML event.                
class MyHTMLEventHandler(adsk.core.HTMLEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            global num            

            htmlArgs = adsk.core.HTMLEventArgs.cast(args)
            data = json.loads(htmlArgs.data)   
             
            if (data['data'] == "ButtonPressed"):
                num += 1  # call your script here and retreive needed component info
                palette = _ui.palettes.itemById('myPalette')
                palette.sendInfoToHTML('send', 'It has been sent ' + str(num) + ' times')          
            elif (data['data'] == "OK"): 
                return      
            else:
                # some error
                return            

        except:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc())) 
           

# Event handler for the palette close event.
class MyCloseEventHandler(adsk.core.UserInterfaceGeneralEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            _ui.messageBox('Close button is clicked.') 
        except:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
    
def run(context):
    try:
        global _ui, _app
        _app = adsk.core.Application.get()
        _ui  = _app.userInterface
        
        # Add a command that displays the panel.
        showPaletteCmdDef = _ui.commandDefinitions.itemById('showPalette')
        if not showPaletteCmdDef:
            showPaletteCmdDef = _ui.commandDefinitions.addButtonDefinition('showPalette', 'Show Custom Palette', 'Show the custom palette', '')

            # Connect to Command Created event.
            onCommandCreated = ShowPaletteCommandCreatedHandler()
            showPaletteCmdDef.commandCreated.add(onCommandCreated)
            handlers.append(onCommandCreated)
        
        panel = _ui.allToolbarPanels.itemById('SolidScriptsAddinsPanel')
        cntrl = panel.controls.itemById('showPalette')
        if not cntrl:
            panel.controls.addCommand(showPaletteCmdDef)
    except:
        if _ui:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


def stop(context):
    try:        
        # Delete the palette created by this add-in.
        palette = _ui.palettes.itemById('myPalette')
        if palette:
            palette.deleteMe()

        # Delete controls and associated command definitions created by this add-ins
        panel = _ui.allToolbarPanels.itemById('SolidScriptsAddinsPanel')
        cmd = panel.controls.itemById('showPalette')
        if cmd:
            cmd.deleteMe()
        cmdDef = _ui.commandDefinitions.itemById('showPalette')
        if cmdDef:
            cmdDef.deleteMe() 
    except:
        if _ui:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;BR /&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Sun, 05 May 2024 13:36:57 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/fusion-api-and-scripts-forum/palette-to-get-data-from-python-keeps-looping/m-p/12753682#M1480</guid>
      <dc:creator>j4n.vokurka</dc:creator>
      <dc:date>2024-05-05T13:36:57Z</dc:date>
    </item>
    <item>
      <title>Re: Palette to get data from python keeps looping</title>
      <link>https://forums.autodesk.com/t5/fusion-api-and-scripts-forum/palette-to-get-data-from-python-keeps-looping/m-p/12753738#M1481</link>
      <description>&lt;P&gt;&lt;a href="https://forums.autodesk.com/t5/user/viewprofilepage/user-id/13214108"&gt;@j4n.vokurka&lt;/a&gt;&amp;nbsp;my sincere Thanks. I just could not understand why it was looping. Your solution worked perfectly. Thank You&lt;/P&gt;</description>
      <pubDate>Sun, 05 May 2024 14:37:47 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/fusion-api-and-scripts-forum/palette-to-get-data-from-python-keeps-looping/m-p/12753738#M1481</guid>
      <dc:creator>info83PHN</dc:creator>
      <dc:date>2024-05-05T14:37:47Z</dc:date>
    </item>
    <item>
      <title>Re: Palette to get data from python keeps looping</title>
      <link>https://forums.autodesk.com/t5/fusion-api-and-scripts-forum/palette-to-get-data-from-python-keeps-looping/m-p/12753924#M1482</link>
      <description>&lt;P&gt;&lt;a href="https://forums.autodesk.com/t5/user/viewprofilepage/user-id/6486599"&gt;@info83PHN&lt;/a&gt;&amp;nbsp;no problem &lt;span class="lia-unicode-emoji" title=":slightly_smiling_face:"&gt;🙂&lt;/span&gt;&lt;BR /&gt;&lt;BR /&gt;Also if you want to display the palette right away when the add-in is started, you can execute its command definition which will simulate user clicking the button.&lt;BR /&gt;&lt;BR /&gt;Add this at the end of your run method:&lt;/P&gt;&lt;LI-CODE lang="general"&gt;showPaletteCmdDef.execute() &lt;/LI-CODE&gt;&lt;P&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;/P&gt;</description>
      <pubDate>Sun, 05 May 2024 18:00:50 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/fusion-api-and-scripts-forum/palette-to-get-data-from-python-keeps-looping/m-p/12753924#M1482</guid>
      <dc:creator>j4n.vokurka</dc:creator>
      <dc:date>2024-05-05T18:00:50Z</dc:date>
    </item>
    <item>
      <title>Re: Palette to get data from python keeps looping</title>
      <link>https://forums.autodesk.com/t5/fusion-api-and-scripts-forum/palette-to-get-data-from-python-keeps-looping/m-p/12753932#M1483</link>
      <description>&lt;P&gt;&amp;nbsp;PERFECT - Thank You - I was going to make another post for that as I could not find that solution either.&lt;/P&gt;</description>
      <pubDate>Sun, 05 May 2024 18:07:45 GMT</pubDate>
      <guid>https://forums.autodesk.com/t5/fusion-api-and-scripts-forum/palette-to-get-data-from-python-keeps-looping/m-p/12753932#M1483</guid>
      <dc:creator>info83PHN</dc:creator>
      <dc:date>2024-05-05T18:07:45Z</dc:date>
    </item>
  </channel>
</rss>

