-
Notifications
You must be signed in to change notification settings - Fork 1
/
_lib.js
executable file
·56 lines (48 loc) · 2.21 KB
/
_lib.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#import '_sandbox.js'
var pluginPath = sketch.scriptPath.match( /(?:.*)(?:\/Plugins\/)(?:[^\/]*)(?:)/gm ); // ImageFiller's folder
function showError(msg){
doc.showMessage(msg);
return false;
}
function getImagesFromPath(imagesPath){
if (imagesPath.slice(-1) != "/") imagesPath = imagesPath+"/"; // ugly fix for path concatenations
new AppSandbox().authorize(imagesPath, run);
function run(){
var usedImages = [];
var selections = selection.count();
if (selections == 0) showError("Oh! You need to select a few layers before running the plugin.");
// Get all images from the folder and its subdirectories
var fileManager = NSFileManager.defaultManager();
fileManager.changeCurrentDirectoryPath(imagesPath);
var enumerator = fileManager.enumeratorAtPath(imagesPath);
var dirsNFiles = [[NSMutableArray alloc] init];
while ((entry = [enumerator nextObject]) != null){
if (fileManager.fileExistsAtPath(entry)) {
dirsNFiles.addObject(entry);
}
}
var extensions = [NSArray arrayWithObjects:@"png", @"PNG", @"jpg", @"JPG", @"jpeg", @"JPEG", @"gif", @"GIF", nil];
var imagesFileNames = [dirsNFiles filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"pathExtension IN %@", extensions]];
var imgLen = imagesFileNames.count();
if (imgLen == 0) showError("Hm. Couldn't find any images inside "+imagesPath+". You should add a few.");
// apply images to selection
var theimages = [[NSMutableArray alloc] init];
theimages.addObjectsFromArray(imagesFileNames);
for (var i=0; i < selections; i++){
if (theimages.count() == 0) theimages.addObjectsFromArray(imagesFileNames);
var layer = selection[i]
var fills = layer.style().fills()
if (fills.count() == 0) fills.addNewStylePart();
var firstFill = fills.lastObject();
firstFill.setFillType(4);
firstFill.setPatternFillType(1);
var r = Math.floor(Math.random() * theimages.count());
var fileName = imagesPath+theimages[r];
if (fileManager.fileExistsAtPath(fileName)) {
image = [[NSImage alloc] initWithContentsOfFile:fileName];
firstFill.setImage(image);
}
theimages.removeObjectAtIndex(r)
}
}
}