Skip to main content
This topic has been closed for replies.
Correct answer m1b

Hi @code_seeeeeker here is a script originally by another forum user, that I adapted to use a ScriptUI Palette. Palettes are more complicated to code because you need to send messages back and forth between Illustrator and the Palette using BridgeTalk.

 

Here is the code. See if you can adapt it for your needs. Post back if you have specific questions.

- Mark

 

 

/**
 * @file Illustrator ScriptUI BridgeTalk Palette Demo.js
 *
 * Just shows a simple example of using BridgeTalk to
 * communicate between a palette window and Ilustrator.
 *
 * @author m1b and @dimitri_cas
 * https://community.adobe.com/t5/illustrator-discussions/small-javascript-that-gives-back-the-scale-and-the-rotate-of-a-selected-quot-placed-img-quot/m-p/14871091#M420851
 */
(function () {

    // check if the window already exists by using a global variable
    if (
        "undefined" !== typeof $.global.myPalette
        && null !== $.global.myPalette
    ) {
        // NOTE: while debugging, you will want to disable this part
        // because it will stop your new palette from instantiating
        // (otherwise you'll need to restart Illustrator each time!)
        $.global.myPalette.active = true;
        $.global.myPalette.show();
        return;
    }

    // create a new ScriptUI palette (modeless window)
    $.global.myPalette = new Window("palette", "Get Scale and Rotation", undefined, { resizeable: false });

    // simple UI for the demo: a text field and button
    var scaleXGroup = myPalette.add('group {orientation: "row", preferredSize:[300,-1]}'),
        scaleXlabel = scaleXGroup.add("statictext {text:'Scale X:', alignment:['left','center'] }"),
        scaleXField = scaleXGroup.add("edittext {text:'100', alignment:['left','center'], characters:10}"),
        scaleYlabel = scaleXGroup.add("statictext {text:'Scale Y:', alignment:['left','center'] }"),
        scaleYField = scaleXGroup.add("edittext {text:'100', alignment:['left','center'], characters:10}"),
        rotationField = scaleXGroup.add("edittext {text:'0', alignment:['left','center'], characters:10}"),
        udpateButton = myPalette.add("button", undefined, "Update");

    // do the BT call when the button is clicked
    udpateButton.onClick = function () {

        // a BridgeTalk message
        var bt = new BridgeTalk();
        bt.target = "illustrator";

        // convert the function to a string using toSource and invoke it, passing the textInput text
        bt.body = "(" + getScaleAndRotation.toSource() + ")();";

        // handle the result returned from Illustrator
        bt.onResult = function (response) {

            var values = response.body.split(',');

            var rounded = [
                roundStringToTwoPlaces(values[0]),
                roundStringToTwoPlaces(values[1]),
                roundStringToTwoPlaces(values[2]),
            ];

            if (undefined != rounded[0])
                scaleXField.text = rounded[0];
            if (undefined != rounded[1])
                scaleYField.text = rounded[1];
            if (undefined != rounded[2])
                rotationField.text = rounded[2];

        };

        // send the script to Illustrator
        bt.send();

    };

    // Show the palette
    myPalette.center();
    myPalette.show();

    // helper to format a number string from response
    function roundStringToTwoPlaces(n) {
        if (!isNaN(n))
            return String(Math.round(Number(n) * 100) / 100);
    };

    // function to be sent to Illustrator via BridgeTalk
    function getScaleAndRotation() {

        /*
            IMPORTANT: you must use block comments in any function
            that you will be sending via BridgeTalk, because it seems
            to evaluate the whole body as a single line, therefore
            an inline comment will nullify everything after it.
        */

        var selectedItem = app.activeDocument.selection[0];

        /* Check if something is selected */
        if (undefined == selectedItem) {
            alert("Please select an object.");
            return;
        }

        /* Check if it's a linked image (PlacedItem) or a raster image (RasterItem) */
        if (selectedItem.typename !== "PlacedItem" && selectedItem.typename !== "RasterItem") {
            alert("The selected object is not a linked or raster image.");
            return;
        }

        /* Get the transformation matrix of the selected object */
        var matrix = selectedItem.matrix;

        /* Calculate the scaling based on the transformation matrix */
        var scaleX = Math.sqrt(matrix.mValueA * matrix.mValueA + matrix.mValueB * matrix.mValueB) * 100;
        var scaleY = Math.sqrt(matrix.mValueC * matrix.mValueC + matrix.mValueD * matrix.mValueD) * 100;

        /* Calculate the rotation in degrees */
        var rotation = -Math.atan2(matrix.mValueB, matrix.mValueA) * (180 / Math.PI);

        return [scaleX, scaleY, rotation].join(',');

    };

})();

 

EDIT: I found this simpler example too:

/**
 * @file Illustrator ScriptUI BridgeTalk Palette Demo.js
 *
 * Just shows a simple example of using BridgeTalk to
 * communicate between a palette window and Ilustrator.
 *
 * @author m1b
 * @discussion https://community.adobe.com/t5/illustrator-discussions/quot-error-there-is-no-document-quot-adobe-illustrator-javascript/m-p/14875541
 */
