-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.jsx
381 lines (312 loc) · 10.2 KB
/
module.jsx
1
/** * LICENSE & COPYRIGHT * * You are free to use, modify, and distribute this script as you see fit. * No credit is required but would be greatly appreciated. * * Scott Lewis - scott@iconify.it * http://github.com/iconifyit * http://iconify.it * * THIS SCRIPT IS OFFERED AS-IS WITHOUT ANY WARRANTY OR GUARANTEES OF ANY KIND. * YOU USE THIS SCRIPT COMPLETELY AT YOUR OWN RISK AND UNDER NO CIRCUMSTANCES WILL * THE DEVELOPER AND/OR DISTRIBUTOR OF THIS SCRIPT BE HELD LIABLE FOR DAMAGES OF * ANY KIND INCLUDING LOSS OF DATA OR DAMAGE TO HARDWARE OR SOFTWARE. IF YOU DO * NOT AGREE TO THESE TERMS, DO NOT USE THIS SCRIPT. *//** * Declare the target app. */#target illustrator/** * Include the libraries we need. */#includepath "lib/";#include "JSON.jsxinc";#include "Utils.jsxinc";#include "Logger.jsxinc";#include "Iterator.js";#include "Object.ext.js";#include "Observable.js";#include "ArtboardDimensions.js";// terms.jsx must be loaded before Strings as Strings takes the LANG object as an argument.#include "terms.jsxinc";#include "Strings.jsx";/** * Name that script. */#script "Resize Icons";/** * Disable Illustrator's alerts. */// Utils.displayAlertsOff();/** * Set some global variables. */var $HERE = new File($.fileName).path + '/';var $HOME = new File('~/').fsName + '/';var $UUID = Utils.uuid().split('-').shift();/** * The config object for this script. * @type {{ * APP_NAME: string, * SCALE: number, * UNIT_TYPES: object * }} */var CONFIG = Utils.create({ APP_NAME : 'ai-resize-icons', SCALE : 100, UNIT_TYPES : { PT : 0, PICA : 1, INCH : 2, MM : 3, CM : 4, HQ : 5, PX : 6 }});/** * Import external configs to over-ride the settings above. */#include "conf/config.js";/** * Update the CONFIG object with any user-specified * custom values. */Utils.update(CONFIG, MY_CONFIG || {});/** * Create the module class. * @type {{run}} */var Module = (function(CONFIG) { Utils.extend(this, new Observable(), true); var parent = this; parent.topics = { START : 'app.start', LOOP : 'loop.start', CONTINUE : 'loop.continue', MAIN : 'loop.main', NEXT : 'loop.next', FINISH : 'app.shutdown', ERROR : 'app.error', WARN : 'app.warn', DIALOG : 'app.dialog' }; /** * Create a new instance of this module. * @constructor */ var Instance = function() { var self = this; self.UUID = $UUID; self.config = CONFIG; // Create a logger instance. Utils['logger'] = new Logger(CONFIG.APP_NAME, Utils.folder(CONFIG.LOG_FILE_PATH)); self.logger = Utils.logger; parent.publish(parent.topics.START, [{ instance : self }]); if (app.documents.length == 0) { parent.publish(parent.topics.ERROR, [{ message : Strings.get('NO_OPEN_DOCS') }]); return; } // Env setup app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; app.preferences.setIntegerPreference("rulerType", CONFIG.UNIT_TYPES.PX); var doc = app.activeDocument; var Artboards = new Iterator(doc.artboards); // TODO: Move input dialog to plugin parent.publish(parent.topics.DIALOG, [{ instance : self }]); // User-interaction var theUnit = null; // "%"; var theValue = null; // 100; var n = 0; var max = 5; while ( (isNaN(theValue) || ['%', 'px'].indexOf(theUnit) == -1) && n < max ) { theResponse = Window.prompt( Strings.get('ENTER_NEW_SIZE'), '100%'); theUnit = theResponse.replace(/[0-9]+/, ''); theValue = parseFloat(theResponse); n++; } // Input validation if (isNaN(theValue) || ['%', 'px'].indexOf(theUnit) == -1) { throw new Error(Strings.get('INVALID_USER_INPUT')) } // UI feedback Utils.showProgressBar(Artboards.size()); // Data set iteration. This is where the magic happens. Artboards.each(function(i) { var artboard = this; parent.publish(parent.topics.LOOP, [{ instance : self, index : i, artboard : artboard, item : null }]); doc.artboards.setActiveArtboardIndex(i); doc.selectObjectsOnActiveArtboard(); app.executeMenuCommand('group'); // If there are no visible items, update the progress bar and continue. if (! doc.selection.length) { Utils.updateProgress( Strings.get('NO_VISIBLE_ITEMS', i) ); parent.publish(parent.topics.WARN, [{ message : Strings.get('NO_VISIBLE_ITEMS', i) }]); return; } var groupItem = doc.selection[0]; var dims = new ArtboardDimensions(this); var context = { instance : self, artboard : artboard, item : groupItem, index : i }; // TODO: Move to plugin try { self.config.SCALE = calcScale(groupItem, theUnit, theValue, dims); Utils.logger.info( Strings.get('CALCULATED_SIZE') ); if (isNaN(self.config.SCALE)) { Utils.progress.close(); return new Error( Strings.get('SCALE_MUST_BE_NUMBER') ); } if (! sizeFitsArtboard(groupItem, dims, self.config.SCALE)) { return new Error( Strings.get('ITEM_MUST_FIT_ARTBOARD') ); } } catch(e) { Utils.progress.close(); return new Error(e); } try { Utils.updateProgressMessage( Strings.get('GROUPING_SELECTION') ); if (! Utils.isVisibleAndUnlocked(groupItem)) { Utils.logger.info( Strings.get('SELECTION_VISIBLE', [Strings.get('HIDDEN')] ) ); parent.publish(parent.topics.SKIP, [context]); return; } // Plugins that work on the artboard/artwork should subscribe here. parent.publish(parent.topics.MAIN, [context]); } catch(e) { Utils.progress.close(); Utils.logger.error(e.message); } Utils.updateProgress( Strings.get('ITEM_UPDATED') ); if (i < Artboards.size()) { parent.publish(parent.topics.NEXT, [context]); } }); Utils.progress.close(); parent.publish(parent.topics.FINISH, [{ instance : self }]); }; function calcScale(groupItem, theUnit, theValue, dims) { var scale = theValue; if (Utils.trim(theUnit) != '%' && Utils.trim(theUnit) != '') { scale = Utils.scaleFromSize( groupItem.width, groupItem.height, theValue, theValue ); } return scale; } function sizeFitsArtboard(groupItem, dims, scale) { var ratio = scale / 100; if (ratio * groupItem.width > dims.width || ratio * groupItem.height > dims.height) { return false; } return true; } /** * Returns the public module object. */ return { topics : parent.topics, subscribe : parent.subscribe, unsubscribe : parent.unsubscribe, /** * Runs the module code. */ run: function() { Utils.displayAlertsOff(); try { new Instance(); } catch(ex) { Utils.logger.error( ex.message ); } Utils.displayAlertsOn(); } }})( CONFIG || {} );// MonitoringModule.subscribe(Module.topics.START, function(context) { $.writeln('Instance.' + context.instance.UUID + " started");});Module.subscribe(Module.topics.LOOP, function(context) { $.writeln('Instance.' + context.instance.UUID + ".LOOP");});Module.subscribe(Module.topics.CONTINUE, function(context) { $.writeln('Instance.' + context.instance.UUID + ".CONTINUE");});Module.subscribe(Module.topics.MAIN, function(context) { $.writeln('Instance.' + context.instance.UUID + ".MAIN");});Module.subscribe(Module.topics.NEXT, function(context) { $.writeln('Instance.' + context.instance.UUID + ".NEXT");});Module.subscribe(Module.topics.FINISH, function(context) { $.writeln('Instance.' + context.instance.UUID + ".FINISH");});Module.subscribe(Module.topics.ERROR, function(context) { throw new Error(context.message);});Module.subscribe(Module.topics.WARN, function(context) { Utils.logger.warn(context.message);});// Pluginsvar centerHandle = Module.subscribe(Module.topics.MAIN, function(context) { var artboard = context.artboard; var artwork = context.item; $.writeln('Centering artwork on artboard ' + context.artboard.name); try { var right = artboard.artboardRect[2]; var bottom = artboard.artboardRect[3]; artwork.position = [ Math.round((right - artwork.width)/2), Math.round((bottom + artwork.height)/2) ]; redraw(); Module.unsubscribe(centerHandle); } catch(ex) { Utils.logger.error( ex.getMessage() ); }});var resizeHandle = Module.subscribe(Module.topics.MAIN, function(context) { var artwork = context.item; var scale = context.instance.config.SCALE; $.writeln('Mock resizing item on artboard ' + context.artboard.name + ' to ' + scale); return; try { scale = isNaN(scale) ? 100 : scale; if (typeof(artwork.resize) == "function" && scale != 100) { artwork.resize(scale, scale, true, true, true, true, scale); } } catch(ex) { Utils.logger.error( ex.getMessage() ); } redraw();});Module.run();