Skip to content
This repository has been archived by the owner on Feb 24, 2021. It is now read-only.

Commit

Permalink
Fixed #8; Finally you can change the base density!
Browse files Browse the repository at this point in the history
  • Loading branch information
Geert Wille committed Sep 10, 2015
1 parent acfd058 commit 0be45da
Show file tree
Hide file tree
Showing 6 changed files with 175 additions and 47 deletions.
29 changes: 29 additions & 0 deletions Change Base Density.sketchplugin
@@ -0,0 +1,29 @@
// Developer: Geert Wille

@import 'library/main.js'

var selection = context.selection,
document = context.document,
factors = [
{
folder: '',
scale: 1.0,
suffix: '',
},
{
folder: '',
scale: 2.0,
suffix: '@2x',
},
{
folder: '',
scale: 3.0,
suffix: '@3x',
},
]
;

var home_folder = "/Users/" + NSUserName();
new AppSandbox().authorize(home_folder, function() {
com.geertwille.main.updateBaseDensity();
});
43 changes: 23 additions & 20 deletions Create Xcode Assets Catalog.sketchplugin
Expand Up @@ -2,29 +2,32 @@
//
// Developer: Geert Wille

#import 'library/main.js'
@import 'library/main.js'

var factors = [
{
folder: '',
scale: 1.0,
suffix: '',
},
{
folder: '',
scale: 2.0,
suffix: '@2x',
},
{
folder: '',
scale: 3.0,
suffix: '@3x',
},
];
var selection = context.selection,
document = context.document,
factors = [
{
folder: '',
scale: 1.0,
suffix: '',
},
{
folder: '',
scale: 2.0,
suffix: '@2x',
},
{
folder: '',
scale: 3.0,
suffix: '@3x',
},
]
;

var home_folder = "/Users/" + NSUserName();
new AppSandbox().authorize(home_folder, function() {
// do whatever you need to do here
com.geertwille.main.export('ios', factors);
var config = com.geertwille.main.readConfig();
com.geertwille.main.export('ios', factors, config['density-scale']);
});

4 changes: 3 additions & 1 deletion README.md
Expand Up @@ -35,7 +35,9 @@ directory, you'll find the plugin functions under the Plugins menu in Sketch.

## Assumptions

The plugin assumes you design your layouts in mdpi, which means 1px = 1dp
~~The plugin assumes you design your layouts in mdpi, which means 1px = 1dp~~

From now on this is configurable!

## Shortcuts

Expand Down
1 change: 1 addition & 0 deletions config.json
@@ -0,0 +1 @@
{"density-scale":3}
73 changes: 73 additions & 0 deletions library/functions.js
@@ -0,0 +1,73 @@
var writeTextToFile = function(text, filePath) {
var t = [NSString stringWithFormat:@"%@", text],
f = [NSString stringWithFormat:@"%@", filePath];
return [t writeToFile:f atomically:true encoding:NSUTF8StringEncoding error:nil];
}

var readTextFromFile = function(filePath) {
var fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:filePath]) {
return [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
}
return nil;
}

var jsonFromFile = function(filePath, mutable) {
var data = [NSData dataWithContentsOfFile:filePath];
var options = mutable == true ? NSJSONReadingMutableContainers : 0
return [NSJSONSerialization JSONObjectWithData:data options:options error:nil];
}

var saveJsonToFile = function(jsonObj, filePath) {
writeTextToFile(stringify(jsonObj), filePath);
}

var stringify = function(obj, prettyPrinted) {
var prettySetting = prettyPrinted ? NSJSONWritingPrettyPrinted : 0,
jsonData = [NSJSONSerialization dataWithJSONObject:obj options:prettySetting error:nil];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

var createTempFolderNamed = function(name) {
var tempPath = getTempFolderPath(name);
createFolderAtPath(tempPath);
return tempPath;
}

var getTempFolderPath = function(withName) {
var fileManager = [NSFileManager defaultManager],
cachesURL = [[fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject],
withName = (typeof withName !== 'undefined') ? withName : (Date.now() / 1000),
folderName = [NSString stringWithFormat:"%@", withName];
return [[cachesURL URLByAppendingPathComponent:folderName] path];
}

var createFolderAtPath = function(pathString) {
var fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:pathString]) return true;
return [fileManager createDirectoryAtPath:pathString withIntermediateDirectories:true attributes:nil error:nil];
}

var removeFileOrFolder = function(filePath) {
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}

var readPluginPath = function() {
var pluginFolder = context.scriptPath.match(/Plugins\/([\w -])*/)[0] + "/";
var sketchPluginsPath = context.scriptPath.replace(/Plugins([\w \/ -])*.sketchplugin$/, "");

return {
sketchPluginsPath: sketchPluginsPath,
pluginFolder: pluginFolder
}
}

