4
4
Fork 0
This repository has been archived on 2025-01-20. You can view files and clone it, but you cannot make any changes to its state, such as pushing and creating new issues, pull requests or comments.
json-photoshop-scripting/Utility-Scripts/Get-SVG-Code-from-Path/Get SVG Code from Path.js

409 lines
62 KiB
JavaScript
Raw Permalink Normal View History

2018-04-15 16:41:40 +02:00
/*
<javascriptresource>
<name>Get SVG Code from Path...</name>
<about>"Get SVG Code from Path" v1.1
Get SVG code from the currently selected path.
Utility script using the "JSON Action Manager" scripting library.
© 2015 Michel MARIANI.
</about>
<menu>automate</menu>
<category>JSON Action Manager Paths Utility</category>
</javascriptresource>
*/
//------------------------------------------------------------------------------
// File: Get SVG Code from Path.js
// Version: 1.1
// Release Date: 2015-11-27
// Copyright: © 2015 Michel MARIANI <http://www.tonton-pixel.com/blog/>
// Licence: GPL <http://www.gnu.org/licenses/gpl.html>
//------------------------------------------------------------------------------
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------
// Version History:
// 1.1:
// - Used new version 4.4.4 of jamEngine scripting library module.
// 1.0:
// - Initial release.
//------------------------------------------------------------------------------
// jamEngine.jsxinc v4.4.4 (minified)
if(typeof jamEngine!=='object') {var jamEngine={};(function() {var that;jamEngine.meaningfulIds=false;jamEngine.parseFriendly=false;jamEngine.displayDialogs=DialogModes.ERROR;var conflictingStringIdStrs={"'Algn'":["align","alignment"],"'AntA'":["antiAlias","antiAliasedPICTAcquire"],"'BckL'":["backgroundLayer","backgroundLevel"],"'BlcG'":["blackGenerationType","blackGenerationCurve"],"'BlcL'":["blackLevel","blackLimit"],"'Blks'":["blacks","blocks"],"'BlrM'":["blurMethod","blurMore"],"'BrgC'":["brightnessEvent","brightnessContrast"],"'BrsD'":["brushDetail","brushesDefine"],"'Brsh'":["brush","brushes"],"'Clcl'":["calculation","calculations"],"'ClrP'":["colorPalette","coloredPencil"],"'Cnst'":["constant","constrain"],"'CntC'":["centerCropMarks","conteCrayon"],"'Cntr'":["center","contrast"],"'CrtD'":["createDroplet","createDuplicate"],"'CstP'":["customPalette","customPhosphors"],"'Cstm'":["custom","customPattern"],"'Drkn'":["darken","darkness"],"'Dstr'":["distort","distortion","distribute","distribution"],"'Dstt'":["desaturate","destWhiteMax"],"'FlIn'":["fileInfo","fillInverse"],"'Gd '":["good","guide"],"'GnrP'":["generalPreferences","generalPrefs","preferencesClass"],"'GrSt'":["grainStippled","graySetup"],"'Grdn'":["gradientClassEvent","gridMinor"],"'Grn '":["grain","green"],"'Grns'":["graininess","greens"],"'HstP'":["historyPreferences","historyPrefs"],"'HstS'":["historyState","historyStateSourceType"],"'ImgP'":["imageCachePreferences","imagePoint"],"'In '":["in","stampIn"],"'IntW'":["interfaceWhite","intersectWith"],"'Intr'":["interfaceIconFrameDimmed","interlace","interpolation","intersect"],"'JPEG'":["JPEG","JPEGFormat"],"'LghD'":["lightDirection","lightDirectional"],"'LghO'":["lightOmni","lightenOnly"],"'LghS'":["lightSource","lightSpot"],"'Lns '":["lens","lines"],"'Mgnt'":["magenta","magentas"],"'MrgL'":["mergeLayers","mergedLayers"],"'Mxm '":["maximum","maximumQuality"],"'NTSC'":["NTSC","NTSCColors"],"'NmbL'":["numberOfLayers","numberOfLevels"],"'PlgP'":["pluginPicker","pluginPrefs"],"'Pncl'":["pencilEraser","pencilWidth"],"'Pnt '":["paint","point"],"'Prsp'":["perspective","perspectiveIndex"],"'PrvM'":["previewMacThumbnail","previewMagenta"],"'Pstr'":["posterization","posterize"],"'RGBS'":["RGBSetup","RGBSetupSource"],"'Rds '":["radius","reds"],"'ScrD'":["scratchDisks","screenDot"],"'ShdI'":["shadingIntensity","shadowIntensity"],"'ShpC'":["shapeCurveType","shapingCurve"],"'ShrE'":["sharpenEdges","shearEd"],"'Shrp'":["sharpen","sharpness"],"'SplC'":["splitChannels","supplementalCategories"],"'Spot'":["spot","spotColor"],"'SprS'":["separationSetup","sprayedStrokes"],"'StrL'":["strokeLength","strokeLocation"],"'Strt'":["saturation","start"],"'TEXT'":["char","textType"],"'TIFF'":["TIFF","TIFFFormat"],"'TglO'":["toggleOptionsPalette","toggleOthers"],"'TrnG'":["transparencyGamutPreferences","transparencyGrid","transparencyGridSize"],"'TrnS'":["transferSpec","transparencyShape","transparencyStop"],"'Trns'":["transparency","transparent"],"'TxtC'":["textClickPoint","textureCoverage"],"'TxtF'":["textureFile","textureFill"],"'UsrM'":["userMaskEnabled","userMaskOptions"],"'c@#^'":["inherits","pInherits"],"'comp'":["comp","sInt64"],"'doub'":["floatType","IEEE64BitFloatingPoint","longFloat"],"'long'":["integer","longInteger","sInt32"],"'magn'":["magnitude","uInt32"],"'null'":["null","target"],"'shor'":["sInt16","sMInt","shortInteger"],"'sing'":["IEEE32BitFloatingPoint","sMFloat","shortFloat"]};jamEngine.getConflictingStringIdStrs=function(charIdStr) {return conflictingStringIdStrs[charIdStr]||null;};jamEngine.uniIdStrToId=function(uniIdStr) {var id=0;if(typeof uniIdStr==='string') {if((uniIdStr.length===(1+4+1))&&(uniIdStr.charAt(0)==="'")&&(uniIdStr.charAt(5)==="'")) {id=app.charIDToTypeID(uniIdStr.substring(1,5));} else {id=app.stringIDToTypeID(uniIdStr);}} return id;};var smallestHashValue=app.charIDToTypeID(" ");jamEngine.idToUniIdStrs=function(id) {var charIdStr="";var stringIdStr=app.typeIDToStringID(id);if(id>=smallestHashValue) {charIdStr="'"+app.typeIDToCharID(id)+"'";if(stringIdStr!=="") {if(charIdStr in conflicting
// jamJSON.jsxinc v4.4 (minified)
if(typeof jamJSON!=='object') {var jamJSON={};(function() {var state;var stack;var container;var key;var value;var escapes={'\\':'\\','"':'"','/':'/','t':'\t','n':'\n','r':'\r','f':'\f','b':'\b'};var action={'{':{go:function() {stack.push({state:'ok'});container={};state='firstokey';},ovalue:function() {stack.push({container:container,state:'ocomma',key:key});container={};state='firstokey';},firstavalue:function() {stack.push({container:container,state:'acomma'});container={};state='firstokey';},avalue:function() {stack.push({container:container,state:'acomma'});container={};state='firstokey';}},'}':{firstokey:function() {var pop=stack.pop();value=container;container=pop.container;key=pop.key;state=pop.state;},ocomma:function() {var pop=stack.pop();container[key]=value;value=container;container=pop.container;key=pop.key;state=pop.state;}},'[':{go:function() {stack.push({state:'ok'});container=[];state='firstavalue';},ovalue:function() {stack.push({container:container,state:'ocomma',key:key});container=[];state='firstavalue';},firstavalue:function() {stack.push({container:container,state:'acomma'});container=[];state='firstavalue';},avalue:function() {stack.push({container:container,state:'acomma'});container=[];state='firstavalue';}},']':{firstavalue:function() {var pop=stack.pop();value=container;container=pop.container;key=pop.key;state=pop.state;},acomma:function() {var pop=stack.pop();container.push(value);value=container;container=pop.container;key=pop.key;state=pop.state;}},':':{colon:function() {if(container.hasOwnProperty(key)) {throw new SyntaxError("[jamJSON.parse] Duplicate key: “"+key+"”");} state='ovalue';}},',':{ocomma:function() {container[key]=value;state='okey';},acomma:function() {container.push(value);state='avalue';}},'true':{go:function() {value=true;state='ok';},ovalue:function() {value=true;state='ocomma';},firstavalue:function() {value=true;state='acomma';},avalue:function() {value=true;state='acomma';}},'false':{go:function() {value=false;state='ok';},ovalue:function() {value=false;state='ocomma';},firstavalue:function() {value=false;state='acomma';},avalue:function() {value=false;state='acomma';}},'null':{go:function() {value=null;state='ok';},ovalue:function() {value=null;state='ocomma';},firstavalue:function() {value=null;state='acomma';},avalue:function() {value=null;state='acomma';}}};var number={go:function() {state='ok';},ovalue:function() {state='ocomma';},firstavalue:function() {state='acomma';},avalue:function() {state='acomma';}};var string={go:function() {state='ok';},firstokey:function() {key=value;state='colon';},okey:function() {key=value;state='colon';},ovalue:function() {state='ocomma';},firstavalue:function() {state='acomma';},avalue:function() {state='acomma';}};var commentFunc=function(){};function debackslashify(text) {return text.replace(/\\(?:u(.{4})|([^u]))/g,function(a,b,c){return(b)?String.fromCharCode(parseInt(b,16)):escapes[c];});} jamJSON.parse=function(text,validate,allowComments) {if(validate) {var tx=/^[\x20\t\n\r]*(?:([,:\[\]{}]|true|false|null)|(-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+\-]?[0-9]+)?)|"((?:[^\r\n\t\\\"]|\\(?:["\\\/trnfb]|u[0-9a-fA-F]{4}))*)")/;var txc=/^[\x20\t\n\r]*(?:(\/(?:\/.*|\*(?:.|[\r\n])*?\*\/))|([,:\[\]{}]|true|false|null)|(-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+\-]?[0-9]+)?)|"((?:[^\r\n\t\\\"]|\\(?:["\\\/trnfb]|u[0-9a-fA-F]{4}))*)")/;var r;var i;var actionFunc;state='go';stack=[];try {while(true) {i=(allowComments)?1:0;r=(allowComments)?txc.exec(text):tx.exec(text);if(!r) {break;} if(allowComments&&r[1]) {actionFunc=commentFunc;} else if(r[i+1]) {actionFunc=action[r[i+1]][state];} else if(r[i+2]) {value=+r[i+2];actionFunc=number[state];} else {value=debackslashify(r[i+3]);actionFunc=string[state];} if(actionFunc) {actionFunc();text=text.slice(r[0].length);} else {break;}}} catch(e) {state=e;} if(state!=='ok'||/[^\x20\t\n\r]/.test(text)) {throw state instanceof SyntaxError?state:new SyntaxError("[jamJSON.parse] Invalid JSON");} return value;} else {return eval('('+text+')');}};var escapable=/[\\\"\x00-\x1F\x7F-\x9F\u00AD\u0600-\u0604
// jamShapes.jsxinc v4.4 (minified)
if(typeof jamShapes!=='object') {var jamShapes={};(function() {jamShapes.isCustomShapesFile=function(file) {return(file.type==='8BCS')||file.name.match(/\.csh$/i);};jamShapes.isCustomShapesPrefsFile=function(file) {return file.name.match(/^CustomShapes.psp$/i);};jamShapes.dataFromCustomShapesFile=function(shapesFile,shapeIndex) {function skipBytes(file,byteCount) {file.seek(byteCount,1);} function readBEInt(file,byteCount) {var bytes=file.read(byteCount);var intValue=0;for(var index=0;index<byteCount;index++) {intValue=(intValue<<8)+bytes.charCodeAt(index);} return intValue;} function readBytes(file,byteCount) {return file.read(byteCount);} function readPascalString(file) {var stringLength=readBEInt(file,1);return readBytes(file,stringLength);} function readUnicodeStringWithPadding(file) {var unicodeString="";var unicodeLength=readBEInt(file,4);for(var index=0;index<unicodeLength;index++) {var unicodeChar=readBEInt(file,2);if(unicodeChar!==0) {unicodeString+=String.fromCharCode(unicodeChar);}} if((unicodeLength%2)!==0) {skipBytes(file,2);} return unicodeString;} function readSignedBEInt32(file) {var intValue=readBEInt(file,4);return(intValue<0x80000000)?intValue:(intValue-0x100000000);} function readSignedBEFixed32(file) {return readSignedBEInt32(file)/0x1000000;} var file;if(typeof shapesFile==='string') {file=new File(shapesFile);} else if(shapesFile instanceof File) {file=shapesFile;} else {throw new Error('[jamShapes.dataFromCustomShapesFile] Invalid argument');} var selectorStrings=["closedLength","closedLinked","closedUnlinked","openLength","openLinked","openUnlinked","pathFill","clipboard","initialFill"];var fileData;if(file.open("r")) {try {file.encoding='BINARY';var magicNumber=file.read(4);if(magicNumber==='cush') {var fileVersion=readBEInt(file,4);if(fileVersion===2) {fileData={};fileData["fileVersion"]=fileVersion;var customShapes=[];var customShapeCount=readBEInt(file,4);for(var customShapeIndex=0;customShapeIndex<customShapeCount;customShapeIndex++) {var customShape={};customShape["name"]=localize(readUnicodeStringWithPadding(file));var unknown=jamUtils.dataToHexaString(readBytes(file,4));var dataLength=readBEInt(file,4);var dataStart=file.tell();customShape["ID"]=readPascalString(file);if((typeof shapeIndex==='undefined')||(shapeIndex===customShapeIndex)) {var top=readSignedBEInt32(file);var left=readSignedBEInt32(file);var bottom=readSignedBEInt32(file);var right=readSignedBEInt32(file);customShape["bounds"]=[top,left,bottom,right];var pathRecords=[];var pathRecordCount=Math.floor((dataStart+dataLength-file.tell())/(2+8+8+8));for(var pathRecordIndex=0;pathRecordIndex<pathRecordCount;pathRecordIndex++) {var pathRecord=[];var selector=readBEInt(file,2);if((selector>=0)&&(selector<selectorStrings.length)) {pathRecord.push(selectorStrings[selector]);} else {throw new Error("[jamShapes.dataFromCustomShapesFile] Unknown selector: "+selector);} switch(selector) {case 6:pathRecord.push(null);skipBytes(file,24);break;case 8:pathRecord.push(readBEInt(file,2));skipBytes(file,24-2);break;case 0:case 3:pathRecord.push(readBEInt(file,2));skipBytes(file,24-2);break;case 1:case 2:case 4:case 5:pathRecord.push ([[readSignedBEFixed32(file),readSignedBEFixed32(file)],[readSignedBEFixed32(file),readSignedBEFixed32(file)],[readSignedBEFixed32(file),readSignedBEFixed32(file)]]);break;default:pathRecord.push(null);skipBytes(file,24);break;} pathRecords.push(pathRecord);} customShape["pathRecords"]=pathRecords;} file.seek(dataStart+dataLength,0);customShapes.push(customShape);} fileData["customShapes"]=customShapes;} else {fileData="Unrecognized custom shapes file version: "+fileVersion;}} else {fileData="Unrecognized custom shapes file magic number: '"+magicNumber+"'";}} catch(e) {fileData=e.message;} finally {file.close();}} else {fileData="Cannot open file";} return fileData;};jamShapes.debugMode=false;jamShapes.pathComponentsFromCustomShape=function(customShape,shapeOperation,bounds,constrainProportions) {var rectangle=bounds[0];var unit=bounds[1];var left=rectangle[0];var top=rectangle[1];var right=rectangle[2];var bottom=
// jamUtils.jsxinc v4.4 (minified)
if(typeof jamUtils!=='object') {var jamUtils={};(function() {jamUtils.toDistanceUnit=function(amount,amountBasePerInch) {return(amount/amountBasePerInch)*72.0;};jamUtils.fromDistanceUnit=function(amount,amountBasePerInch) {return(amount/72.0)*amountBasePerInch;};jamUtils.fontExists=function(fontPostScriptName) {var useDOM=true;var found=false;if(useDOM) {for(var i=0;i<app.fonts.length;i++) {if(app.fonts[i].postScriptName===fontPostScriptName) {found=true;break;}}} else {var saveMeaningfulIds=jamEngine.meaningfulIds;var saveParseFriendly=jamEngine.parseFriendly;jamEngine.meaningfulIds=true;jamEngine.parseFriendly=true;var resultDescriptorObj=jamEngine.jsonGet ([["property",["<property>","fontList"]],["application",["<enumerated>",["ordinal","targetEnum"]]]]);var fontPostScriptNameArr=resultDescriptorObj["fontList"][1][1]["fontPostScriptName"][1];for(var i=0;i<fontPostScriptNameArr.length;i++) {if(fontPostScriptNameArr[i][1]===fontPostScriptName) {found=true;break;}} jamEngine.meaningfulIds=saveMeaningfulIds;jamEngine.parseFriendly=saveParseFriendly;} return found;};jamUtils.loadAction=function(action,actionSet,actionsFilePath) {try {jamEngine.jsonGet([["action",["<name>",action]],["actionSet",["<name>",actionSet]]]);var found=true;} catch(e) {var found=false;} if(!found) {jamEngine.jsonPlay("open",{"target":["<path>",actionsFilePath]});}};jamUtils.loadActionSet=function(actionSet,actionsFilePath) {try {jamEngine.jsonGet([["actionSet",["<name>",actionSet]]]);var found=true;} catch(e) {var found=false;} if(!found) {jamEngine.jsonPlay("open",{"target":["<path>",actionsFilePath]});}};jamUtils.loadPreset=function(presetProperty,presetName,presetFilePath) {var useDOM=false;var useOpen=true;var classes={"brush":"brush","colors":"color","gradientClassEvent":"gradientClassEvent","style":"styleClass","pattern":"'PttR'","shapingCurve":"shapingCurve","customShape":"customShape","toolPreset":"toolPreset"};var presetClass=classes[presetProperty];var saveMeaningfulIds=jamEngine.meaningfulIds;var saveParseFriendly=jamEngine.parseFriendly;jamEngine.meaningfulIds=true;jamEngine.parseFriendly=true;var found=false;var resultDescriptorObj=jamEngine.jsonGet ([["property",["<property>","presetManager"]],["application",["<enumerated>",["ordinal","targetEnum"]]]]);var presetManagerArr=resultDescriptorObj["presetManager"][1];for(var i=0;i<presetManagerArr.length;i++) {var presets=presetManagerArr[i][1];if(presets[0]===presetClass) {var presetsArr=presets[1]["name"][1];for(var j=0;j<presetsArr.length;j++) {if(presetsArr[j][1]===presetName) {found=true;break;}} break;}} if(!found) {if(useDOM) {app.load(new File(presetFilePath));} else if(useOpen) {jamEngine.jsonPlay("open",{"target":["<path>",presetFilePath]});} else {jamEngine.jsonPlay ("set",{"target":["<reference>",[["property",["<property>",presetProperty]],["application",["<enumerated>",["ordinal","targetEnum"]]]]],"to":["<path>",presetFilePath],"append":["<boolean>",true]});}} jamEngine.meaningfulIds=saveMeaningfulIds;jamEngine.parseFriendly=saveParseFriendly;};function getFileObject(file) {var fileObject;if(file instanceof File) {fileObject=file;} else if(typeof file==='string') {fileObject=new File(file);} else {throw new Error('[jamUtils getFileObject] Invalid argument');} return fileObject;} jamUtils.readTextFile=function(textFile) {var text=null;var file=getFileObject(textFile);if(file.open("r")) {text=file.read();file.close();} return text;};jamUtils.readJsonFile=function(jsonFile) {return jamJSON.parse(this.readTextFile(jsonFile),true);};jamUtils.writeTextFile=function(textFile,text) {var file=getFileObject(textFile);if(file.open('w','TEXT')) {file.encoding='UTF-8';file.lineFeed='unix';file.write('\uFEFF');file.write(text);file.close();}};jamUtils.writeJsonFile=function(jsonFile,data,space) {this.writeTextFile(jsonFile,jamJSON.stringify(data,space));};jamUtils.cloneData=function(data) {var clone;if(data===null) {clone=data;} else if(data.constructor===Object) {clone={};for(var k in data) {if(data.hasOwnProperty(k)) {clone[k]=this.cloneData(data[k]);}}} else if(data.constructor===Array)
//------------------------------------------------------------------------------
jamEngine.meaningfulIds = true;
jamEngine.parseFriendly = true;
//------------------------------------------------------------------------------
var promptString = "Save to SVG file:";
var signature = "json-action-manager-get-svg-code-from-path-options";
var defaultOptions =
{
defaultFile: "~/Desktop/photoshop-path.svg",
dialogWidth: 1024,
dialogHeight: 768,
dialogX: 0,
dialogY: 0
};
var defaultFile = new File (defaultOptions.defaultFile);
//------------------------------------------------------------------------------
function displayDialog (customOptions, code)
{
// Get an available UI font among a list of favorites
function getAvailableUIFont (fontsArray)
{
// List all fonts available in Photoshop in JSON format
var fontsObj = { };
for (var i = 0; i < app.fonts.length; i++)
{
var family = app.fonts[i].family;
if (!(family in fontsObj))
{
fontsObj[family] = { };
}
fontsObj[family][app.fonts[i].style] =
{
"name": app.fonts[i].name
};
}
var availableFont;
var fontFamily;
var fontStyle;
var fontSize;
for (var i = 0; i < fontsArray.length; i++)
{
fontFamily = fontsArray[i][0];
if (fontFamily in fontsObj)
{
fontStyle = fontsArray[i][1];
if (fontStyle in fontsObj[fontFamily])
{
fontSize = fontsArray[i][2];
availableFont = ScriptUI.newFont (fontFamily, fontStyle, fontSize)
break;
}
}
}
return availableFont;
}
var monospacedFont =
getAvailableUIFont
(
[
[ "Monaco", "Regular", 12 ],
[ "Lucida Sans Typewriter", "Regular", 14 ],
[ "Courier", "Regular", 16 ],
[ "Courier New", "Regular", 14 ]
]
);
defaultFile = new File (customOptions.defaultFile);
var dialog = new Window ('dialog', "Get SVG Code from Path", undefined, { resizeable: true });
dialog.orientation = "column";
dialog.preferredSize.width = customOptions.dialogWidth;
dialog.preferredSize.height = customOptions.dialogHeight;
dialog.onResizing = function ()
{
this.layout.resize ();
};
dialog.onShow = function ()
{
var x = customOptions.dialogX;
var y = customOptions.dialogY;
if ((x !== 0) || (y !== 0))
{
this.location.x = x;
this.location.y = y;
}
codeArea.text = code;
};
var codeGroup = dialog.add ('group');
codeGroup.orientation = "column";
codeGroup.alignment = [ "fill", "fill" ];
var codeArea = codeGroup.add ('edittext', undefined, "", { multiline: true, readonly: true });
codeArea.alignment = [ "fill", "fill" ];
codeArea.minimumSize = [ -1, 64 ];
if (monospacedFont)
{
codeArea.graphics.font = monospacedFont;
}
var actionButtonsGroup = codeGroup.add ('group');
actionButtonsGroup.alignment = [ "center", "bottom" ];
actionButtonsGroup.orientation = "row";
actionButtonsGroup.alignChildren = "fill";
var file;
var saveButton = actionButtonsGroup.add ('button', undefined, 'Save...');
saveButton.onClick = function ()
{
file = defaultFile.saveDlg (promptString);
if (file)
{
jamUtils.writeTextFile (file, code);
defaultFile = file;
}
};
var buttonsGroup = dialog.add ('group');
buttonsGroup.alignment = [ "right", "bottom" ];
buttonsGroup.orientation = "row";
buttonsGroup.alignChildren = "fill";
var cancelButton = buttonsGroup.add ('button', undefined, 'Cancel', { name: "cancel" });
cancelButton.onClick = function ()
{
dialog.close (false);
};
var okButton = buttonsGroup.add ('button', undefined, 'OK', { name: "ok" });
okButton.onClick = function ()
{
customOptions.defaultFile = defaultFile.fsName;
customOptions.dialogWidth = dialog.size.width;
customOptions.dialogHeight = dialog.size.height;
customOptions.dialogX = dialog.location.x;
customOptions.dialogY = dialog.location.y;
dialog.close (true);
};
return dialog.show ();
}
//------------------------------------------------------------------------------
function getPresetCustomShapesCount ()
{
var resultDescObj = jamEngine.jsonGet
(
[
[ "property", [ "<property>", "presetManager" ] ],
[ "application", [ "<enumerated>", [ "ordinal", "targetEnum" ] ] ]
]
);
var presetManagerArr = resultDescObj["presetManager"][1];
var presetCustomShapesCount;
for (var i = 0; i < presetManagerArr.length; i++)
{
var preset = presetManagerArr[i][1];
if (preset[0] === "customShape")
{
presetCustomShapesCount = preset[1]["name"][1].length;
break;
}
}
return presetCustomShapesCount;
}
//------------------------------------------------------------------------------
function getSVGCodefromCurrentPath (shiftStr)
{
var svgCode = null;
//
var presetCustomShapesCountBefore = getPresetCustomShapesCount ();
//
var date = new Date ();
var tempCustomShapesName = "Temp-Custom-Shapes-" + date.getTime ();
//
try
{
jamEngine.jsonPlay
(
"make",
{
"target": [ "<reference>", [ [ "customShape", [ "<class>", null ] ] ] ],
"name": [ "<string>", tempCustomShapesName ],
"using":
{
"<reference>":
[
{ "property": { "<property>": "selection" } },
{ "document": { "<enumerated>": { "ordinal": "targetEnum" } } }
]
}
}
);
}
catch (e)
{
}
//
var presetCustomShapesCount = getPresetCustomShapesCount ();
//
// To confirm that a custom shapes preset has effectively been created
// (not the case if the path is made of incompatible shape operations, for instance, or if the path is empty).
if (presetCustomShapesCount === (presetCustomShapesCountBefore + 1))
{
var tempCustomShapesFile = new File (Folder.temp + "/" + tempCustomShapesName + ".csh");
jamEngine.jsonPlay
(
"set",
{
"target": [ "<path>", tempCustomShapesFile.fsName ],
"to": [ "<list>", [ [ "<reference>", [ [ "customShape", [ "<index>", presetCustomShapesCount ] ] ] ] ] ]
}
);
//
jamEngine.jsonPlay
(
"delete",
{
"target": [ "<list>", [ [ "<reference>", [ [ "customShape", [ "<index>", presetCustomShapesCount ] ] ] ] ] ]
}
);
//
var customShapes = jamShapes.dataFromCustomShapesFile (tempCustomShapesFile)["customShapes"];
if (customShapes && (customShapes.length === 1))
{
var customShape = customShapes[0];
var bounds = customShape["bounds"];
var top = bounds[0];
var left = bounds[1];
var bottom = bounds[2];
var right = bounds[3];
var width = right - left;
var height = bottom - top;
svgCode = '<svg xmlns="http://www.w3.org/2000/svg" ';
svgCode += 'viewBox="' + 0 + ' ' + 0 + ' ' + width + ' ' + height + '">' + '\n';
svgCode += '<path ';
svgCode += 'fill-rule="' + "evenodd" + '" ';
svgCode += 'd="' + '\n';
var pathRecords = customShape["pathRecords"];
var subLength = 0;
for (var pathRecordIndex = 0; pathRecordIndex < pathRecords.length; pathRecordIndex++)
{
var pathRecord = pathRecords[pathRecordIndex];
var selector = pathRecord[0];
var data = pathRecord[1];
switch (selector)
{
case "closedLength":
case "openLength":
subLength = data;
var closedSubpath = (selector === "closedLength");
var subpath = [ ];
break;
case "closedLinked":
case "closedUnlinked":
case "openLinked":
case "openUnlinked":
var backward = [ data[0][1] * width, data[0][0] * height ];
var anchor = [ data[1][1] * width, data[1][0] * height ];
var forward = [ data[2][1] * width, data[2][0] * height ];
subpath.push ({ "backward": backward, "forward": forward, "anchor": anchor });
if (--subLength === 0)
{
var firstBackward = null;
var firstAnchor = null;
var prevForward = null;
for (var subpathIndex = 0; subpathIndex < subpath.length; subpathIndex++)
{
var pathPoint = subpath[subpathIndex];
if (subpathIndex === 0)
{
svgCode += shiftStr + 'M ' + pathPoint["anchor"] + '\n';
firstBackward = pathPoint["backward"];
firstAnchor = pathPoint["anchor"];
}
else
{
svgCode += shiftStr + 'C ' + prevForward + ' ' + pathPoint["backward"] + ' ' + pathPoint["anchor"] + '\n';
}
prevForward = pathPoint["forward"];
}
if (closedSubpath)
{
svgCode += shiftStr + 'C ' + prevForward + ' ' + firstBackward + ' ' + firstAnchor + '\n';
svgCode += shiftStr + 'Z' + '\n';
}
}
break;
}
}
svgCode += '" />' + '\n';
svgCode += '</svg>' + '\n';
}
//
tempCustomShapesFile.remove ();
}
return svgCode;
}
//------------------------------------------------------------------------------
function main ()
{
var appVersion = parseInt (app.version);
if (appVersion >= 10) // CS3
{
var hasCurrentPath = true;
try
{
jamEngine.jsonGet ([ [ "path", [ "<enumerated>", [ "ordinal", "targetEnum" ] ] ] ]);
}
catch (e)
{
hasCurrentPath = false;
}
if (hasCurrentPath)
{
var customOptions = jamUtils.getCustomOptions (signature, defaultOptions);
var svgCode = getSVGCodefromCurrentPath ('\t');
if (svgCode)
{
if (displayDialog (customOptions, svgCode))
{
jamUtils.putCustomOptions (signature, customOptions, true);
}
}
else
{
alert ("Cannot get SVG code from path.");
}
}
else
{
alert ("No path selected.");
}
}
else
{
alert ("Sorry, this script requires Photoshop CS3 or later.");
}
}
//------------------------------------------------------------------------------
try
{
main ();
}
catch (e)
{
alert (e);
}
//------------------------------------------------------------------------------