• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

What is the best Practices to Call Palette from another Dialog?

Enthusiast ,
Jul 03, 2021 Jul 03, 2021

Copy link to clipboard

Copied

Hi Experts,

its first time that i need to call dialog from another dialog! , i am begineer in coding , the main script (dialog)  (have a button user must click to enter options!), something like this :

Button2.onClick = function() {Options();};
function Options() {
CallTheQueryGManager();
}

I put all the other dialog (its actually a palette)  in a big function? something like that :

function CallTheQueryGManager() {
#targetengine "session";
var gqmanager = new Window ("palette");

but when calling from new Windows ("dialog") to ("palette"), the palette window is freezed not accessble until i close the dialog!, also the script act so strange!, executing itself  without click on buttons! and not responding if i hit other buttons! , whats wrong i did? or what best practices for this? i am using indesign 2021 - 16.2.1 x64 - on windows, i am also using ExtedScript Toolkit for writing the scripts, and also i tried to make the both dialogs (palette) but it not working well (not updating the execution!) i have to close and reopen the script!,  please advice me what to do to connect well betweeen dialogs with no errors?, and thanks in advance.

Best
Mohammad Hasanin
TOPICS
Scripting

Views

717

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 2 Correct answers

Guide , Jul 05, 2021 Jul 05, 2021

Hi @M.Hasanin 

 

Looks like an interesting project. I don't understand why you need a distinct (sub)palette. All could probably be done from within a single UI, no?

 

A crucial fact about the palette type (versus dialog) is that any instance of such Window object must have a persistent reference in memory. Having a targetengine directive is a requirement, but you also need to store the result of new Window('palette', etc) in a non-local variable. Otherwise the palette is automatically destroyed when

...

Votes

Translate

Translate
Guide , Jul 05, 2021 Jul 05, 2021

As code formatting & highlighting is horrible in Adobe forums, here is a better view on GH Gist:

InteractingPalettesExample.jsx 

 

Best,

Marc

Votes

Translate

Translate
Community Expert ,
Jul 03, 2021 Jul 03, 2021

Copy link to clipboard

Copied

You will need to close the dialog during the onClick() with dialogBox.close();

 

You can reopen it with dialogBox.show() after executing whatever you're doing in the palette if you pass the Dialog object to your Options function. 

 

Can't tell you why other buttons aren't behaving correctly without seeing the code. 

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Enthusiast ,
Jul 03, 2021 Jul 03, 2021

Copy link to clipboard

Copied

Thanks a lot for your reply, here is the complete code, please note that in the past this is was Dialog not palette, i mean the main window and also everytime clicking the find grep button it was reset the operation and find and apply new object styles and removing the old one, now after converting this to palette it only work once and i have to select (none) object style again to remove the past operation!, also undo function not working!.

 

 

 

//Find Text Using GREP and Apply Object Styles with UI to Containers - Version 2.02
//Created By : Mohammad Ibrahim Hasanain - July 2021
//Credits to : Manan Joshi (Helped Me in GQM fixing issues in Saving and Loading Txt File)
//--------------------------------------------------------------------------------------------------------------------------

//Main();
//Activate Un-Doable for this Script
//app.doScript(Main, undefined, undefined, UndoModes.ENTIRE_SCRIPT,"Assigned GREP Results Container");

function Main() {
	// Check to see whether any InDesign documents are open.
	// If no documents are open, display an error message.
	if (app.documents.length > 0) {
		var myDoc = app.activeDocument;
		 doAssignGREPtoOS();
		//alert("Finished!");
	}
	else {
		// No documents are open, so display an error message.
		alert("No InDesign documents are open. Please open a document and try again.");
	}
}

//Get ObjectStyles
var myObjStylesList = app.activeDocument.objectStyles.everyItem().name

//Making Windows
//var w = new Window ("dialog");
//var w = new Window ("dialog");
#targetengine "session";
var w = new Window ("palette");
var gqmanager = new Window ("palette");
//var gqmanager = new Window ("dialog");
//Calling the GREP Query Manager outside the Function
w.text = "Assigned GREP Results Container to Object Styles - Version 2.02";
w.preferredSize.width = 600;
w.alignChildren = ["left","top"];  //"left";
w.orientation =  "column"; //"row"; 
w.spacing = 10; 
w.margins = 16; 

//Document Object Styles Dropdown List--Source
var myInputGroup1 = w.add ("group");

//Adding Text Box :
myInputGroup1.add ("statictext", undefined, "GREP :");
myInputGroup1.alignment = "left";
var myGREPString = myInputGroup1.add ("edittext", undefined, "");
myGREPString.characters = 20;
myGREPString.enabled = true;
myGREPString.preferredSize.width = 350; 

//Adding the Object Styles Found
myInputGroup1.add ("statictext", undefined, "Object styles :");
myInputGroup1.alignment = "left";
var myDropdown1 = myInputGroup1.add ("dropdownlist", undefined, myObjStylesList);
myDropdown1.selection = 0 ;
    
//OK and Cancel
//Adding OK Button
var myButtonGroup = w.add ("group");
myButtonGroup.alignment = "center";
var Button0 = myButtonGroup.add ("button", undefined, "Find GREP and Apply Obejct Style");
var Button1 = myButtonGroup.add ("button", undefined, "Exit");
var Button2 = myButtonGroup.add ("button", undefined, "GREP Query Manager");
var Button3 = myButtonGroup.add ("button", undefined, "About");

//After Drawing Interface
//Showing the Dialog - We Will Show as Varaible So We Can Correctly Use Cancel Button (w.Show() are One time in Code)
var a = w.show();
//What Happened if User Hit About Button - All the OnClick Callers Must Came Before Showing Dialogs
Button0.onClick = function() {gogo();};
function gogo() {
Main();
}

//What Happened if User Hit About Button - All the OnClick Callers Must Came Before Showing Dialogs
Button1.onClick = function() {Canceled();};
function Canceled() {
  alert("Exit by User!");
  var a = w.close();
  exit(0);
}

//What Happened if User Hit About Button - All the OnClick Callers Must Came Before Showing Dialogs
Button2.onClick = function() {Options();};
function Options() {
CallTheQueryGManager();
}
//What Happened if User Hit About Button - All the OnClick Callers Must Came Before Showing Dialogs
Button3.onClick = function() {alertAbout();};
function alertAbout() {
alert("Find GREP and Apply Object Styles to Container, \nVersion 2.02 \n July 2021  \nTechno&Design \nCreated By : Mohammed Ibrahim \nCredits to : Manan Joshi \nContact me : medos20.mi@gmail.com" , "About");
}

function doAssignGREPtoOS() {
//Start the function
var myObjectStyle = myDropdown1.selection.toString(); //Object Style from DropDown List
var GrepString= myGREPString.text
app.findGrepPreferences = NothingEnum.NOTHING;
app.changeGrepPreferences = NothingEnum.NOTHING;
app.findGrepPreferences.findWhat = GrepString;
myFoundText = app.activeDocument.findGrep();
for(i=0;i<myFoundText.length;i++){
myFoundText[i].parentTextFrames[0].appliedObjectStyle=app.activeDocument.objectStyles.itemByName(myObjectStyle);
}
//alert("GREP Found's Assigned by Object Styles!", "Finished!");
}

//----------------------------------------------------------------
//for Palettes this is a Must!-Calling the Session
//----------------------------------------------------------------
//GREP Query Manager
//----------------------------------------------------------------
function CallTheQueryGManager() {
//~ #targetengine "session";
//~ var gqmanager = new Window ("palette");
gqmanager.text = "GREP Query Manager";
var myList = gqmanager.add ("listbox", undefined, ["\\(.+?\\)", "\\d+", ".+:", ".+!?", "!?"], {multiselect: true});

//MyListSize
myList.maximumSize.height = gqmanager.maximumSize.height - 100;
myList.minimumSize.width = 300;
var input = gqmanager.add ("edittext");
input.active = true;
input.characters = 30;

var inserttxt = gqmanager.add ("button", undefined, "Insert GREP Query", {name: "Insert"});
var del = gqmanager.add ("button", undefined, "Delete GREP Query", {name: "Delete"});
var load = gqmanager.add ("button", undefined, "Load GREP Queries", {name: "Load"});
var savelist = gqmanager.add ("button", undefined, "Save GREP Queries", {name: "Save"});
var deletelist = gqmanager.add ("button", undefined, "Delete Current Queries", {name: "Delete All items"});
var restoreorglist = gqmanager.add ("button", undefined, "Restore Previous Queries", {name: "Restore Previous"});

//myList onChange
myList.onChange = function () {
input.text = "";
input.text = input.text + myList.selection
//for Main Entry Dialog
myGREPString.text = input.text 
}

//insert item Button
inserttxt.onClick = function () {
insert_item (myList, input.text);
input.text = "";
input.active = true;
}

//delete selected item
del.onClick = function () {
// remember which line is selected
var sel = myList.selection[0].index;
for (var i = myList.selection.length-1; i > -1; i--)
myList.remove(myList.selection[i]);

// select a line after deleting one or more items
if (sel > myList.items.length-1)
myList.selection = myList.items.length-1;
else
myList.selection = sel;

}

//Saving the List in the Same path of Indesign file (must before Show Command)
savelist.onClick = function () {
    //Define path and file name
    var filePathMinusExtension = app.activeDocument.fullName.fsName.substr(0, app.activeDocument.fullName.fsName.lastIndexOf("."));
    var writeFile = File(filePathMinusExtension + "_GREP_Queries.txt");
    writeFile.encoding = 'UTF-8';
    writeFile.open('w');
	var content = ""
	for(var i = 0; i < myList.items.length; i++)
	content += myList.items[i].toString() + "\r"
    writeFile.write(content);
    writeFile.close();
    alert("Done, File Saved in Same InDesign Document Location", "Alert!");
}

//Load List Items and Show them
load.onClick = function () {
    //Remove old list items
    myList.removeAll()
    var filePathMinusExtension = app.activeDocument.fullName.fsName.substr(0, app.activeDocument.fullName.fsName.lastIndexOf("."));
    var ReadFile = File(filePathMinusExtension + "_GREP_Queries.txt");
    if (ReadFile.exists) {
        try {
            ReadFile.open("r");
            while (ln = ReadFile.readln()) {
                myList.add("item", ln);
            }
            //Close the file
            ReadFile.close();
            alert("Done, the GREP Queries Loaded");
            return true;
        }
        catch (errOpen) {
            alert("Error. The GREP Queries file could not be opened!");
            return false;
        }
    }
    else{
        alert("The GREP Queries file could not be found!");
        return false;
    }
}

//Insert Item Function
function insert_item (list_obj, new_item) {
if (list_obj.find (new_item) == null) {
var stop = list_obj.items.length;
//w.add(myList);
var i = 0;
while (i < stop && new_item > list_obj.items[i].text)
i++;
list_obj.add ("item", new_item, i);
}
}

//Delete All List - also - myList.removeAll()-Working!
deletelist.onClick = function () {
for (var i = myList.items.length-1; i > -1; i--)
myList.remove(myList.items[i]);
}

restoreorglist.onClick = function () {
    //First Remove any other Queries
    myList.removeAll()
   //Now Adding the Default GREP Queries
    myList.add ("item", "\\(.+?\\)");
    myList.add ("item", "\\d+");
    myList.add ("item", ".+:");
    myList.add ("item", ".+!?");
    myList.add ("item", "!?");
}
//Showing Dialog
gqmanager.show ();
}
//Showing Main Dialog
//w.show();

 

 

 

Best
Mohammad Hasanin

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Enthusiast ,
Jul 04, 2021 Jul 04, 2021

Copy link to clipboard

Copied

Hi, here is an explaining Video :
Video Explaining Problems 

Best
Mohammad Hasanin

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Guide ,
Jul 05, 2021 Jul 05, 2021

Copy link to clipboard

Copied

Hi @M.Hasanin 

 

Looks like an interesting project. I don't understand why you need a distinct (sub)palette. All could probably be done from within a single UI, no?

 

A crucial fact about the palette type (versus dialog) is that any instance of such Window object must have a persistent reference in memory. Having a targetengine directive is a requirement, but you also need to store the result of new Window('palette', etc) in a non-local variable. Otherwise the palette is automatically destroyed when the identifier is out of scope. A solution is to return that reference (from the function that builds the UI) and to store it as a static property of some persistent object, e.g your main function.

 

Here is a quick draft, keeping the idea of two interacting palettes. Not tested in depth, but this could help you improve the structure of your code:

 

#targetengine 'StyleToGrep'

if( 'function' != typeof $.global.StyleToGrep )
{
    Object.prototype.setup=function(o,k){for(k in o)o.hasOwnProperty(k)&&(this[k]=o[k]);return this};

    $.global.StyleToGrep = function StyleToGrep(  ui)
    //----------------------------------
    {
        if( !callee.getDocument() )
        {
            alert("No InDesign documents are open. Please open a document and try again.");
            return;
        }
        (callee.WIN=callee.uiMain()).show();
    }
    .setup
    ({
        //--- Settings
        UI_TYPE:    'palette',
        MAIN_TITLE: "Assigned GREP Results Container to Object Styles - Version 2.0x",
        GREP_TITLE: "GREP Query Manager",
        // ---
        QUERY_EXT: '_GREP_Queries.txt',
        DEF_QUERIES: ["\\(.+?\\)", "\\d+", ".+:", ".+!?", "!?"],
        // ---
        WIN_PROPS: {resizable:false, closeButton:true, maximizeButton:false, minimizeButton:false, independent:false},
        WIN: false,
        SUB: false,
    })
    .setup
    ({
        //--- Methods
        about: function(){ alert("blabla...") },
        getDocument: function(){ return app.properties.activeDocument||false },
        styleNames: function(  doc){ return (doc=this.getDocument()) ? doc.objectStyles.everyItem().name : [] },

        queryFile: function(  doc,ff)
        {
            ff = (doc=this.getDocument()) && doc.properties.fullName;
            ff && (ff=ff.fsName.substr(0,ff.fsName.lastIndexOf('.')));
            ff && (ff=File(ff + this.QUERY_EXT));
            return ff || false;
        },

        loadQueries: function(  ff,r,msg)
        {
            r = (ff=this.queryFile()).exists && (ff.encoding='BINARY') && ff.open('r');
            r && (r=[ff.read().split(/[\r\n]+/g),ff.close()][0]);
            msg = r
            ? ( r.length ? "Done, GREP Queries Loaded." : "Empty GREP Queries file!" )
            : "Error. The GREP Queries file could not be opened!";
            alert( msg );
            return r;
        },

        saveQueries: function(/*str[]*/data,  ff)
        {
            if( !data.length ) return;
            if( (ff=this.queryFile()) && (ff.encoding='BINARY') && ff.open('w') )
            {
                ff.write(data.join('\r')); ff.close();
                alert("Done, File Saved in Same InDesign Document Location");
            }
        },
        
        assign: function(/*str*/style,/*str*/grep,  doc,os,a,t,z)
        {
            os = (doc=this.getDocument()) && doc.objectStyles.itemByName(style);
            if( (!os) || !os.isValid ) return;
            app.findGrepPreferences = app.changeGrepPreferences = +NothingEnum.NOTHING;
            app.findGrepPreferences.findWhat = grep;
            for
            (
                z=0, a=doc.findGrep()||0, i=a.length||0 ;
                i-- ;
                (t=a[i].parentTextFrames).length && (++z, t[0].appliedObjectStyle=os)
            );
            if( 0 < z ) alert( z + " containers(s) processed.")
        },
    })
    .setup
    ({
        // --- Main UI
        uiMain: function uiMain(  w,t,u)
        {
            if( w=Window.find(this.UI_TYPE,this.MAIN_TITLE) ){ return w; }

            w = new Window(this.UI_TYPE, this.MAIN_TITLE, u, this.WIN_PROPS);
            w.preferredSize.width = 600;
            w.alignChildren = ['center','top'];
            w.orientation = 'row';
            w.spacing = w.margins = 16;
            // ---
            t = w.add('group');
            t.orientation = 'column';
            t.alignChildren = ['left','top'];
            t.spacing = 4;
            // ---
            t.add('statictext', u, "GREP: ");
            w.grep = t.add('edittext', u, "");
            w.grep.characters = 20;
            w.grep.enabled = true;
            w.grep.preferredSize.width = 350; 
            // ---
            t.add('statictext', u, "Object Styles: ");
            w.oss = t.add('dropdownlist', u, this.styleNames());
            w.oss.preferredSize.width = 350; 
            w.oss.selection = 0;
            
            t = w.add('group');
            t.orientation = 'column';
            t.add('button', u, "Find GREP and Apply Style", {cmd:'apply'});
            t.add('button', u, "GREP Query Manager", {cmd:'grep'});
            t.add('button', u, "Exit", {cmd:'exit'});
            t.add('button', u, "About", {cmd:'about'});
            
            t.addEventListener('click',callee.BTNS);
            w.center();
            return w;
        }
        .setup
        ({
            BTNS: function onButton(/*MouseEvent*/ev, t,w)
            {
                w = (t=ev.target).window;
                switch( (t.properties||0).cmd )
                {
                    case 'apply':
                        (t=w.oss.selection) && StyleToGrep.assign(t.text,w.grep.text);
                        break;
                    case 'exit':
                        StyleToGrep.SUB && StyleToGrep.SUB.close();
                        w.close();
                        break;
                    case 'grep':
                        t = StyleToGrep.SUB = StyleToGrep.uiGrep();
                        t.show();
                        t.active = true;
                        break;
                    case 'about':
                        StyleToGrep.about();
                        break;
                    default:;
                }
            },
        }),
    })
    .setup
    ({
        // --- Grep UI
        uiGrep: function(  w,t,u)
        {
            if( w=Window.find(this.UI_TYPE,this.GREP_TITLE) ){ return w; }

            w = new Window(this.UI_TYPE, this.GREP_TITLE, u, this.WIN_PROPS);
            w.orientation = 'row';
            w.margins = w.spacing = 16;
            w.alignChildren = ['left', 'top'];
            t = w.add('group');
            t.orientation = 'column';
            w.input = t.add('edittext');
            w.input.characters = 30;
            w.input.active = true;
            w.list = t.add('listbox', u, this.DEF_QUERIES, {multiselect:true});
            w.list.minimumSize.width = 300;
            w.list.minimumSize.height = 200;
            w.list.onChange = callee.LIST;
            // ---
            t = w.add('group');
            t.orientation = 'column';
            t.alignChildren = ['left','top'];
            t.add('button', u, "Insert",           {cmd:'insert'});
            t.add('button', u, "Delete Selection", {cmd:'delete'});
            t.add('button', u, "Delete All",       {cmd:'deleteall'});
            t.add('button', u, "Load",             {cmd:'load'});
            t.add('button', u, "Save",             {cmd:'save'});
            t.add('button', u, "Restore",          {cmd:'restore'});
            t.addEventListener('click',callee.BTNS);
            
            w.center();
            return w;
        }
        .setup
        ({
            LIST: function onListChange(  w,t)
            {
                w = this.window;
                t = this.selection; // ListItem[]
                w.input.text = t && t.length ? t[0].text : '';
                
                if( t=Window.find(StyleToGrep.UI_TYPE,StyleToGrep.MAIN_TITLE) )
                {
                    try{ t.grep.text=w.input.text }catch(_){}
                }
            },
            
            BTNS: function onButton(/*MouseEvent*/ev,  t,w,lb,a,i)
            {
                w = (t=ev.target).window;
                lb = w.list; // multisel
                switch( (t.properties||0).cmd )
                {
                    case 'insert':
                        t = w.input.text;
                        if( !lb.find(t) )
                        {
                            for( i=(a=lb.items).length ; i-- && t < a[i].text ; );
                            lb.add("item", t, 1+i);
                        }
                        w.input.text = "";
                        w.input.active = true;
                        break;

                    case 'delete':
                        a = lb.selection;
                        if( (!a) || !a.length ) break;
                        t = a[0].index;
                        for( i=a.length ; i-- ; lb.remove(a[i]) );
                        lb.selection = Math.min(t,lb.items.length-1);
                        break;
                    
                    case 'deleteall':
                        lb.removeAll();
                        break;

                    case 'load':
                        lb.removeAll();
                        if( !(a=StyleToGrep.loadQueries()) ) break;
                        for( i=-1 ; ++i < a.length ; lb.add('item',a[i]) );
                        break;
                    
                    case 'save':
                        a = lb.items;
                        for( t=[], i=-1 ; ++i < a.length ; t[i]=a[i].text );
                        StyleToGrep.saveQueries(t);
                        break;
                    
                    case 'restore':
                        lb.removeAll();
                        a = StyleToGrep.DEF_QUERIES;
                        for( i=-1 ; ++i < a.length ; lb.add('item',a[i]) );
                        break;

                    default:;
                }
            }
        }),
    });
    
    delete Object.prototype.setup; // cleanup
}

StyleToGrep();

 

Best,

Marc

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Guide ,
Jul 05, 2021 Jul 05, 2021

Copy link to clipboard

Copied

As code formatting & highlighting is horrible in Adobe forums, here is a better view on GH Gist:

InteractingPalettesExample.jsx 

 

Best,

Marc

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Enthusiast ,
Jul 07, 2021 Jul 07, 2021

Copy link to clipboard

Copied

LATEST

Thanks alot Eng.Marc, Many Thanks to you, Can i get also the Groups and Sub Groups Styles? and How?

Best
Mohammad Hasanin

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines