30 Replies Latest reply on Nov 24, 2016 4:10 AM by Jostify

    [CS3][JS] beforeClose event listener problem

    Kasyan Servetsky Level 5
      Hi all,

      I want my script to do the following: every time when a user closes a document, I wish for "Check Spelling..." dialog box to show up and after the user finishes spell-checking, the document should be closed.
      But instead, if I have one document open, I get an error: Error Number: 53762, Error String: Action is not enabled, and if more than one document open, the dialog opens in the wrong document.
      As far as I understand, the problem is that the menu action is invoked AFTER the document has already been closed – it is quite clear that opening the dialog with no documents open makes no sense – that’s why the error occurs.

      Does anybody know how to solve this? Why beforeClose event type doesn’t correspond to its name? The scripting guide states: “beforeClose – Appears after a close-document request is made but before the document is closed.”

      Here is the script:


      #targetengine "session"
      main();
      function main(){
         var myEventListener = app.addEventListener("beforeClose", myCheckSpelling, false);
      }
      function myCheckSpelling(myEvent){
         app.menuActions.item("Check Spelling...").invoke();
      }

      Kasyan
        • 1. Re: [CS3][JS] beforeClose event listener problem
          Level 1
          I wish I could help you but I can't because I am having the same problem in AppleScript. I am wanting to record the name of the active document while I am closing it. The problem is, the line:

          set DocName to the name of the active document

          will not work because the document is closed before the script is run, even though I have specified it to happen as a beforeClose in the event listener.
          • 2. Re: [CS3][JS] beforeClose event listener problem
            Harbs. Level 6
            I think a distinction needs to be made here:

            The events are not sent after the document is closed. It is sent after
            the document *window* is closed. Scripts which run in an afterOpen or
            beforeClose event are equivalent to running a script on a document
            opened without a window. The following script demonstrated this point:

            #targetengine "test"
            app.addEventListener("beforeClose", theHandler);
            app.addEventListener("afterOpen", theHandler);
            function theHandler(){
            alert(app.layoutWindows.length);
            alert(app.documents.length);
            }

            If you need it to run with a layout window active, I'd suggest you use
            Rorohiko's docClose and docLoaded events.

            --
            Harbs
            http://www.in-tools.com
            • 3. Re: [CS3][JS] beforeClose event listener problem
              Level 1
              After playing this morning I realized the importance of calling the EventListener event into the script, in Applescript it appears like this.

              unlogUser(evt) --evt being the result passed by the EventListener (as per the scripting guide)

              on unlogUser(myDoc)
              set myDocName to the name of the parent of myDoc
              end unLogUser

              I don't know how to translate that to JS, but I hope the concept helps, it certainly helped me.
              • 4. Re: [CS3][JS] beforeClose event listener problem
                Level 1
                Check the event phase of your listener. There are big differences between capture and bubbling phases.

                Bob
                • 5. Re: [CS3][JS] beforeClose event listener problem
                  Kasyan Servetsky Level 5
                  First of all, thanks everybody who responded to me.

                  >If you need it to run with a layout window active, I'd suggest you use Rorohiko's docClose and docLoaded events.

                  I just started exploring a demo version Active Page Item Developer Toolkit, so Im not expert in it yet. I want to make this script for another person; if I use Rorohiko's events, does it mean that this guy should buy APID Toolkit to use the script?

                  >I don't know how to translate that to JS, but I hope the concept helps

                  I know how to translate your code to JS, but the concept hasnt worked in my case.

                  >Check the event phase of your listener.

                  After I did a little test, I found out the following information about my listener:

                  Handling Event: beforeClose
                  Target: [object Document]Test.indd
                  Current: [object Application]Adobe InDesign
                  Phase: Bubbling
                  Captures: true
                  Bubbles: true
                  Cancelable: false
                  Stopped: false
                  Canceled: false

                  Now I know that event phase is Bubbling, but I dont know what to do with it next. Could you please give me a hint?

                  Kasyan
                  • 6. Re: [CS3][JS] beforeClose event listener problem
                    Kasyan Servetsky Level 5
                    One more question is about Rorohiko's docClose event:
                    I created a new document, created a frame, selected it and set Event Filter to “docClose”. Finally I set script to the following:
                    var myDocument = app.documents[0];
                    alert(myDocument.name);

                    This works — even though the layout window is hidden, the alert with document’s name pops up – so I’m on the beam. BTW, It doesn’t work with “var myDocument = app.activeDocument;” for some reason.
                    But when I change the script to – app.menuActions.item("Check Spelling...").invoke(); – I get the same error as before.
                    Then I checked both checkboxes: Display Error dialogs and Use Debugger, ESTK shows up with this script:
                    var theItem = resolve("/document[@name=\"del1.indd\"]//rectangle[@id=193]");
                    app.menuActions.item("Check Spelling...").invoke();

                    1st line was selected, I typed into console “app.documents[0].name”
                    It returned “del1.indd” – so Harbs had been right – indeed the document was still open, though invisible. I continued to the next step and got the same error.
                    • 7. Re: [CS3][JS] beforeClose event listener problem
                      CTC Imaging Level 1
                      I do not if you sloved all but I had the same issue using JS.

                      Here is what Olev Told me to try.

                      check this thread.
                      Alexandre VERCAMMEN, "(CS3) Does anyone know how to place request for..." #11, 12 May 2008 4:01 pm

                      Code ===========================
                      Main ();
                      ...
                      app.menuActions.item("Close").addEventListener("beforeInvoke",EventClose, false);
                      ...

                      function EventClose (itsEvent)
                      {

                      var myExeSrcFile = new File (app.scriptArgs.get("Event_Close"));
                      if (myExeSrcFile.exists)
                      {
                      myExeSrcFile.open ('r:(read)');
                      app.doScript(myExeSrcFile, ScriptLanguage.javascript);
                      myExeSrcFile.close();
                      }
                      else
                      alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);

                      return;
                      }
                      • 8. Re: [CS3][JS] beforeClose event listener problem
                        Harbs. Level 6
                        Hi Kasyan,

                        I just checked, and it seems I was mistaken. The docLoaded event is
                        indeed after the layout window is loaded, but the docClosed event is
                        after the layout window is closed. It was never pertinent to me, so I
                        never checked this before...

                        --
                        Harbs
                        http://www.in-tools.com
                        • 9. Re: [CS3][JS] beforeClose event listener problem
                          Level 1
                          Hi Kasyan,

                          Hm. The trouble is that the event is not cancelable. Ordinarily, to prevent the program from moving on to the action, you'd stop even propagation and cancel the default behavior of the event. But you can't do that for beforeClose.

                          But, as a workaround, you could try putting the event listener on the Close menu action. I don't think this will catch people closing the window via the close box, through--only if they use the menu item.

                          Thanks,

                          Ole
                          • 10. Re: [CS3][JS] beforeClose event listener problem
                            CTC Imaging Level 1
                            Yes, indeed as a Menu Action it works great. There is not reason really to handle it as an event since the document being closed is the active one!

                            On the other hand an Open statement would be an event. Specifically when we are dealing with another application passing (calling) the document to InDesign as a parameter.

                            Unfortunately, InDesign crashes as soon as you close the document that was opened by the "Open" event. I have not figured it out yet, especially since triggering the script manually works great. So how could it be a script error at an exit level?

                            Any suggestion?

                            Code ============================

                            app.addEventListener("afterOpen", EventOpen, false);
                            ....
                            function EventOpen (itsEvent)
                            {
                            var myExeSrcFile = new File (app.scriptArgs.get("Event_Open"));
                            if (myExeSrcFile.exists)
                            {
                            itsEvent.parent.windows.add(); //*** Doc. has no window.
                            myExeSrcFile.open ('r:(read)');
                            app.doScript(myExeSrcFile, ScriptLanguage.javascript);
                            myExeSrcFile.close();
                            }
                            else
                            alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);
                            return;
                            }

                            ========================

                            FYI: Replacing the Event with an Action and removing the windows.add method works. But it cannot handle "Application Call"!

                            Code ++++++++++++++++++++++++++++++++++

                            app.menuActions.item("Open...").addEventListener("afterInvoke",ActionOpen, false);
                            ....
                            function ActionOpen (itsAction)
                            {
                            var myExeSrcFile = new File (app.scriptArgs.get("Event_Open"));
                            if (myExeSrcFile.exists)
                            {
                            myExeSrcFile.open ('r:(read)');
                            app.doScript(myExeSrcFile, ScriptLanguage.javascript);
                            myExeSrcFile.close();
                            }
                            else
                            alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);
                            return;
                            }
                            • 11. Re: [CS3][JS] beforeClose event listener problem
                              Kasyan Servetsky Level 5
                              Hi all,

                              At last I figured out how to solve my problem. Here is my script:


                              /* CheckSpelling.jsx
                              Version 1
                              This script is written to remind a user to spell-check the current document.
                              Put this script into Startup scripts folder and restart InDesign if it's running. */
                              #target indesign
                              #targetengine "session"
                              var myLastDoc;
                              var myConfirm;
                              var myCheckSpellEvList = app.menuActions.item("Check Spelling...").addEventListener("beforeInvoke", myCheckSpellHandler, false);
                              var myBeforeCloseEvList = app.addEventListener("beforeClose", myBeforeCloseHandler, false);
                              var myAfterCloseEvList = app.addEventListener("afterClose", myAfterCloseHandler, false);
                              function myBeforeCloseHandler(myEvent){
                                 myConfirm = false;
                                 if (!eval(myEvent.parent.extractLabel("SpellingChecked")) && myEvent.parent.saved == true){
                                    myLastDoc = myEvent.parent.fullName;
                                    myConfirm = confirm("Do you want to check spelling now?", false, "You forgot to check spelling!");
                                 }
                              }
                              function myAfterCloseHandler(myEvent){
                                 if (!eval(myEvent.parent.extractLabel("SpellingChecked"))){
                                    if (myConfirm) {
                                       app.open(myLastDoc);
                                       app.menuActions.item("Check Spelling...").invoke();
                                    }
                                 }
                              }
                              function myCheckSpellHandler(myEvent){
                                 app.activeDocument.insertLabel("SpellingChecked", "true");
                              }

                              Initially I tried to take the approach offered by Ole (in the thread pointed out by Alexandre).


                              #targetengine "session"
                              main();
                              function main(){
                              var myCloseMenuAction = app.menuActions.item("Close");
                              var myEventListener = myCloseMenuAction.eventListeners.add("beforeInvoke",myBeforeInvokeHandler, false);
                              }
                              function myBeforeInvokeHandler(myEvent){
                                 var myDoc = app.activeDocument.parent;
                                    myEvent.preventDefault();
                                    myEvent.stopPropagation();
                                    app.scriptPreferences.userInteractionLevel = UserInteractionLevels.neverInteract;
                                    app.menuActions.item("Check Spelling...").invoke();
                                    app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;
                              }

                              But it had two drawbacks:
                              1 – If a user closes the window by clicking the window's close box, the script doesn’t carry out its duties, which are not allowing a user to forget check spelling of the document before he closes it.
                              2 – An alert pops up — “An attached script canceled this action.” — of which I unsuccessfully tried to get rid by setting temporarily userInteractionLevel to neverInteract.

                              When Harbs told me that the script running in an beforeClose event is equivalent to running a script on a document opened without a window, I remembered an example from the scripting guide: open a document in the background and the then show it:
                              var myDocument = app.open(File("/c/myTestDocument.indd"), false);
                              
                              var myLayoutWindow = myDocument.windows.add();


                              I tried to repeat the trick:


                              #targetengine "session"
                              main();
                              function main(){
                                 var myEventListener = app.addEventListener("beforeClose", myCheckSpelling, false);
                              }
                              function myCheckSpelling(myEvent){
                                 myEvent.parent.parent.windows.add();
                                 app.menuActions.item("Check Spelling...").invoke();
                              }

                              The document reappears, the “Check Spelling...” dialog shows up and at this moment the things go off the rails — InDesign is crashing.

                              The document at this moment seems to be in limbo: neither open, nor closed. So I decided to let it finish closing and then reopen it, in case a user chooses “Yes” in the confirm dialog.

                              Thanks again everybody who helped me.

                              Kasyan
                              • 12. Re: [CS3][JS] beforeClose event listener problem
                                CTC Imaging Level 1
                                Good deal.
                                Maybe I can modify my OpenEvent, where I would close and reopen?
                                As of now it opens fine but as soon as the document is closed, InDesign crashes!

                                Code ==========================
                                function EventOpen (itsEvent)
                                {
                                var myExeSrcFile = new File (app.scriptArgs.get("Event_Open"));
                                if (myExeSrcFile.exists)
                                {
                                var eventDoc = itsEvent.parent.fullName;
                                eventDoc.close(); //*** Make sure it's closed
                                app.open(eventDoc); //*** Reopen it.
                                myExeSrcFile.open ('r:(read)');
                                app.doScript(myExeSrcFile, ScriptLanguage.javascript);
                                myExeSrcFile.close();
                                }
                                else
                                alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);
                                return;
                                }

                                or (Even BETTER using the ActionMenu of Open.

                                function EventOpen (itsEvent)
                                {
                                var eventDoc = itsEvent.parent.fullName;
                                eventDoc.close(); //*** Make sure it's closed
                                app.open(eventDoc); //*** Reopen it.
                                app.menuActions.item("Open...").invoke();
                                }
                                =====================================

                                As soon as I get to work, I'll test and post an update.
                                • 13. Re: [CS3][JS] beforeClose event listener problem
                                  CTC Imaging Level 1
                                  Well I tried a bunch of variation and either InDesign crashed as soon as you close the document or I get script error when I try to close and reopen. It is very frustating, since it seems to be an issue about handlers... When I close the doc., it may not be handling myDoc pointer (var myDoc = app.activeDocument) but the event.parent????
                                  I am confused now!
                                  :)
                                  Still do not understand why using the script manually works. As soon I tie an eventListener, it crashes ONLY when closing the doc.
                                  Any help will be appreciated (it has been 9 months... and counting)
                                  LOL :)
                                  • 14. Re: [CS3][JS] beforeClose event listener problem
                                    Kasyan Servetsky Level 5
                                    Hi Alex,

                                    To make the document reopen after closing I added two event listeners: beforeClose and afterClose.
                                    The first is to ask a user if he wants to reopen the document and the second is to reopen it if the user chose so.
                                    My approach is let InDesign to finish closing the document and when afterClose event is sent – that is the document is closed — reopen it.

                                    Kasyan
                                    • 15. Re: [CS3][JS] beforeClose event listener problem
                                      CTC Imaging Level 1
                                      Well I understood your "trick" so I tried to apply to the other end the "Open".

                                      Well I have to create a window (*) for the document otherwise I get a javascript error from the "doScript" instruction. The script executes fines. The handler completes fully w/o error. But because of that window (*), InDesign will crash as soon as I close the document. Also you cannot use "fullName" because of "Untiled" documents which are created when opening a template or a CS2 version. Looks like the platform becomes "unstable" as soon as closing a document "handled" on another level?

                                      Anyone help?
                                      • 16. Re: [CS3][JS] beforeClose event listener problem
                                        Level 1
                                        Hi Alexandre,

                                        Could you send me a complete script that demonstrates the problem?

                                        I'm sorry I haven't been able to get to this sooner--I've been incredibly busy, and this one seems like it'll take some time to resolve.

                                        Thanks,

                                        Ole
                                        • 17. Re: [CS3][JS] beforeClose event listener problem
                                          CTC Imaging Level 1
                                          Thank you Ole.

                                          I've been at it for about 6 months.

                                          I am providing 3 modules. All modules are in 1 folder. That's why the ScriptPath & Department variables.
                                          FYI: app.pdfPlacePreferences.pageNumber was used solved issues with InEvenScript plugin for CS2. That plugin was NOT handling a loop call. To solve it, I've used a variable to turn ON & OFF the handler. "Import" is used in the OPEN script, and that will execute the event!

                                          1) Startup. I trimmed it for you but I kept the orignal OPEN-Event disabled. See PrePressEVENT.
                                          2) PrePressTEST. It's a trimmed version of the actual PrePressOPEN. But it makes InDesign crash. FYI: PrePressOPEN works perfectly when triggered manualy (Script Panel).
                                          3) PrepressEVENT. Disabled in Startup, I am using this one so I can debug the EVENT and do actual work at the same time. Until it crashed of course.

                                          The window.add() is what makes it crash. Without it, fine. But if removed myDoc = app.activeDocument points to the wrong one!

                                          Thank you in advance. Hope this is clear enough.

                                          Module STARTUP
                                          =====================
                                          #target indesign
                                          #targetengine "session"
                                          app.scriptPreferences.version = 5.0;

                                          //******************** BEGIN Main ********************

                                          var myScriptName = app.activeScript.fsName;
                                          var myScriptPath = app.activeScript.path;
                                          var myErrorStyle = "*****Error while Updating!"
                                          var myMsgStyle = "*****No UpDate! (Delete to Reset)";
                                          var myDept = "PrePress";

                                          //*** Initialize SCRIPT Variables
                                          app.scriptArgs.clear();
                                          app.scriptArgs.set("Department", "PrePress");
                                          app.scriptArgs.set("ErrorStyle", "*****Error while Updating!");
                                          app.scriptArgs.set("MsgStyle", "*****No UpDate! (Delete to Reset)");
                                          app.scriptArgs.set("Event_Path", myScriptPath); //***Path to InEventScript Plug-In
                                          app.scriptArgs.set("Event_Test", myScriptPath + "/"+myDept+"TEST.jsx"); //*** Debugging MODULE
                                          app.scriptArgs.set("Event_Open", myScriptPath + "/"+myDept+"OPEN.jsx");
                                          app.scriptArgs.set("Event_Close", myScriptPath + "/"+myDept+"CLOSE.jsx");
                                          app.scriptArgs.set("Event_Copy", myScriptPath + "/"+myDept+"COPY.jsx");
                                          app.scriptArgs.set("Event_Clean", myScriptPath + "/"+myDept+"CLEAN.jsx");
                                          app.scriptArgs.set("Event_Print", myScriptPath + "/"+myDept+"PRINT.jsx");
                                          app.scriptArgs.set("Event_App", myScriptPath + "/"+myDept+"APPPreferences.jsx");
                                          app.scriptArgs.set("Event_Doc", myScriptPath + "/"+myDept+"DOCPreferences.jsx");

                                          //*** Initialize GLOBAL Variables
                                          app.pdfPlacePreferences.pageNumber = 1; //***Flag to PREVENT InEventScript Plug-In RECURSIVE (Loop)
                                          SkipWRDS = new Array;

                                          //*** REMOVE all EVENTS
                                          app.eventListeners.everyItem().remove();

                                          //******************** EVENTS ********************
                                          //app.addEventListener("afterOpen", EventOpen, false); //STILL INDESIGN CRASH with OPEN !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                                          var tmp = "List of Events loaded\n----------------------\n";
                                          var myEvents = app.eventListeners;
                                          for (var cpt = 0; cpt < myEvents.length; cpt++)
                                          tmp += "Event : " + myEvents[cpt].parent.name + "\tType: " + myEvents[cpt].eventType + "\n";

                                          //alert ("\tPREPRESS Area\n\t\==========\n\n"+tmp);
                                          alert ("\tTEST Area\n\t=======\n\n"+tmp);

                                          //******************** END Main ********************

                                          //****************** FUNCTIONS Definitions ********************

                                          function EventOpen (itsEvent)
                                          {
                                          var myExeSrcFile = new File (app.scriptArgs.get("Event_Open"));
                                          if (myExeSrcFile.exists)
                                          {
                                          if (app.pdfPlacePreferences.pageNumber == 99999)
                                          app.pdfPlacePreferences.pageNumber = 1; //***Flag to PREVENT InEventScript Plug-In RECURSIVE (Loop)
                                          else
                                          {
                                          app.pdfPlacePreferences.pageNumber = 1; //***Flag to PREVENT InEventScript Plug-In RECURSIVE (Loop)
                                          // itsEvent.preventDefault();
                                          // itsEvent.stopPropagation();
                                          itsEvent.parent.windows.add(); //*** Doc. has no Window!!!
                                          myExeSrcFile.open ('r:(read)');
                                          app.doScript(myExeSrcFile, ScriptLanguage.javascript);
                                          myExeSrcFile.close();
                                          }
                                          }
                                          else
                                          alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);
                                          return;
                                          }

                                          Module PrePressTEST
                                          =====================
                                          #target indesign
                                          //#include "PrePressLIBRARY.jsxinc"
                                          app.scriptPreferences.version = 5.0;

                                          //******************** BEGIN Main ********************

                                          if (app.modalState) //*** Alert already displayed
                                          exit();

                                          if (app.pdfPlacePreferences.pageNumber == 99999)
                                          {
                                          app.pdfPlacePreferences.pageNumber = 1; //***Flag to PREVENT InEventScript Plug-In RECURSIVE (Loop)
                                          exit();
                                          }

                                          if (app.documents.length == 0)
                                          exit();

                                          var myDoc = app.activeDocument;

                                          //*** ALL DOCUMENTS PREFERENCE
                                          myDoc.textPreferences.showInvisibles = true;
                                          myDoc.viewPreferences.showRulers = true;
                                          myDoc.layoutWindows[0].transformReferencePoint = AnchorPoint.centerAnchor;

                                          alert (myDoc.name);

                                          //******************** END Main ********************

                                          Module PrePressEVENT
                                          =====================
                                          #target indesign
                                          #targetengine "session"
                                          app.scriptPreferences.version = 5.0;

                                          //******************** BEGIN Main ********************

                                          var myEvents = app.eventListeners;
                                          var tmp = "\nList of Events removed\n------------------------\n";
                                          for (var cpt = myEvents.length-1 ; cpt >= 0 ; cpt--)
                                          {
                                          if (myEvents[cpt].eventType == "afterOpen")
                                          {
                                          tmp += "Event #" + cpt + "\tType: " + myEvents[cpt].eventType + "\n";
                                          myEvents[cpt].remove(); //*** There MAY be MORE than 1 instance.
                                          }
                                          }

                                          //******************** EVENTS ********************
                                          app.addEventListener("afterOpen", EventOpen, false);

                                          tmp += "\nList of Events loaded\n----------------------\n";
                                          var myEvents = app.eventListeners;
                                          for (var cpt = 0; cpt < myEvents.length; cpt++)
                                          tmp += "Event : " + myEvents[cpt].parent.name + "\tType: " + myEvents[cpt].eventType + "\n";

                                          alert ("\tTEST Area\n\t=======\n\n"+tmp);

                                          //******************** END Main ********************

                                          //****************** FUNCTIONS Definitions ********************

                                          function EventOpen (itsEvent)
                                          {

                                          // app.scriptArgs.set("Event_Listener", itsEvent.parent.toSource()); //*** PASS Argument

                                          var myExeSrcFile = new File (app.scriptArgs.get("Event_Test"));
                                          if (myExeSrcFile.exists)
                                          {
                                          if (app.pdfPlacePreferences.pageNumber == 99999)
                                          app.pdfPlacePreferences.pageNumber = 1; //***Flag to PREVENT InEventScript Plug-In RECURSIVE (Loop)
                                          else
                                          {
                                          app.pdfPlacePreferences.pageNumber = 1; //***Flag to PREVENT InEventScript Plug-In RECURSIVE (Loop)
                                          /*
                                          EventInfo (itsEvent);
                                          itsEvent.preventDefault();
                                          itsEvent.stopPropagation();
                                          */
                                          itsEvent.parent.windows.add(); //*** Doc. has no Window!!!
                                          myExeSrcFile.open ('r:(read)');
                                          app.doScript(myExeSrcFile, ScriptLanguage.javascript);
                                          myExeSrcFile.close();
                                          alert ("Executed...");
                                          }
                                          }
                                          else
                                          alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);

                                          return;
                                          }

                                          function EventInfo (itsEvent)
                                          {
                                          var myString = "Handling Event: " +itsEvent.eventType;
                                          myString += "\r\rTarget: " + itsEvent.target + " " +itsEvent.target.name;
                                          myString += "\rCurrent: " +itsEvent.currentTarget + " " + itsEvent.currentTarget.name;
                                          myString += "\r\rPhase: " + GetPhaseName(itsEvent.eventPhase );
                                          myString += "\rCaptures: " +itsEvent.captures;
                                          myString += "\rBubbles: " + itsEvent.bubbles;
                                          myString += "\r\rCancelable: " +itsEvent.cancelable;
                                          myString += "\rStopped: " +itsEvent.propagationStopped;
                                          myString += "\rCanceled: " +itsEvent.defaultPrevented;
                                          myString += "\r\rTime: " +itsEvent.timeStamp;
                                          alert(myString);

                                          function GetPhaseName(myPhase)
                                          {
                                          switch(myPhase){
                                          case EventPhases.atTarget:
                                          myPhaseName = "At Target";
                                          break;
                                          case EventPhases.bubblingPhase:
                                          myPhaseName = "Bubbling";
                                          break;
                                          case EventPhases.capturingPhase:
                                          myPhaseName = "Capturing";
                                          break;
                                          case EventPhases.done:
                                          myPhaseName = "Done";
                                          break;
                                          case EventPhases.notDispatching:
                                          myPhaseName = "Not Dispatching";
                                          break;
                                          }
                                          return myPhaseName;
                                          }
                                          • 18. Re: [CS3][JS] beforeClose event listener problem
                                            CTC Imaging Level 1
                                            Good morning Kasyan and Ole

                                            This about another thread I posted. Kasyan you helped someone one a similar issue regarding Group Overset Text. Could you look into it.

                                            Mainly the issue is you have to use insertionPoints to change the kerningValue. If the Word is hidden (overflow) than you get a javascript error. Obviously you have to reset the textframe height so you can reveal the text. Sounds easy BUT I have to change the TextFrame on the fly (because of search & replace) and back to its original size before the end of the loop (stepping through the search result list)

                                            Alexandre VERCAMMEN, "[JS] Formating Text Overflow" #, 8 Oct 2008 5:00 pm

                                            "myAnswer" is the Array of words resulting from a search/replace.
                                            Here is an example.
                                            ==============================================
                                            for (var cpt = 0; cpt < myAnswer.length; cpt++)
                                            {
                                            myAnswer[cpt].capitalization = Capitalization.normal;
                                            if (myAnswer[cpt].contents.search(/c[\/\.]o/) > -1)
                                            {
                                            switch (true)
                                            {
                                            case ((myAnswer[cpt].appliedFont.name.search("Plantin Std") > -1) &&
                                            (myAnswer[cpt].appliedFont.fontStyleName == "Regular")):
                                            myAnswer[cpt].insertionPoints[1].kerningValue += 10;
                                            myAnswer[cpt].insertionPoints[2].kerningValue += -80;
                                            break;
                                            case ((myAnswer[cpt].appliedFont.name.search("Helvetica") > -1) &&
                                            (myAnswer[cpt].appliedFont.fontStyleName == "Roman")):
                                            myAnswer[cpt].insertionPoints[1].kerningValue += 50;
                                            myAnswer[cpt].insertionPoints[2].kerningValue += -70;
                                            break;
                                            case ((myAnswer[cpt].appliedFont.name.search("Helvetica") > -1) &&
                                            (myAnswer[cpt].appliedFont.fontStyleName == "Bold")):
                                            myAnswer[cpt].insertionPoints[1].kerningValue += 10;
                                            myAnswer[cpt].insertionPoints[2].kerningValue += -90;
                                            break;
                                            case ((myAnswer[cpt].appliedFont.name.search("Helvetica") > -1) &&
                                            (myAnswer[cpt].appliedFont.fontStyleName == "Bold Condensed")):
                                            myAnswer[cpt].insertionPoints[1].kerningValue += -40;
                                            myAnswer[cpt].insertionPoints[2].kerningValue += -60;
                                            break;
                                            default:
                                            myAnswer[cpt].insertionPoints[2].kerningValue += -40;
                                            break;
                                            }
                                            }
                                            }
                                            • 19. Re: [CS3][JS] beforeClose event listener problem
                                              Kasyan Servetsky Level 5
                                              Hi Alex

                                              Could you send me a zipped ID document (without images, just text) and full version of the script so that I could reproduce your problem.

                                              Kasyan

                                              askoldich@yahoo.com
                                              kasyan@business.ua
                                              • 20. Re: [CS3][JS] beforeClose event listener problem
                                                Level 1
                                                Hi Alexandre,

                                                Actually, you should be able to use single characters to set the kerning value (rather than insertion points). So you can solve the problem with successive searches. There should be no need to change the size of the text frame, and no need to process the found results.

                                                Let's imagine that I want to find and kern the "Kv" in "Kvern". I create a character style--let's call it "kern". This character style does not apply any formatting.

                                                1. Search for "Kvern" and apply the character style "kern"
                                                2. Search for "vern" with the character style "kern" applied and apply the "[None]" character style.
                                                3. Search for "K" with the character style "kern" applied and apply no style and the manual kerning value you want.

                                                Then move on to the next custom kerning instance, etc.

                                                Thanks,

                                                Ole
                                                • 21. Re: [CS3][JS] beforeClose event listener problem
                                                  CTC Imaging Level 1
                                                  Ole,
                                                  Actually I tried to access the character from w/i the word and received the error "No available in the present state...". It was even explicit to use insertionPoints to change the kerning between the 2 characters!?!
                                                  Alex.
                                                  • 22. Re: [CS3][JS] beforeClose event listener problem
                                                    Kasyan Servetsky Level 5
                                                    Alex,

                                                    When I use characters instead of insertionPoints, the error has gone.

                                                    var myChar = myAnswer[cpt].characters[1];
                                                    
                                                    myChar.kerningValue = -40;
                                                    • 23. Re: [CS3][JS] beforeClose event listener problem
                                                      CTC Imaging Level 1
                                                      I'll try. In that stripped module. I did before I contacted you and it did not!?!?


                                                      On Thu, Oct 16, 2008 at 2:58 PM, Kasyan Servetsky < member@adobeforums.com> wrote:

                                                      A new message was posted by Kasyan Servetsky in


                                                      InDesign Scripting --
                                                        [CS3][JS] beforeClose event listener problem

                                                      Alex,

                                                      When I use characters instead of insertionPoints, the error has gone.

                                                      var myChar = myAnswer[cpt].characters[1];
                                                      
                                                      myChar.kerningValue = -40;








                                                      View/reply at [CS3][JS] beforeClose event listener problem
                                                      Replies by email are OK.
                                                      Use the unsubscribe form to cancel your email subscription.



                                                      • 24. Re: [CS3][JS] beforeClose event listener problem
                                                        Level 1
                                                        Hi Alexandre,

                                                        re: "Actually I tried to access the character from w/i the word and received the error "No available in the present state...". It was even explicit to use insertionPoints to change the kerning between the 2 characters!?!"

                                                        Read my message again. You should be able to do what you need to do using find/change alone. There's no need to address the character inside the found items directly, as the kerning value can be applied via find/change. Here's an example:

                                                        //FindChangeManualKerning.jsx
                                                        //An InDesign CS3 JavaScript
                                                        //
                                                        //Shows how to add footnotes.
                                                        main();
                                                        function main(){
                                                            mySetup();
                                                            mySnippet();
                                                            myTeardown();
                                                        }
                                                        function mySetup(){
                                                             var myDocument = app.documents.add();
                                                            var myPage = myDocument.pages.item(0);
                                                             var myTextFrame = myPage.textFrames.add();
                                                             //Set the bounds of the text frame.
                                                             myTextFrame.geometricBounds = myGetBounds(myDocument, myPage);
                                                             //Fill the text frame with placeholder text.
                                                             myTextFrame.contents = TextFrameContents.placeholderText;
                                                        }
                                                        function mySnippet(){
                                                             var myCharacterStyle;
                                                            //
                                                            var myDocument = app.documents.item(0);
                                                            var myPage = myDocument.pages.item(0);
                                                            var myTextFrame = myPage.textFrames.item(0);
                                                            //Add four instances of "Kvern" at random locations in the story.
                                                             for(myCounter = 0; myCounter < 4; myCounter ++){
                                                                  myWord = myTextFrame.parentStory.words.item(myGetRandom(0, myTextFrame.parentStory.words.length));
                                                                  var myFootnote = myWord.insertionPoints.item(-1).contents = " Kvern ";
                                                             }
                                                             myNoCharacterStyle = myDocument.characterStyles.item("[None]");
                                                             try{
                                                                  myCharacterStyle = myDocument.characterStyles.item("kern");
                                                                  myCharacterStyle.name;
                                                             }
                                                             catch(myError){
                                                                  myCharacterStyle = myDocument.characterStyles.add({name:"kern"})
                                                             }
                                                             app.findTextPreferences = NothingEnum.nothing;
                                                             app.changeTextPreferences = NothingEnum.nothing;
                                                             app.findTextPreferences.findWhat = "Kvern";
                                                             app.changeTextPreferences.appliedCharacterStyle = myCharacterStyle;
                                                             myDocument.changeText();
                                                             app.findTextPreferences.findWhat = "vern";
                                                             app.findTextPreferences.appliedCharacterStyle = myCharacterStyle;
                                                             app.changeTextPreferences.appliedCharacterStyle = myNoCharacterStyle;
                                                             myDocument.changeText();
                                                             app.findTextPreferences.findWhat = "K"
                                                             app.changeTextPreferences.appliedCharacterStyle = myNoCharacterStyle;
                                                             app.changeTextPreferences.kerningValue = -40;
                                                             myDocument.changeText();
                                                             app.findTextPreferences = NothingEnum.nothing;
                                                             app.changeTextPreferences = NothingEnum.nothing;
                                                            //

                                                        }
                                                        function myTeardown(){
                                                        }
                                                        //
                                                        //This function gets a random number in the range myStart to myEnd.
                                                        function myGetRandom(myStart, myEnd){
                                                             var myRange = myEnd - myStart;
                                                             return myStart + Math.floor(Math.random()*myRange);
                                                        }
                                                        //

                                                        function myGetBounds(myDocument, myPage){
                                                             var myPageWidth = myDocument.documentPreferences.pageWidth;
                                                             var myPageHeight = myDocument.documentPreferences.pageHeight
                                                             if(myPage.side == PageSideOptions.leftHand){
                                                                  var myX2 = myPage.marginPreferences.left;
                                                                  var myX1 = myPage.marginPreferences.right;
                                                             }
                                                             else{
                                                                  var myX1 = myPage.marginPreferences.left;
                                                                  var myX2 = myPage.marginPreferences.right;
                                                             }
                                                             var myY1 = myPage.marginPreferences.top;
                                                             var myX2 = myPageWidth - myX2;
                                                             var myY2 = myPageHeight - myPage.marginPreferences.bottom;
                                                             return [myY1, myX1, myY2, myX2];
                                                        }


                                                        Thanks,

                                                        Ole
                                                        • 25. Re: [CS3][JS] beforeClose event listener problem
                                                          CTC Imaging Level 1
                                                          Actually if you try "myChar.kerningValue += -40;" to make it an increment, it does NOT work!?!?

                                                          It does work however if visible.

                                                           


                                                          It won't let you store the value either "myCharKern = myChar.kerningValue;" So I cannot calculate the increment.


                                                          It does NOT work event if visible. To get the value, it looks like you have to use insertionPoints.

                                                           


                                                          Hummmmm...

                                                           

                                                          FYI: This is not the 1st time I had to change += or -= in the code since we upgraded to CS3. Even if you ran the script as "app.scriptPreferences.version = 4.0;"

                                                           

                                                          On Thu, Oct 16, 2008 at 3:25 PM, Alexandre VERCAMMEN < alexvercammen@gmail.com> wrote:


                                                          I'll try. In that stripped module. I did before I contacted you and it did not!?!?





                                                          On Thu, Oct 16, 2008 at 2:58 PM, Kasyan Servetsky < member@adobeforums.com> wrote:

                                                          A new message was posted by Kasyan Servetsky in


                                                          InDesign Scripting --
                                                            [CS3][JS] beforeClose event listener problem

                                                          Alex,

                                                          When I use characters instead of insertionPoints, the error has gone.

                                                          var myChar = myAnswer[cpt].characters[1];
                                                          
                                                          myChar.kerningValue = -40;








                                                          View/reply at [CS3][JS] beforeClose event listener problem
                                                          Replies by email are OK.
                                                          Use the unsubscribe form to cancel your email subscription.




                                                          • 26. Re: [CS3][JS] beforeClose event listener problem
                                                            CTC Imaging Level 1
                                                            Ole,

                                                            I believe Iunderstood. My problem is I would like to increment the kerning. Altough not a must but easier. Also I prompt the user about the change which at that time he has the ability to change Globaly (document), Localy (selections he started with) or just the word itself. That is a function which includes the search/replace. So I would have to adapt to a new function and do the search/replace within the portion of the program where I am kerning. Then I would read the kerningValue ot the current selection, add the increment, create a characterStyle which is appplied to the replace portion of the search. Then afterwards remove the characterStyle replacing it with "none" keep formating. I would not have to step through the Result search...
                                                            Did I get it?
                                                            • 27. Re: [CS3][JS] beforeClose event listener problem
                                                              Kasyan Servetsky Level 5
                                                              Alex,

                                                              Can you place text cursor somewhere inside a hidden (overflowed) text and change kerning? Obviously, you cannot. So when I run your script in ESTK2, it stops and says – “kerningValue = Error: The property is not applicable in the curr...”. I think insertion points don’t live in overflowed text.
                                                              • 28. Re: [CS3][JS] beforeClose event listener problem
                                                                CTC Imaging Level 1
                                                                Good morning Kasyan,

                                                                Yes indeed, I agree. You can select, shrink the window to hide your cursor. And there it is, it won't work. BUT re-expand the window and the cursor is still positioned. I do understand the semantic however.
                                                                So I could try Ole's approach where as you do the search/replace you do your formatting through a characterStyle. The 1st occurrence of the "word" is usually visible, so I'll be able to grab the initial values, calculate the new kerning and store it in the style. Then do search/replace. Just need to re-write to modify the "prompt" function. problem is multiple kerning pairs.... YES there it is. 1st one IS VISIBLE, so calculate the values of kerning OUTSIDE of the loop, then in the loop apply the actual kerning to the characters. Which we KNOW works!!! I'll be trying that as soon as I am at work and send feedback.

                                                                Thank you for working on this
                                                                Thank you Ole for your advice. I believe this will work.
                                                                Alex
                                                                • 29. Re: [CS3][JS] beforeClose event listener problem
                                                                  CTC Imaging Level 1
                                                                  Yes it did work. Only if the 1st occurence is visible of course. Good enough since it would be the case 99% of the time.
                                                                  I do still have a problem w/ single character word, because I can only kern the front part of it. Which is not a problem with "visible" insertionPoints (front & back is possible).
                                                                  Also I need to make it work for x amount of pairs (using an array) for other instances I check for. IE: Compound names need kerning for "/" generaly, the "-" are fine.

                                                                  Thank you so much all for your help guys.

                                                                  Ole, what about InDesign crashing with the eventListener(Open)?
                                                                  Seems like a issue with that windows.add() located in the Handler.
                                                                  Don't stress about it, enjoy your weekend.

                                                                  Alex.
                                                                  • 30. Re: [CS3][JS] beforeClose event listener problem
                                                                    Jostify

                                                                    I had the same problem, and it took some effort to find out the real reason. Then the solution turned out to be very simple!

                                                                    The real problem is that a script triggered by the event "beforeClose" is run TWICE:

                                                                    First time it does work (at least in my case where I do an pdf-export from the document. ) Then the document is closed.

                                                                    The second time the script fails - since the document is closed by the first run.

                                                                    But you can stop the action the second run by referring to the name of the target.

                                                                    At the first the target name is the name of the window, including the zoom-info (for example "Documentname @ 58 %"). The second time the target name is identical to the document name.

                                                                     

                                                                    So here is my solution (in applescript):

                                                                     

                                                                    my doSomesthingWithDocumentOnClose(evt)

                                                                     

                                                                    on doSomesthingWithDocumentOnClose(pEvt)

                                                                      tell application "Adobe InDesign CS6"

                                                                      set targetName to name of parent of pEvt

                                                                      end tell

                                                                      if targetName contains " @" then

                                                                      -- do your stuff

                                                                      end if

                                                                    end doSomesthingWithDocumentOnClose