mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 20:18:38 -05:00
661 lines
41 KiB
Rust
661 lines
41 KiB
Rust
//! Every global and member the script host (`script.run`) adds to the JavaScript engine is in one of
|
||
//! the tables below, and each name that reaches outside the document has the `outside` id
|
||
//! `script.check` (`vectorcraft-scriptcheck`) gives it. The names are read from a run: the own
|
||
//! properties of the global object, of each object or function it holds and of each function's
|
||
//! `prototype`, with a setter listed again as `name=`. The names a plain `vectorcraft_js::Realm` with
|
||
//! E4X also has are the language's, which reach files and other apps only through the host; `eval` and
|
||
//! `Function` still have rows, since they run code the checker can't read. A name the host adds
|
||
//! without a row fails the test.
|
||
|
||
use std::collections::BTreeSet;
|
||
|
||
use serde_json::json;
|
||
use vectorcraft_engine::Session;
|
||
use vectorcraft_js::{DirectiveName, JsValue, Options, Realm};
|
||
use vectorcraft_scriptcheck::{Limits, check};
|
||
|
||
/// The names that reach outside the document: each with a script that uses it and the `outside` id
|
||
/// the checker gives that script.
|
||
const OUTSIDE: &[(&str, &str, &str)] = &[
|
||
("eval", "eval(s);", "unseenCode"),
|
||
("Function", "var g = new Function(s);", "unseenCode"),
|
||
("$.evalFile", "$.evalFile(p);", "unseenCode"),
|
||
("$.getenv", "var h = $.getenv(n);", "environment"),
|
||
("$.setenv", "$.setenv(n, v);", "environment"),
|
||
("File.prototype.open", "var f = new File(p); f.open('w');", "filesWritten"),
|
||
("File.prototype.write", "var f = new File(p); f.write(s);", "filesWritten"),
|
||
("File.prototype.writeln", "var f = new File(p); f.writeln(s);", "filesWritten"),
|
||
("File.prototype.copy", "var f = new File(p); f.copy(q);", "filesWritten"),
|
||
("File.prototype.createAlias", "var f = new File(p); f.createAlias(q);", "filesWritten"),
|
||
("File.prototype.remove", "var f = new File(p); f.remove();", "filesWritten"),
|
||
("File.prototype.rename", "var f = new File(p); f.rename(q);", "filesWritten"),
|
||
("File.prototype.length=", "var f = new File(p); f.length = 0;", "filesWritten"),
|
||
("File.prototype.hidden=", "var f = new File(p); f.hidden = true;", "filesWritten"),
|
||
("File.prototype.readonly=", "var f = new File(p); f.readonly = true;", "filesWritten"),
|
||
("File.prototype.execute", "var f = new File(p); f.execute();", "filesOpened"),
|
||
("Folder.prototype.create", "var d = new Folder(p); d.create();", "filesWritten"),
|
||
("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"),
|
||
("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"),
|
||
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
|
||
("Preferences.prototype.setBooleanPreference", "app.preferences.setBooleanPreference(k, true);", "preferences"),
|
||
("Preferences.prototype.setIntegerPreference", "app.preferences.setIntegerPreference(k, 1);", "preferences"),
|
||
("Preferences.prototype.setRealPreference", "app.preferences.setRealPreference(k, 0.5);", "preferences"),
|
||
("Preferences.prototype.setStringPreference", "app.preferences.setStringPreference(k, s);", "preferences"),
|
||
("Preferences.prototype.removePreference", "app.preferences.removePreference(k);", "preferences"),
|
||
("Document.prototype.print", "var o = new PrintOptions(); o.jobOptions.file = new File(p); app.activeDocument.print(o);", "filesWritten"),
|
||
("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"),
|
||
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
|
||
("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"),
|
||
("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"),
|
||
("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"),
|
||
];
|
||
|
||
/// The names the host adds that stay inside the document and the run, by the object that has them.
|
||
/// Reading a file or a folder, a file dialog, a message to the person and a ScriptUI dialog do not
|
||
/// change anything outside it. The document model (`app`, its classes and the enumerations) acts on
|
||
/// the open documents; `Document.close` closes a document, and saves it to its own file only when it
|
||
/// is given `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and
|
||
/// `Document.path` only name its file and folder. `app.open` reads the file it is given, and
|
||
/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. Reading a
|
||
/// preference changes nothing, and the matrix functions return new records. `app.copy` and `app.cut`
|
||
/// fill VectorCraft's clipboard, which the desktop app offers to other apps after the run as Edit ›
|
||
/// Copy does.
|
||
const INSIDE: &[(&str, &str)] = &[
|
||
("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"),
|
||
("Window.", "alert confirm length prompt prototype"),
|
||
("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show"),
|
||
("Object.prototype.", "reflect toSource"),
|
||
("UnitValue.", "baseUnit baseUnit= length prototype"),
|
||
("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="),
|
||
("localize.", "length"),
|
||
("toSource.", "length"),
|
||
("ExternalObject.", "length prototype search"),
|
||
("ExternalObject.prototype.", "constructor terminate"),
|
||
(
|
||
"$.",
|
||
"about appEncoding appEncoding= bp build buildDate colorPicker decimalPoint engineName error fileName flags \
|
||
flags= gc global hiresTimer includePath level line locale locale= localize localize= memCache memCache= os screens \
|
||
sleep stack strict version write writeln",
|
||
),
|
||
("File.", "decode encode fs isEncodingAvailable openDialog saveDialog length prototype"),
|
||
(
|
||
"File.prototype.",
|
||
"absoluteURI alias changePath close constructor created creator displayName encoding encoding= eof error error= \
|
||
exists fsName fullName getRelativeURI hidden length lineFeed lineFeed= localizedName modified name openDlg parent path read \
|
||
readch readln readonly relativeURI resolve saveDlg seek tell toString type",
|
||
),
|
||
(
|
||
"Folder.",
|
||
"appData appPackage commonFiles current current= decode desktop encode fs isEncodingAvailable length myDocuments \
|
||
prototype selectDialog startup system temp trash userData",
|
||
),
|
||
(
|
||
"Folder.prototype.",
|
||
"absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \
|
||
getRelativeURI localizedName modified name parent path relativeURI resolve selectDlg toString",
|
||
),
|
||
(
|
||
"",
|
||
"activeDocument activeDocument= app Application Artboard Artboards BlendModes CompoundPathItem CompoundPathItems \
|
||
CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
|
||
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement \
|
||
GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints \
|
||
PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \
|
||
selection= StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod",
|
||
),
|
||
("Application.", "prototype"),
|
||
(
|
||
"Application.prototype.",
|
||
"activeDocument activeDocument= beep beep= concatenateMatrix concatenateRotationMatrix concatenateScaleMatrix \
|
||
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents doScript \
|
||
executeMenuCommand getIdentityMatrix getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix \
|
||
invertMatrix isEqualMatrix isSingularMatrix loadAction loadAction= open paste PPDFileList preferences printPresetsList \
|
||
printerList redo redraw selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= \
|
||
userInteractionLevel \
|
||
userInteractionLevel=",
|
||
),
|
||
("Preferences.", "prototype"),
|
||
("Preferences.prototype.", "constructor getBooleanPreference getIntegerPreference getRealPreference getStringPreference typename"),
|
||
("DocumentPreset.", "prototype"),
|
||
(
|
||
"DocumentPreset.prototype.",
|
||
"artboardLayout artboardLayout= artboardRowsOrCols artboardRowsOrCols= artboardSpacing artboardSpacing= colorMode \
|
||
colorMode= constructor documentBleedLink documentBleedLink= documentBleedOffsetRect documentBleedOffsetRect= height \
|
||
height= numArtboards numArtboards= previewMode previewMode= rasterResolution rasterResolution= title title= \
|
||
toString transparencyGrid transparencyGrid= typename units units= width width=",
|
||
),
|
||
("Documents.", "prototype"),
|
||
("Documents.prototype.", "add addDocument addDocumentNoUI constructor getByName index length parent toString typename"),
|
||
("Document.", "prototype"),
|
||
(
|
||
"Document.prototype.",
|
||
"activeLayer activeLayer= artboards characterStyles close compoundPathItems constructor convertCoordinate \
|
||
defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \
|
||
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
|
||
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
|
||
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
|
||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \
|
||
height layers name pageItems paragraphStyles parent path pathItems placedItems rasterItems rulerOrigin \
|
||
rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
|
||
symbols symbols= tags textFrames toString typename views width",
|
||
),
|
||
("Views.", "prototype"),
|
||
("Views.prototype.", "constructor index length parent toString typename"),
|
||
("View.", "prototype"),
|
||
("View.prototype.", "bounds centerPoint centerPoint= constructor parent screenMode screenMode= toString typename zoom zoom="),
|
||
("Layer.", "prototype"),
|
||
(
|
||
"Layer.prototype.",
|
||
"artworkKnockout artworkKnockout= blendingMode blendingMode= color color= compoundPathItems constructor \
|
||
dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \
|
||
locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \
|
||
preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \
|
||
textFrames= toString typename visible visible= zOrder zOrderPosition",
|
||
),
|
||
("Layers.", "prototype"),
|
||
("Layers.prototype.", "add constructor getByName index length parent removeAll toString typename"),
|
||
("GroupItem.", "prototype"),
|
||
(
|
||
"GroupItem.prototype.",
|
||
"clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \
|
||
rasterItems rasterItems= symbolItems symbolItems= textFrames textFrames=",
|
||
),
|
||
("GroupItems.", "prototype"),
|
||
("GroupItems.prototype.", "add constructor createFromFile createFromFile= getByName index length parent removeAll toString typename"),
|
||
("CompoundPathItem.", "prototype"),
|
||
("CompoundPathItem.prototype.", "constructor pathItems"),
|
||
("CompoundPathItems.", "prototype"),
|
||
("CompoundPathItems.prototype.", "add constructor getByName index length parent removeAll toString typename"),
|
||
("Artboard.", "prototype"),
|
||
(
|
||
"Artboard.prototype.",
|
||
"artboardRect artboardRect= constructor name name= parent remove rulerOrigin rulerOrigin= rulerPAR rulerPAR= \
|
||
showCenter showCenter= showCrossHairs showCrossHairs= showSafeAreas showSafeAreas= toString typename",
|
||
),
|
||
("Artboards.", "prototype"),
|
||
(
|
||
"Artboards.prototype.",
|
||
"add constructor getActiveArtboardIndex getByName index insert length parent remove setActiveArtboardIndex \
|
||
toString typename",
|
||
),
|
||
("PageItems.", "prototype"),
|
||
("PageItems.prototype.", "constructor getByName index length parent removeAll toString typename"),
|
||
("PageItem.", "prototype"),
|
||
(
|
||
"PageItem.prototype.",
|
||
"artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \
|
||
controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer left \
|
||
left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \
|
||
position= remove resize rotate selected selected= sliced sliced= tags toString top top= transform translate \
|
||
typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
|
||
width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition",
|
||
),
|
||
("PlacedItems.", "prototype"),
|
||
("PlacedItems.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||
("PlacedItem.", "prototype"),
|
||
("PlacedItem.prototype.", "boundingBox constructor contentVariable contentVariable= embed file file= matrix matrix= relink trace"),
|
||
("PluginItem.", "prototype"),
|
||
("PluginItem.prototype.", "constructor isTracing tracing"),
|
||
("RasterItems.", "prototype"),
|
||
("RasterItems.prototype.", "constructor getByName index length parent removeAll typename"),
|
||
("RasterItem.", "prototype"),
|
||
(
|
||
"RasterItem.prototype.",
|
||
"bitsPerChannel boundingBox channels colorants colorants= colorize colorize= colorizedGrayscale constructor \
|
||
contentVariable contentVariable= embedded embedded= file imageColorSpace matrix matrix= overprint overprint= status \
|
||
trace transparent",
|
||
),
|
||
("TracingObject.", "prototype"),
|
||
(
|
||
"TracingObject.prototype.",
|
||
"anchorCount areaCount areaCount= constructor expandTracing imageResolution parent pathCount releaseTracing sourceArt \
|
||
tracingOptions typename usedColorCount",
|
||
),
|
||
("TracingOptions.", "prototype"),
|
||
(
|
||
"TracingOptions.prototype.",
|
||
"constructor cornerAngle cornerAngle= fills fills= ignoreWhite ignoreWhite= livePaintOutput livePaintOutput= \
|
||
loadFromPreset maxColors maxColors= maxStrokeWeight maxStrokeWeight= minArea minArea= minStrokeLength \
|
||
minStrokeLength= outputToSwatches outputToSwatches= palette palette= parent pathFitting pathFitting= \
|
||
preprocessBlur preprocessBlur= preset resample resample= resampleResolution resampleResolution= storeToPreset \
|
||
strokes strokes= threshold threshold= tracingMode tracingMode= typename viewRaster viewRaster= viewVector \
|
||
viewVector=",
|
||
),
|
||
("PathItems.", "prototype"),
|
||
(
|
||
"PathItems.prototype.",
|
||
"add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star toString typename",
|
||
),
|
||
("PathItem.", "prototype"),
|
||
(
|
||
"PathItem.prototype.",
|
||
"area clipping closed closed= constructor evenodd evenodd= fillColor fillColor= fillOverprint fillOverprint= filled \
|
||
filled= guides guides= length pathPoints polarity polarity= resolution resolution= selectedPathPoints \
|
||
setEntirePath strokeCap strokeCap= strokeColor strokeColor= strokeDashOffset strokeDashOffset= \
|
||
strokeDashes strokeDashes= strokeJoin strokeJoin= strokeMiterLimit strokeMiterLimit= strokeOverprint strokeOverprint= \
|
||
strokeWidth strokeWidth= stroked stroked=",
|
||
),
|
||
("PathPoints.", "prototype"),
|
||
("PathPoints.prototype.", "add constructor index length parent removeAll typename"),
|
||
("PathPoint.", "prototype"),
|
||
(
|
||
"PathPoint.prototype.",
|
||
"anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \
|
||
rightDirection= selected selected= typename",
|
||
),
|
||
("Tags.", "prototype"),
|
||
("Tags.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||
("Tag.", "prototype"),
|
||
("Tag.prototype.", "constructor name name= parent remove typename value value="),
|
||
(
|
||
"BlendModes.",
|
||
"COLORBLEND COLORBURN COLORDODGE DARKEN DIFFERENCE EXCLUSION HARDLIGHT HUE LIGHTEN LUMINOSITY MULTIPLY NORMAL \
|
||
OVERLAY SATURATIONBLEND SCREEN SOFTLIGHT",
|
||
),
|
||
("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"),
|
||
("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"),
|
||
("DocumentColorSpace.", "CMYK RGB"),
|
||
("DocumentPresetType.", "BasicCMYK BasicRGB Mobile Print Video Web"),
|
||
("DocumentPreviewMode.", "DefaultPreview OverprintPreview PixelPreview"),
|
||
("DocumentRasterResolution.", "HighResolution MediumResolution ScreenResolution"),
|
||
(
|
||
"DocumentTransparencyGrid.",
|
||
"TransparencyGridBlue TransparencyGridDark TransparencyGridGreen TransparencyGridLight TransparencyGridMedium \
|
||
TransparencyGridNone TransparencyGridOrange TransparencyGridPurple TransparencyGridRed",
|
||
),
|
||
("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"),
|
||
("PathPointSelection.", "ANCHORPOINT LEFTDIRECTION LEFTRIGHTPOINT NOSELECTION RIGHTDIRECTION"),
|
||
("PointType.", "CORNER SMOOTH"),
|
||
("PolarityValues.", "NEGATIVE POSITIVE"),
|
||
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
|
||
("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"),
|
||
("StrokeCap.", "BUTTENDCAP PROJECTINGENDCAP ROUNDENDCAP"),
|
||
("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"),
|
||
("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"),
|
||
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
|
||
// The enumerations of saving, exporting and opening.
|
||
(
|
||
"",
|
||
"ColorConversion ColorDestination ColorProfile Compatibility CompressionQuality DownsampleMethod EPSPostScriptLevelEnum \
|
||
EPSPreview ExportType MonochromeCompression OutputFlattening PDFBoxType PDFChangesAllowedEnum PDFCompatibility \
|
||
PDFOverprint PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes SVGCSSPropertyLocation SVGDTDVersion \
|
||
SVGDocumentEncoding SVGFontSubsetting SVGFontType SaveOptions UserInteractionLevel",
|
||
),
|
||
("", "AutoCADColors AutoCADCompatibility AutoCADExportFileFormat AutoCADExportOption AutoCADRasterFormat AutoCADUnit"),
|
||
("AutoCADColors.", "Max16Colors Max256Colors Max8Colors TrueColors"),
|
||
("AutoCADCompatibility.", "AutoCADRelease13 AutoCADRelease14 AutoCADRelease15 AutoCADRelease18 AutoCADRelease21 AutoCADRelease24"),
|
||
("AutoCADExportFileFormat.", "DWG DXF"),
|
||
("AutoCADExportOption.", "MaximizeEditability PreserveAppearance"),
|
||
("AutoCADRasterFormat.", "JPEG PNG"),
|
||
("AutoCADUnit.", "Centimeters Inches Millimeters Picas Pixels Points"),
|
||
("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"),
|
||
(
|
||
"ColorDestination.",
|
||
"COLORDESTINATIONDOCCMYK COLORDESTINATIONDOCRGB COLORDESTINATIONPROFILE COLORDESTINATIONWORKINGCMYK \
|
||
COLORDESTINATIONWORKINGRGB None",
|
||
),
|
||
("ColorProfile.", "INCLUDEALLPROFILE INCLUDEDESTPROFILE INCLUDERGBPROFILE LEAVEPROFILEUNCHANGED None"),
|
||
(
|
||
"CompressionQuality.",
|
||
"AUTOMATICJPEG2000HIGH AUTOMATICJPEG2000LOSSLESS AUTOMATICJPEG2000LOW AUTOMATICJPEG2000MAXIMUM AUTOMATICJPEG2000MEDIUM \
|
||
AUTOMATICJPEG2000MINIMUM AUTOMATICJPEGHIGH AUTOMATICJPEGLOW AUTOMATICJPEGMAXIMUM AUTOMATICJPEGMEDIUM AUTOMATICJPEGMINIMUM \
|
||
JPEG2000HIGH JPEG2000LOSSLESS JPEG2000LOW JPEG2000MAXIMUM JPEG2000MEDIUM JPEG2000MINIMUM JPEGHIGH JPEGLOW JPEGMAXIMUM \
|
||
JPEGMEDIUM JPEGMINIMUM None ZIP4BIT ZIP8BIT",
|
||
),
|
||
("DownsampleMethod.", "AVERAGEDOWNSAMPLE BICUBICDOWNSAMPLE NODOWNSAMPLE SUBSAMPLE"),
|
||
("MonochromeCompression.", "CCIT3 CCIT4 MONOZIP None RUNLENGTH"),
|
||
("OutputFlattening.", "PRESERVEAPPEARANCE PRESERVEPATHS"),
|
||
(
|
||
"PDFChangesAllowedEnum.",
|
||
"CHANGE128ANYCHANGES CHANGE128COMMENTING CHANGE128EDITPAGE CHANGE128FILLFORM CHANGE128NONE CHANGE40ANYCHANGES \
|
||
CHANGE40COMMENTING CHANGE40NONE CHANGE40PAGELAYOUT",
|
||
),
|
||
("PDFPrintAllowedEnum.", "PRINT128HIGHRESOLUTION PRINT128LOWRESOLUTION PRINT128NONE PRINT40HIGHRESOLUTION PRINT40NONE"),
|
||
("PDFTrimMarkWeight.", "TRIMMARKWEIGHT0125 TRIMMARKWEIGHT025 TRIMMARKWEIGHT05"),
|
||
("PDFXStandard.", "PDFX1A2001 PDFX1A2003 PDFX32002 PDFX32003 PDFX42007 PDFXNONE"),
|
||
("PageMarksTypes.", "Japanese Roman"),
|
||
("SVGCSSPropertyLocation.", "ENTITIES PRESENTATIONATTRIBUTES STYLEATTRIBUTES STYLEELEMENTS"),
|
||
("SVGDTDVersion.", "SVG1_0 SVG1_1 SVGBASIC1_1 SVGTINY1_1 SVGTINY1_1PLUS SVGTINY1_2"),
|
||
("SVGDocumentEncoding.", "ASCII UTF16 UTF8"),
|
||
("SVGFontSubsetting.", "ALLGLYPHS COMMONENGLISH COMMONROMAN GLYPHSUSED GLYPHSUSEDPLUSENGLISH GLYPHSUSEDPLUSROMAN None"),
|
||
("SVGFontType.", "CEFFONT OUTLINEFONT SVGFONT"),
|
||
(
|
||
"Compatibility.",
|
||
"ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \
|
||
ILLUSTRATOR19 ILLUSTRATOR8 ILLUSTRATOR9 JAPANESEVERSION3",
|
||
),
|
||
("EPSPostScriptLevelEnum.", "LEVEL2 LEVEL3"),
|
||
("EPSPreview.", "BWTIFF COLORTIFF None TRANSPARENTCOLORTIFF"),
|
||
("ExportType.", "AUTOCAD AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"),
|
||
("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"),
|
||
("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"),
|
||
("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"),
|
||
("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"),
|
||
("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"),
|
||
// The enumerations of placed and raster items.
|
||
("", "ImageColorSpace RasterLinkState"),
|
||
("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"),
|
||
("RasterLinkState.", "DATAFROMFILE DATAMODIFIED NODATA"),
|
||
// The enumerations of tracings.
|
||
("", "TracingModeType ViewRasterType ViewVectorType"),
|
||
("TracingModeType.", "TRACINGMODEBLACKANDWHITE TRACINGMODECOLOR TRACINGMODEGRAY"),
|
||
("ViewRasterType.", "TRACINGVIEWRASTERADJUSTEDIMAGE TRACINGVIEWRASTERNOIMAGE TRACINGVIEWRASTERORIGINALIMAGE TRACINGVIEWRASTERTRANSPARENTIMAGE"),
|
||
(
|
||
"ViewVectorType.",
|
||
"TRACINGVIEWVECTORNOTRACINGRESULT TRACINGVIEWVECTOROUTLINES TRACINGVIEWVECTOROUTLINESWITHTRACING \
|
||
TRACINGVIEWVECTORTRACINGRESULT",
|
||
),
|
||
// The print option classes and the enumerations of printing.
|
||
(
|
||
"",
|
||
"FontSubstitutionPolicy PageMarksTypes PostScriptImageCompressionType PrintArtworkDesignation PrintColorIntent \
|
||
PrintColorManagementOptions PrintColorProfile PrintColorSeparationMode PrintColorSeparationOptions \
|
||
PrintCoordinateOptions PrintFlattenerOptions PrintFontDownloadMode PrintFontOptions PrintJobOptions PrintOptions \
|
||
PrintOrientation PrintPageMarksOptions PrintPaperOptions PrintPosition PrintPostScriptOptions PrintTiling \
|
||
Printer PrinterPostScriptLevelEnum PrintingBounds",
|
||
),
|
||
("Printer.", "prototype"),
|
||
("Printer.prototype.", "constructor name printerInfo printerInfo= typename"),
|
||
("PrintOptions.", "prototype"),
|
||
(
|
||
"PrintOptions.prototype.",
|
||
"PPDName PPDName= colorManagementOptions colorManagementOptions= colorSeparationOptions colorSeparationOptions= \
|
||
constructor coordinateOptions coordinateOptions= flattenerOptions flattenerOptions= flattenerPreset \
|
||
flattenerPreset= fontOptions fontOptions= jobOptions jobOptions= pageMarksOptions pageMarksOptions= paperOptions \
|
||
paperOptions= postScriptOptions postScriptOptions= printPreset printPreset= printerName printerName= typename",
|
||
),
|
||
("PrintJobOptions.", "prototype"),
|
||
(
|
||
"PrintJobOptions.prototype.",
|
||
"artboardRange artboardRange= bitmapResolution bitmapResolution= collate collate= constructor copies copies= \
|
||
designation designation= file file= name name= printAllArtboards printAllArtboards= printArea printArea= \
|
||
printAsBitmap printAsBitmap= reversePages reversePages= typename",
|
||
),
|
||
("PrintColorManagementOptions.", "prototype"),
|
||
("PrintColorManagementOptions.prototype.", "colorProfileMode colorProfileMode= constructor intent intent= name name= typename"),
|
||
("PrintColorSeparationOptions.", "prototype"),
|
||
(
|
||
"PrintColorSeparationOptions.prototype.",
|
||
"colorSeparationMode colorSeparationMode= constructor convertSpotColors convertSpotColors= inkList inkList= \
|
||
overPrintBlack overPrintBlack= typename",
|
||
),
|
||
("PrintCoordinateOptions.", "prototype"),
|
||
(
|
||
"PrintCoordinateOptions.prototype.",
|
||
"constructor emulsion emulsion= fitToPage fitToPage= horizontalScale horizontalScale= orientation orientation= \
|
||
position position= tiling tiling= typename verticalScale verticalScale=",
|
||
),
|
||
("PrintFlattenerOptions.", "prototype"),
|
||
(
|
||
"PrintFlattenerOptions.prototype.",
|
||
"clipComplexRegions clipComplexRegions= constructor convertStrokesToOutlines convertStrokesToOutlines= \
|
||
convertTextToOutlines convertTextToOutlines= flatteningBalance flatteningBalance= gradientResolution \
|
||
gradientResolution= overprint overprint= rasterizationResolution rasterizationResolution= typename",
|
||
),
|
||
("PrintFontOptions.", "prototype"),
|
||
("PrintFontOptions.prototype.", "constructor downloadFonts downloadFonts= fontSubstitution fontSubstitution= typename"),
|
||
("PrintPageMarksOptions.", "prototype"),
|
||
(
|
||
"PrintPageMarksOptions.prototype.",
|
||
"bleedOffsetRect bleedOffsetRect= colorBars colorBars= constructor marksOffsetRect marksOffsetRect= pageInfoMarks \
|
||
pageInfoMarks= pageMarksType pageMarksType= registrationMarks registrationMarks= trimMarks trimMarks= \
|
||
trimMarksWeight trimMarksWeight= typename",
|
||
),
|
||
("PrintPaperOptions.", "prototype"),
|
||
("PrintPaperOptions.prototype.", "constructor height height= name name= offset offset= transverse transverse= typename width width="),
|
||
("PrintPostScriptOptions.", "prototype"),
|
||
(
|
||
"PrintPostScriptOptions.prototype.",
|
||
"binaryPrinting binaryPrinting= compatibleShading compatibleShading= constructor forceContinuousTone \
|
||
forceContinuousTone= imageCompression imageCompression= negativePrinting negativePrinting= postScriptLevel \
|
||
postScriptLevel= shadingResolution shadingResolution= typename",
|
||
),
|
||
("FontSubstitutionPolicy.", "SUBSTITUTEDEVICE SUBSTITUTEOBLIQUE SUBSTITUTETINT"),
|
||
("PageMarksTypes.", "Japanese Roman"),
|
||
("PostScriptImageCompressionType.", "IMAGECOMPRESSIONNONE JPEG RLE"),
|
||
("PrintArtworkDesignation.", "ALLLAYERS VISIBLELAYERS VISIBLEPRINTABLELAYERS"),
|
||
("PrintColorIntent.", "ABSOLUTECOLORIMETRIC PERCEPTUALINTENT RELATIVECOLORIMETRIC SATURATIONINTENT"),
|
||
("PrintColorProfile.", "CUSTOMPROFILE OLDSTYLEPROFILE PRINTERPROFILE SOURCEPROFILE"),
|
||
("PrintColorSeparationMode.", "COMPOSITE HOSTBASEDSEPARATION INRIPSEPARATION"),
|
||
("PrintFontDownloadMode.", "DOWNLOADCOMPLETE DOWNLOADNONE DOWNLOADSUBSET"),
|
||
("PrintOrientation.", "AUTOROTATE LANDSCAPE PORTRAIT REVERSELANDSCAPE REVERSEPORTRAIT"),
|
||
(
|
||
"PrintPosition.",
|
||
"TRANSLATEBOTTOM TRANSLATEBOTTOMLEFT TRANSLATEBOTTOMRIGHT TRANSLATECENTER TRANSLATELEFT TRANSLATERIGHT TRANSLATETOP \
|
||
TRANSLATETOPLEFT TRANSLATETOPRIGHT",
|
||
),
|
||
("PrintTiling.", "TILEFULLPAGES TILEIMAGEABLEAREAS TILESINGLEFULLPAGE"),
|
||
("PrinterPostScriptLevelEnum.", "PSLEVEL1 PSLEVEL2 PSLEVEL3"),
|
||
("PrintingBounds.", "ARTBOARDBOUNDS ARTWORKBOUNDS"),
|
||
(
|
||
"",
|
||
"CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \
|
||
ParagraphAttributes ParagraphStyle ParagraphStyleAttributes ParagraphStyles Paragraphs TextFont TextFonts TextFrame \
|
||
TextFrames TextOrientation TextRange TextType Words",
|
||
),
|
||
("TextFrames.", "prototype"),
|
||
("TextFrames.prototype.", "add areaText constructor getByName index length parent pathText pointText removeAll typename"),
|
||
("TextFrame.", "prototype"),
|
||
(
|
||
"TextFrame.prototype.",
|
||
"anchor anchor= antialias antialias= characters columnCount columnCount= columnGutter columnGutter= constructor \
|
||
contents contents= convertAreaObjectToPointObject convertPointObjectToAreaObject createOutline endTValue endTValue= \
|
||
insertionPoints insertionPoints= kind lines lines= matrix matrix= nextFrame nextFrame= opticalAlignment \
|
||
opticalAlignment= orientation orientation= paragraphs previousFrame previousFrame= rowCount rowCount= rowGutter \
|
||
rowGutter= startTValue startTValue= story textPath textPath= textRange textRanges textRanges= textSelection \
|
||
textSelection= words",
|
||
),
|
||
("TextRange.", "prototype"),
|
||
(
|
||
"TextRange.prototype.",
|
||
"autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \
|
||
characterOffset= characterStyles characters constructor contents contents= deSelect deSelect= \
|
||
duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \
|
||
getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \
|
||
horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \
|
||
leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles \
|
||
paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \
|
||
spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= textFont textFont= textRanges \
|
||
textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \
|
||
verticalScale= words",
|
||
),
|
||
("Characters.", "prototype"),
|
||
("Characters.prototype.", "add addBefore constructor length parent typename"),
|
||
("Words.", "prototype"),
|
||
("Words.prototype.", "add addBefore constructor length parent typename"),
|
||
("Paragraphs.", "prototype"),
|
||
("Paragraphs.prototype.", "add addBefore constructor length parent typename"),
|
||
("CharacterAttributes.", "prototype"),
|
||
(
|
||
"CharacterAttributes.prototype.",
|
||
"autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \
|
||
rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \
|
||
underline= verticalScale verticalScale=",
|
||
),
|
||
("ParagraphAttributes.", "prototype"),
|
||
(
|
||
"ParagraphAttributes.prototype.",
|
||
"constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \
|
||
rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename",
|
||
),
|
||
("CharacterStyles.", "prototype"),
|
||
("CharacterStyles.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||
("CharacterStyle.", "prototype"),
|
||
("CharacterStyle.prototype.", "applyTo characterAttributes constructor name name= parent remove typename"),
|
||
("CharacterStyleAttributes.", "prototype"),
|
||
(
|
||
"CharacterStyleAttributes.prototype.",
|
||
"autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \
|
||
rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \
|
||
underline= verticalScale verticalScale=",
|
||
),
|
||
("ParagraphStyles.", "prototype"),
|
||
("ParagraphStyles.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||
("ParagraphStyle.", "prototype"),
|
||
(
|
||
"ParagraphStyle.prototype.",
|
||
"applyTo characterAttributes characterAttributes= constructor name name= paragraphAttributes parent remove typename",
|
||
),
|
||
("ParagraphStyleAttributes.", "prototype"),
|
||
(
|
||
"ParagraphStyleAttributes.prototype.",
|
||
"constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \
|
||
rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename",
|
||
),
|
||
("TextFonts.", "prototype"),
|
||
("TextFonts.prototype.", "constructor getByName index length parent typename"),
|
||
("TextFont.", "prototype"),
|
||
("TextFont.prototype.", "constructor family name parent style typename"),
|
||
("Justification.", "CENTER FULLJUSTIFY FULLJUSTIFYLASTLINECENTER FULLJUSTIFYLASTLINELEFT FULLJUSTIFYLASTLINERIGHT LEFT RIGHT"),
|
||
("TextOrientation.", "HORIZONTAL VERTICAL"),
|
||
("TextType.", "AREATEXT PATHTEXT POINTTEXT"),
|
||
("", "Stories Story StoryCharacters StoryParagraphs StoryRange StoryWords"),
|
||
("Stories.", "prototype"),
|
||
("Stories.prototype.", "constructor index length parent typename"),
|
||
("Story.", "prototype"),
|
||
(
|
||
"Story.prototype.",
|
||
"characters constructor insertionPoints insertionPoints= length lines lines= paragraphs parent textFrames textRange \
|
||
textRanges textRanges= textSelection textSelection= typename words",
|
||
),
|
||
("StoryRange.", "prototype"),
|
||
(
|
||
"StoryRange.prototype.",
|
||
"autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \
|
||
characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \
|
||
contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \
|
||
getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \
|
||
getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \
|
||
length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \
|
||
paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \
|
||
strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \
|
||
underline underline= verticalScale verticalScale= words",
|
||
),
|
||
("StoryCharacters.", "prototype"),
|
||
("StoryCharacters.prototype.", "constructor length parent typename"),
|
||
("StoryWords.", "prototype"),
|
||
("StoryWords.prototype.", "constructor length parent typename"),
|
||
("StoryParagraphs.", "prototype"),
|
||
("StoryParagraphs.prototype.", "constructor length parent typename"),
|
||
// Variables and data sets. `importVariables` reads the library file it is given. `PageItem`'s
|
||
// `visibilityVariable` is in its row above.
|
||
("", "Dataset Datasets Variable VariableKind Variables"),
|
||
("VariableKind.", "GRAPH IMAGE TEXTUAL Unknown VISIBILITY"),
|
||
("Variables.", "prototype"),
|
||
("Variables.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||
("Variable.", "prototype"),
|
||
("Variable.prototype.", "constructor kind kind= name name= pageItems parent remove typename"),
|
||
("Datasets.", "prototype"),
|
||
("Datasets.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||
("Dataset.", "prototype"),
|
||
("Dataset.prototype.", "constructor display name name= parent remove typename update"),
|
||
("Document.prototype.", "activeDataset activeDataset= dataSets importVariables variables variablesLocked variablesLocked="),
|
||
("GraphItem.prototype.", "contentVariable contentVariable="),
|
||
("PlacedItem.prototype.", "contentVariable contentVariable="),
|
||
("RasterItem.prototype.", "contentVariable contentVariable="),
|
||
("TextFrame.prototype.", "contentVariable contentVariable="),
|
||
];
|
||
|
||
/// The classes the host adds with nothing but a prototype and its constructor: the page item types
|
||
/// that have no members of their own, the color classes, and the save and export option classes.
|
||
const BARE_CLASSES: &str = "BlendItem CMYKColor EnvelopeItem GradientColor GraphItem GrayColor IntertwineItem LabColor \
|
||
MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem cmykColor \
|
||
EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions";
|
||
|
||
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
|
||
/// own API, and what `vc.run` does depends on the command it runs.
|
||
const NOT_CHECKED: &str = "vc";
|
||
|
||
/// An expression whose value is the list of names, one to a line.
|
||
const LIST: &str = r#"(function () {
|
||
var out = [];
|
||
function add(o, prefix) {
|
||
var own = Object.getOwnPropertyNames(o);
|
||
for (var i = 0; i < own.length; i++) {
|
||
out.push(prefix + own[i]);
|
||
var d = Object.getOwnPropertyDescriptor(o, own[i]);
|
||
if (d && d.set) out.push(prefix + own[i] + "=");
|
||
}
|
||
}
|
||
var g = (function () { return this; })();
|
||
var globals = Object.getOwnPropertyNames(g);
|
||
add(g, "");
|
||
for (var i = 0; i < globals.length; i++) {
|
||
// A global with a getter, such as `activeDocument`, is not read: it throws with no document open.
|
||
var gd = Object.getOwnPropertyDescriptor(g, globals[i]);
|
||
if (gd && gd.get) continue;
|
||
var v = g[globals[i]];
|
||
if (v !== null && (typeof v == "object" || typeof v == "function")) {
|
||
add(v, globals[i] + ".");
|
||
if (typeof v == "function" && v.prototype !== null && typeof v.prototype == "object") add(v.prototype, globals[i] + ".prototype.");
|
||
}
|
||
}
|
||
return out.join("\n");
|
||
})()"#;
|
||
|
||
/// The names a script run by the host has.
|
||
fn host_names() -> BTreeSet<String> {
|
||
let mut s = Session::new();
|
||
let r = s.execute("script.run", &json!({"source": format!("vc.log({LIST});"), "name": "list.js"})).unwrap();
|
||
let text = r["log"][0].as_str().unwrap_or_else(|| panic!("no list in {r}"));
|
||
text.lines().map(str::to_string).collect()
|
||
}
|
||
|
||
/// The names a plain JavaScript engine with E4X has.
|
||
fn language_names() -> BTreeSet<String> {
|
||
match Realm::with_options(Options { e4x: true, ..Options::default() }, vectorcraft_js::Limits::default()).run(LIST) {
|
||
Ok(JsValue::String(text)) => text.lines().map(str::to_string).collect(),
|
||
other => panic!("no list: {other:?}"),
|
||
}
|
||
}
|
||
|
||
fn table_names() -> BTreeSet<String> {
|
||
let inside = INSIDE.iter().flat_map(|(prefix, names)| names.split_whitespace().map(move |n| format!("{prefix}{n}")));
|
||
let bare = BARE_CLASSES.split_whitespace().flat_map(|c| [c.to_string(), format!("{c}.prototype"), format!("{c}.prototype.constructor")]);
|
||
OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain(bare).chain([NOT_CHECKED.to_string()]).collect()
|
||
}
|
||
|
||
#[test]
|
||
fn every_name_the_host_adds_has_a_row() {
|
||
let host = host_names();
|
||
let language = language_names();
|
||
let table = table_names();
|
||
let not_checked = |n: &&String| n.starts_with(&format!("{NOT_CHECKED}."));
|
||
let missing: Vec<_> = host.difference(&language).filter(|n| !table.contains(*n) && !not_checked(n)).collect();
|
||
assert!(missing.is_empty(), "the host adds these names, which no table here lists: {missing:?}");
|
||
let gone: Vec<_> = table.difference(&host).collect();
|
||
assert!(gone.is_empty(), "the tables list these names, which a script run by the host does not have: {gone:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn every_name_that_reaches_outside_has_its_checker_id() {
|
||
for (name, script, id) in OUTSIDE {
|
||
let r = check("probe.jsx", script.as_bytes(), None, &Limits::default());
|
||
let ids: Vec<_> = r.outside.iter().map(|o| o.id).collect();
|
||
assert!(ids.contains(id), "{name}: the checker gives {ids:?} for {script:?}, not {id}");
|
||
}
|
||
}
|
||
|
||
/// A line with the directive `d`. The match has no catch-all, so a new directive needs a row, and
|
||
/// [`DirectiveName::from_name`] reads only the directives in [`DirectiveName::ALL`].
|
||
fn directive_line(d: DirectiveName) -> &'static str {
|
||
match d {
|
||
DirectiveName::Include => "#include \"lib.jsxinc\"",
|
||
DirectiveName::IncludePath => "#includepath \"lib\"",
|
||
DirectiveName::Script => "#script Tidy",
|
||
DirectiveName::Strict => "#strict on",
|
||
DirectiveName::Target => "#target vectorcraft",
|
||
DirectiveName::TargetEngine => "#targetengine session",
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn the_checker_lists_every_directive_the_host_reads() {
|
||
for d in DirectiveName::ALL {
|
||
let line = directive_line(d);
|
||
let r = check("probe.jsx", format!("{line}\nvar a = 1;\n").as_bytes(), None, &Limits::default());
|
||
let listed: Vec<_> = r.directives.iter().map(|d| d.name.to_string()).collect();
|
||
assert_eq!(listed, [d.as_str()], "{line}");
|
||
}
|
||
}
|