var helpers = {
readTextFromFile: readTextFromFile,
writeTextToFile: writeTextToFile,
jsonFromFile: jsonFromFile,
saveJsonToFile: saveJsonToFile,
createFolderAtPath: createFolderAtPath,
removeFileOrFolder: removeFileOrFolder,
readPluginPath: readPluginPath
}
72 changes: 46 additions & 26 deletions library/main.js
@@ -1,17 +1,20 @@
#import 'library/general.js'
#import 'library/messages.js'
#import 'library/sandbox.js'
@import 'library/general.js'
@import 'library/functions.js'
@import 'library/messages.js'
@import 'library/sandbox.js'

com.geertwille.main = {
defaultAssetFolder: 'Images.xcassets',
type: '',
baseDensity: 0,
baseDir: '',
factors: {},
layerVisibility: [],

export: function(type, factors) {
export: function(type, factors, baseDensity) {
this.type = type;
this.factors = factors;
this.baseDensity = baseDensity;
this.baseDir = this.getDirFromPrompt();

if (this.baseDir == null) {
Expand All @@ -25,6 +28,10 @@ com.geertwille.main = {
return;
}

if (this.baseDensity == 0) {
this.baseDensity = this.getDensityScaleFromPrompt();
}

// Hide all layers except the ones we are slicing
for (var i = 0; i < [selection count]; i++) {
var layer = [selection objectAtIndex:i];
Expand Down Expand Up @@ -70,6 +77,28 @@ com.geertwille.main = {
}
},

//Let the user select design density
getDensityScaleFromPrompt: function() {
var folders = helpers.readPluginPath(),
accessory = [[NSComboBox alloc] initWithFrame:NSMakeRect(0, 0, 200, 25)],
alert = [[NSAlert alloc] init],
responseCode
;
[accessory addItemsWithObjectValues:['@1x', '@2x', '@3x']];
[accessory selectItemAtIndex: 0];

[alert setMessageText:'Select screen density'];
[alert addButtonWithTitle:'OK'];
[alert setAccessoryView:accessory];

responseCode = [alert runModal];
var densityScale = [accessory indexOfSelectedItem] + 1;

helpers.saveJsonToFile([NSDictionary dictionaryWithObjectsAndKeys:densityScale, @"density-scale", nil], folders.sketchPluginsPath + folders.pluginFolder + '/config.json');

return densityScale;
},

processSlice: function(slice) {
var frame = [slice frame],
sliceName = [slice name],
Expand Down Expand Up @@ -121,7 +150,7 @@ com.geertwille.main = {
}

// write the json string to a file
var ok = this.writeTextToFile(this.prepareJSON(lineBuffer), this.baseDir + "/" + this.defaultAssetFolder + "/" + cutSliceName + ".imageset/Contents.json");
var ok = helpers.writeTextToFile(this.prepareJSON(lineBuffer), this.baseDir + "/" + this.defaultAssetFolder + "/" + cutSliceName + ".imageset/Contents.json");

if (ok === false) {
com.geertwille.general.alert(com.geertwille.messages.unknown_error);
Expand All @@ -144,34 +173,14 @@ com.geertwille.main = {
}
}

slice = [MSExportRequest requestWithRect:rect scale:factor];
slice = [MSExportRequest requestWithRect:rect scale:(factor / this.baseDensity)];
slice.shouldTrim = true;
// slice.saveForWeb = true;
// slice.compression = 0;
slice.includeArtboardBackground = false;
return slice;
},

writeTextToFile: function(text, path) {
var result = false;
if (typeof path !== 'string')
return result;

// create a NSString object from the given text
var nsstring = NSString.stringWithUTF8String(text);

// use the writeToFile method of the NSString object to write the text to the given URL
result = [nsstring writeToFile:path atomically:1 encoding:NSUTF8StringEncoding error:null];

if (!result) {
result = false;
} else {
result = true;
}

return result;
},

prepareJSON: function(lineBuffer) {
var jsoncode = '{ "images" : [';

Expand All @@ -183,5 +192,16 @@ com.geertwille.main = {
jsoncode = jsoncode + ' ], "info" : { "version" : 1, "author" : "xcode" }}';

return jsoncode;
},

readConfig: function() {
var folders = helpers.readPluginPath();
log(folders.sketchPluginsPath + folders.pluginFolder);
return helpers.jsonFromFile(folders.sketchPluginsPath + folders.pluginFolder + '/config.json', true);
// helpers.jsonFromFile();
},

updateBaseDensity: function() {
this.getDensityScaleFromPrompt();
}
}

0 comments on commit 0be45da

Please sign in to comment.