(function () {

    // check if the window already exists by using a global variable
    if (
        "undefined" !== typeof $.global.myPalette
        && null !== $.global.myPalette
    ) {
        // NOTE: while debugging, you will want to disable this part
        // because it will stop your new palette from instantiating
        // (otherwise you'll need to restart Illustrator each time!)
        $.global.myPalette.active = true;
        $.global.myPalette.show();
        return;
    }

    // create a new ScriptUI palette (modeless window)
    $.global.myPalette = new Window("palette", "Text Setter", undefined, { resizeable: false });

    // simple UI for the demo: a text field and button
    var textInput = myPalette.add("edittext {text:'Enter your text here', alignment:['fill','fill']}");
    var feedbackText = myPalette.add("statictext {text:'', alignment:['fill','fill'],preferredSize:[300,60], properties:{multiline:true}}");
    var setButton = myPalette.add("button", undefined, "Set Text");

    // function to be sent to Illustrator via BridgeTalk
    // it sets the selected textFrame(s)' contents to `text`
    function setTextFrameContents(text) {

        if (0 === app.activeDocument.selection.length)
            return alert('Please select a text frame and try again.');

        var items = app.activeDocument.selection,
            contents = [];

        for (var i = 0; i < items.length; i++) {

            if ('TextFrame' === items[i].constructor.name) {
                contents.push(items[i].contents);
                items[i].contents = text;
            }

        }

        return contents.join(' + ');

    };

    // do the BT call when the button is clicked
    setButton.onClick = function () {

        // a BridgeTalk message
        var bt = new BridgeTalk();
        bt.target = "illustrator";

        // convert the function to a string using toSource and invoke it, passing the textInput text
        bt.body = "(" + setTextFrameContents.toSource() + ")('" + textInput.text + "');";

        // handle the result returned from Illustrator
        bt.onResult = function (response) {
            feedbackText.text = 'Old text: ' + (response.body || '');
        };

        // send the script to Illustrator
        bt.send();

    };

    // Show the palette
    myPalette.center();
    myPalette.show();

})();

 

3 replies

Participating Frequently
October 17, 2024

Hi,

Connection issue: When using ScriptUI palette windows, you may sometimes be unable to access the active document in Illustrator. This is because the script window loses its connection to the active document.

See the following discussion.

Is ScriptUI in Illustrator broken? - Adobe Community - 13640854

m1b
Community Expert
m1bCommunity ExpertCorrect answer
Community Expert
October 16, 2024

Hi @code_seeeeeker here is a script originally by another forum user, that I adapted to use a ScriptUI Palette. Palettes are more complicated to code because you need to send messages back and forth between Illustrator and the Palette using BridgeTalk.

 

Here is the code. See if you can adapt it for your needs. Post back if you have specific questions.

- Mark

 

 

/**
 * @file Illustrator ScriptUI BridgeTalk Palette Demo.js
 *
 * Just shows a simple example of using BridgeTalk to
 * communicate between a palette window and Ilustrator.
 *
 * @author m1b and @dimitri_cas
 * https://community.adobe.com/t5/illustrator-discussions/small-javascript-that-gives-back-the-scale-and-the-rotate-of-a-selected-quot-placed-img-quot/m-p/14871091#M420851
 */
(function () {

    // check if the window already exists by using a global variable
    if (
        "undefined" !== typeof $.global.myPalette
        && null !== $.global.myPalette
    ) {
        // NOTE: while debugging, you will want to disable this part
        // because it will stop your new palette from instantiating
        // (otherwise you'll need to restart Illustrator each time!)
        $.global.myPalette.active = true;
        $.global.myPalette.show();
        return;
    }

    // create a new ScriptUI palette (modeless window)
    $.global.myPalette = new Window("palette", "Get Scale and Rotation", undefined, { resizeable: false });

    // simple UI for the demo: a text field and button
    var scaleXGroup = myPalette.add('group {orientation: "row", preferredSize:[300,-1]}'),
        scaleXlabel = scaleXGroup.add("statictext {text:'Scale X:', alignment:['left','center'] }"),
        scaleXField = scaleXGroup.add("edittext {text:'100', alignment:['left','center'], characters:10}"),
        scaleYlabel = scaleXGroup.add("statictext {text:'Scale Y:', alignment:['left','center'] }"),
        scaleYField = scaleXGroup.add("edittext {text:'100', alignment:['left','center'], characters:10}"),
        rotationField = scaleXGroup.add("edittext {text:'0', alignment:['left','center'], characters:10}"),
        udpateButton = myPalette.add("button", undefined, "Update");

    // do the BT call when the button is clicked
    udpateButton.onClick = function () {

        // a BridgeTalk message
        var bt = new BridgeTalk();
        bt.target = "illustrator";

        // convert the function to a string using toSource and invoke it, passing the textInput text
        bt.body = "(" + getScaleAndRotation.toSource() + ")();";

        // handle the result returned from Illustrator
        bt.onResult = function (response) {

            var values = response.body.split(',');

            var rounded = [
                roundStringToTwoPlaces(values[0]),
                roundStringToTwoPlaces(values[1]),
                roundStringToTwoPlaces(values[2]),
            ];

            if (undefined != rounded[0])
                scaleXField.text = rounded[0];
            if (undefined != rounded[1])
                scaleYField.text = rounded[1];
            if (undefined != rounded[2])
                rotationField.text = rounded[2];

        };

        // send the script to Illustrator
        bt.send();

    };

    // Show the palette
    myPalette.center();
    myPalette.show();

    // helper to format a number string from response
    function roundStringToTwoPlaces(n) {
        if (!isNaN(n))
            return String(Math.round(Number(n) * 100) / 100);
    };

    // function to be sent to Illustrator via BridgeTalk
    function getScaleAndRotation() {

        /*
            IMPORTANT: you must use block comments in any function
            that you will be sending via BridgeTalk, because it seems
            to evaluate the whole body as a single line, therefore
            an inline comment will nullify everything after it.
        */

        var selectedItem = app.activeDocument.selection[0];

        /* Check if something is selected */
        if (undefined == selectedItem) {
            alert("Please select an object.");
            return;
        }

        /* Check if it's a linked image (PlacedItem) or a raster image (RasterItem) */
        if (selectedItem.typename !== "PlacedItem" && selectedItem.typename !== "RasterItem") {
            alert("The selected object is not a linked or raster image.");
            return;
        }

        /* Get the transformation matrix of the selected object */
        var matrix = selectedItem.matrix;

        /* Calculate the scaling based on the transformation matrix */
        var scaleX = Math.sqrt(matrix.mValueA * matrix.mValueA + matrix.mValueB * matrix.mValueB) * 100;
        var scaleY = Math.sqrt(matrix.mValueC * matrix.mValueC + matrix.mValueD * matrix.mValueD) * 100;

        /* Calculate the rotation in degrees */
        var rotation = -Math.atan2(matrix.mValueB, matrix.mValueA) * (180 / Math.PI);

        return [scaleX, scaleY, rotation].join(',');

    };

})();

 

EDIT: I found this simpler example too:

/**
 * @file Illustrator ScriptUI BridgeTalk Palette Demo.js
 *
 * Just shows a simple example of using BridgeTalk to
 * communicate between a palette window and Ilustrator.
 *
 * @author m1b
 * @discussion https://community.adobe.com/t5/illustrator-discussions/quot-error-there-is-no-document-quot-adobe-illustrator-javascript/m-p/14875541
 */
(function () {

    // check if the window already exists by using a global variable
    if (
        "undefined" !== typeof $.global.myPalette
        && null !== $.global.myPalette
    ) {
        // NOTE: while debugging, you will want to disable this part
        // because it will stop your new palette from instantiating
        // (otherwise you'll need to restart Illustrator each time!)
        $.global.myPalette.active = true;
        $.global.myPalette.show();
        return;
    }

    // create a new ScriptUI palette (modeless window)
    $.global.myPalette = new Window("palette", "Text Setter", undefined, { resizeable: false });

    // simple UI for the demo: a text field and button
    var textInput = myPalette.add("edittext {text:'Enter your text here', alignment:['fill','fill']}");
    var feedbackText = myPalette.add("statictext {text:'', alignment:['fill','fill'],preferredSize:[300,60], properties:{multiline:true}}");
    var setButton = myPalette.add("button", undefined, "Set Text");

    // function to be sent to Illustrator via BridgeTalk
    // it sets the selected textFrame(s)' contents to `text`
    function setTextFrameContents(text) {

        if (0 === app.activeDocument.selection.length)
            return alert('Please select a text frame and try again.');

        var items = app.activeDocument.selection,
            contents = [];

        for (var i = 0; i < items.length; i++) {

            if ('TextFrame' === items[i].constructor.name) {
                contents.push(items[i].contents);
                items[i].contents = text;
            }

        }

        return contents.join(' + ');

    };

    // do the BT call when the button is clicked
    setButton.onClick = function () {

        // a BridgeTalk message
        var bt = new BridgeTalk();
        bt.target = "illustrator";

        // convert the function to a string using toSource and invoke it, passing the textInput text
        bt.body = "(" + setTextFrameContents.toSource() + ")('" + textInput.text + "');";

        // handle the result returned from Illustrator
        bt.onResult = function (response) {
            feedbackText.text = 'Old text: ' + (response.body || '');
        };

        // send the script to Illustrator
        bt.send();

    };

    // Show the palette
    myPalette.center();
    myPalette.show();

})();

 

Inspiring
October 16, 2024

Thanks, m1b, I'll try this and let you know if it works.

RobOctopus
Inspiring
October 15, 2024

didn't read the rest of the script, but no where is the window declared a palette

var myWindow = new Window(
  "dialog",
  "Custom Checks & Fixes - Illustrator, v1.0",
  undefined,
  { resizeable: true }
);
/* change to */
var myWindow = new Window(
  "palette",
  "Custom Checks & Fixes - Illustrator, v1.0",
  undefined,
  { resizeable: true }
);

 

Inspiring
October 16, 2024

Thanks, RobOctopus, I already tried changing the 'Dialog' to 'Palette', but as I said, some scripts stopped working then.