private void loadDefaultStyles() { VirtualFile defaultsCSSFile = resolveDefaultsCssFile(); // Load the per SWC default styles first for (Iterator it = configuration.getDefaultsCssFiles().iterator(); it.hasNext(); ) { VirtualFile swcDefaultsCssFile = (VirtualFile) it.next(); // Make sure that we resolve things relative to the SWC. ThreadLocalToolkit.getPathResolver().addSinglePathResolver(0, swcDefaultsCssFile); processStyleSheet(swcDefaultsCssFile); ThreadLocalToolkit.getPathResolver().removeSinglePathResolver(swcDefaultsCssFile); } // Load the default styles next, so they can override the SWC defaults if (defaultsCSSFile != null) { // Only load the defaults if it's not a SwcFile. If it's // a SwcFile, it should have already been loaded. if (!(defaultsCSSFile instanceof SwcFile)) { processStyleSheet(defaultsCSSFile); } } else { ThreadLocalToolkit.log(new DefaultCSSFileNotFound()); } // Load the theme styles next, so they can override the defaults for (Iterator it = configuration.getThemeCssFiles().iterator(); it.hasNext(); ) { VirtualFile themeCssFile = (VirtualFile) it.next(); // Make sure that we resolve things in the theme relative // to the theme SWC first. ThreadLocalToolkit.getPathResolver().addSinglePathResolver(0, themeCssFile); processStyleSheet(themeCssFile); ThreadLocalToolkit.getPathResolver().removeSinglePathResolver(themeCssFile); } }
// changed from private to protected to support Flash Authoring - jkamerer 2007.07.30 protected Swc getSwc(File file) { Swc swc; try { String location = FileUtils.canonicalPath(file); swc = (Swc) swcLRUCache.get(location); long fileLastModified = file.lastModified(); if (swc == null || (fileLastModified != swc.getLastModified())) { if (Trace.swc) { if (swc != null) { Trace.trace( "Reloading: location = " + location + ", fileLastModified = " + fileLastModified + ", swc.getLastModified() = " + swc.getLastModified() + ", swc = " + swc.hashCode()); } else { Trace.trace("Loading " + location); } } SwcArchive archive = file.isDirectory() ? (SwcArchive) new SwcDirectoryArchive(location) : lazyRead ? new SwcLazyReadArchive(location) : new SwcDynamicArchive(location); swc = new Swc(archive, true); swc.setLastModified(fileLastModified); if (ThreadLocalToolkit.errorCount() > 0) { swc = null; } else if (useCache) { swcLRUCache.put(location, swc); } } else if (Trace.swc) { Trace.trace("Using cached version of " + location); } } catch (Exception e) { if (Trace.error) { e.printStackTrace(); } SwcException.SwcNotLoaded ex = new SwcException.SwcNotLoaded(file.getName(), e); ThreadLocalToolkit.log(ex); throw ex; } return swc; }
/** Saves the given SWC to disk and adds to the cache */ public synchronized boolean export(Swc swc) throws FileNotFoundException, IOException { try { if (!swc.save()) { return false; } if (Trace.swc) { Trace.trace("Exported SWC " + swc.getLocation() + "(" + swc.getLastModified() + ")"); } if (!(swc.getArchive() instanceof SwcWriteOnlyArchive)) { // add to Swc cache swcLRUCache.put(swc.getLocation(), swc); } } catch (Exception e) { if (Trace.error) { e.printStackTrace(); } if (e instanceof SwcException) { throw (SwcException) e; } else { SwcException ex = new SwcException.SwcNotExported(swc.getLocation(), e); ThreadLocalToolkit.log(ex); throw ex; } } return true; }
private Source createSource(String fileName, SourceCodeBuffer sourceCodeBuffer) { Source result = null; if (sourceCodeBuffer.getBuffer() != null) { String sourceCode = sourceCodeBuffer.toString(); if (configuration.keepGeneratedActionScript()) { try { FileUtil.writeFile(fileName, sourceCode); } catch (IOException e) { ThreadLocalToolkit.log( new VelocityException.UnableToWriteGeneratedFile(fileName, e.getMessage())); } } VirtualFile genFile = new TextFile(sourceCode, fileName, null, MimeMappings.AS, Long.MAX_VALUE); String shortName = fileName.substring(0, fileName.lastIndexOf('.')); result = new Source(genFile, "", shortName, null, false, false, false); result.setPathResolver(compilationUnit.getSource().getPathResolver()); Iterator iterator = implicitIncludes.iterator(); while (iterator.hasNext()) { VirtualFile virtualFile = (VirtualFile) iterator.next(); result.addFileInclude(virtualFile); } } return result; }
public void checkForUnusedTypeSelectors(Set defNames) { Iterator iterator = selectors.entrySet().iterator(); Set unqualifiedDefNames = new HashSet(); Iterator defNameIterator = defNames.iterator(); while (defNameIterator.hasNext()) { String defName = (String) defNameIterator.next(); unqualifiedDefNames.add(defName.replaceFirst(".*:", "")); } while (iterator.hasNext()) { Entry entry = (Entry) iterator.next(); String styleName = (String) entry.getKey(); StyleDef styleDef = (StyleDef) entry.getValue(); String typeName = StyleDef.dehyphenize(styleName); if (styleDef.isTypeSelector() && localStyleTypeNames.contains(styleName) && !unqualifiedDefNames.contains(typeName) && !styleName.equals("global")) { if (configuration.showUnusedTypeSelectorWarnings()) { ThreadLocalToolkit.log( new UnusedTypeSelector( compilationUnit.getSource().getName(), styleDef.getLineNumber(), styleName)); } } } }
private void processStyleSheet(VirtualFile cssFile) { implicitIncludes.add(cssFile); try { FontManager fontManager = configuration.getFontsConfiguration().getTopLevelManager(); StyleSheet styleSheet = new StyleSheet(); styleSheet.checkDeprecation(configuration.showDeprecationWarnings()); styleSheet.parse( cssFile.getName(), cssFile.getInputStream(), ThreadLocalToolkit.getLogger(), fontManager); extractStyles(styleSheet, false); } catch (Exception exception) { CompilerMessage m = new ParseError(exception.getLocalizedMessage()); m.setPath(cssFile.getName()); ThreadLocalToolkit.log(m); } }
public void generate(CompilationUnit unit, TypeTable typeTable) { // since warnings are common when a file is malformed, most unsuccessful compilations // will have some kind of signature warning... the only REAL warnings that are interesting // are those that occur on well-formed programs that compile. only output warnings if the // application was able to successfully compile. // ADDITIONALLY, we'll only even attempt to output warnings IF we got to code generation. // disabled for RTM since this has been active for a few betas and proven itself; // even if warnings occur, we default to safe behavior. // // no reason to harass our customers anymore ;-) if (debug) { final CompilerWarning warning = getWarning(unit); if ((warning != null) && (ThreadLocalToolkit.errorCount() == 0)) { ThreadLocalToolkit.log(warning); } } }
private Source generateStyleSource(StyleDef styleDef, ResourceContainer resources) { String genFileName = generateStyleSourceName(styleDef); Source styleSource = resources.findSource(genFileName); if (styleSource != null) { if (styleSource.getCompilationUnit() == null) { // if no compilationUnit, then we need to generate source so we can recompile. styleSource = null; } else { // C: it is safe to return because this method deals with per-app styles, like defaults.css // and themes. // ResourceContainer will not have anything if any of the theme files is touched. return styleSource; } } // load template Template template; try { template = VelocityManager.getTemplate(STYLEDEF_TEMPLATE); } catch (Exception exception) { ThreadLocalToolkit.log(new VelocityException.TemplateNotFound(STYLEDEF_TEMPLATE)); return null; } SourceCodeBuffer out = new SourceCodeBuffer(); try { VelocityUtil util = new VelocityUtil(TEMPLATE_PATH, configuration.debug(), out, null); VelocityContext vc = VelocityManager.getCodeGenContext(util); vc.put(STYLEDEF_KEY, styleDef); template.merge(vc, out); } catch (Exception e) { ThreadLocalToolkit.log( new VelocityException.GenerateException( compilationUnit.getSource().getRelativePath(), e.getLocalizedMessage())); return null; } return resources.addResource(createSource(genFileName, out)); }
private static String generateSignature(final CompilationUnit unit) { final Context cx = unit.getContext().getAscContext(); String sigString = null; { // good estimate of buffer size for a signature final int powerOfTwoBufferSize = (int) Math.pow(2, Math.round(Math.log(unit.getSource().size()) / Math.log(2))); // generate the signature final SignatureEvaluator evaluator = new SignatureEvaluator(powerOfTwoBufferSize, keepGeneratedSignatures); evaluator.setLocalizationManager(ThreadLocalToolkit.getLocalizationManager()); ((ProgramNode) unit.getSyntaxTree()).evaluate(cx, evaluator); sigString = evaluator.getSignature(); } return sigString; }
private VirtualFile resolveDefaultsCssFile() { VirtualFile defaultsCSSFile = configuration.getDefaultsCssUrl(); if (defaultsCSSFile == null) { PathResolver resolver = ThreadLocalToolkit.getPathResolver(); String version = configuration.getCompatibilityVersionString(); if (version != null) { defaultsCSSFile = resolver.resolve("defaults-" + version + ".css"); } if (defaultsCSSFile == null) { defaultsCSSFile = resolver.resolve("defaults.css"); } } return defaultsCSSFile; }
/** * only allow MetaDataNode in the specified ranges. * * @param unit * @param map * @param beginLines * @param endLines */ public static void metaDataOnly( CompilationUnit unit, LineNumberMap map, int[] beginLines, int[] endLines) { ProgramNode node = (ProgramNode) unit.getSyntaxTree(); Context cx = node.cx; StatementListNode stmts = node.statements; for (int i = 0, length = stmts.items == null ? 0 : stmts.items.size(); i < length; i++) { Node n = stmts.items.get(i); if (n instanceof DocCommentNode || !(n instanceof MetaDataNode)) { int line = map.get(cx.input.getLnNum(n.pos())); for (int j = 0, count = line == 0 ? 0 : beginLines.length; j < count; j++) { if (line >= beginLines[j] && line <= endLines[j]) { CompilerMessage m = new OnlyMetadataIsAllowed(); m.setPath(cx.input.origin); m.setLine(cx.input.getLnNum(n.pos())); ThreadLocalToolkit.log(m); break; } } } } }
public static void swcDependencies(String[] args) { try { CompilerAPI.useAS3(); // setup the path resolver CompilerAPI.usePathResolver(); // set up for localizing messages LocalizationManager l10n = new LocalizationManager(); l10n.addLocalizer(new XLRLocalizer()); l10n.addLocalizer(new ResourceBundleLocalizer()); ThreadLocalToolkit.setLocalizationManager(l10n); // setup the console logger. the configuration parser needs a logger. CompilerAPI.useConsoleLogger(); // process configuration ConfigurationBuffer cfgbuf = new ConfigurationBuffer(DependencyRootConfiguration.class, Configuration.getAliases()); DefaultsConfigurator.loadDefaults(cfgbuf); DependencyRootConfiguration configuration = (DependencyRootConfiguration) Mxmlc.processConfiguration( l10n, "swcdepends", args, cfgbuf, DependencyRootConfiguration.class, "no-default-arg"); // well, setup the logger again now that we know configuration.getWarnings()??? CompilerAPI.useConsoleLogger(true, true, configuration.getWarnings(), true); CompilerAPI.setupHeadless(configuration); CompilerConfiguration compilerConfig = configuration.getCompilerConfiguration(); VirtualFile[] virtualFiles = new VirtualFile[0]; VirtualFile[] moreFiles = compilerConfig.getLibraryPath(); if (moreFiles != null) virtualFiles = moreFiles; // first one, just assign reference moreFiles = Configuration.getAllExcludedLibraries(compilerConfig, configuration); if (moreFiles != null) virtualFiles = (VirtualFile[]) CompilerConfiguration.merge(virtualFiles, moreFiles, VirtualFile.class); moreFiles = compilerConfig.getThemeFiles(); if (moreFiles != null) { // remove the css files and keep the swcs List<VirtualFile> themeSwcs = new ArrayList<VirtualFile>(moreFiles.length); for (int i = 0; i < moreFiles.length; i++) { if (moreFiles[i].getName().endsWith(".swc")) themeSwcs.add(moreFiles[i]); } if (themeSwcs.size() > 0) virtualFiles = (VirtualFile[]) CompilerConfiguration.merge( virtualFiles, themeSwcs.toArray(new VirtualFile[themeSwcs.size()]), VirtualFile.class); } moreFiles = compilerConfig.getIncludeLibraries(); if (moreFiles != null) virtualFiles = (VirtualFile[]) CompilerConfiguration.merge(virtualFiles, moreFiles, VirtualFile.class); DependencyConfiguration dependencyConfig = configuration.getDependencyConfiguration(); List<String> types = dependencyConfig.getDesiredScriptDependencyTypes(); SwcDependencyInfo depInfo = SwcDependencyUtil.getSwcDependencyInfo( virtualFiles, types.size() == 0 ? null : types.toArray(new String[types.size()]), dependencyConfig.getMinimizeDependencySet()); List<String> depOrder = depInfo.getSwcDependencyOrder(); List<String> showSwcs = dependencyConfig.getShowSwcs(); // list the swc dependencies for (String swcLocation : depOrder) { // filter the swcs that are shown if (showSwcs.size() != 0) { boolean skip = true; for (String showSwc : showSwcs) { if (swcLocation.equals(showSwc) || swcLocation.endsWith(showSwc)) { skip = false; break; } } if (skip) continue; } System.out.println(swcLocation + ":"); // list of swc dependencies on swcLocation Set<String> depends = depInfo.getDependencies(swcLocation); for (String swcDepName : depends) { System.out.println("\t" + swcDepName); // list the external scripts that caused the dependencies between // swcLocation and swcDepName. if (dependencyConfig.getShowExterns()) { SwcExternalScriptInfo swcExternalScriptInfo = depInfo.getSwcExternalScriptInfo(swcLocation); for (String externalScriptName : swcExternalScriptInfo.getExternalScripts(swcDepName)) { if (dependencyConfig.getShowTypes()) { System.out.print("\t\t" + externalScriptName + "\t"); for (String type : swcExternalScriptInfo.getScriptDependencyTypes(externalScriptName)) { System.out.print(type + " "); } System.out.println(); } else System.out.println("\t\t" + externalScriptName); } } } } } catch (ConfigurationException ex) { Mxmlc.processConfigurationException(ex, "swcdepends"); } catch (SwcException ex) { assert ThreadLocalToolkit.errorCount() > 0; } catch (Throwable t) // IOException, Throwable { ThreadLocalToolkit.logError(t.getLocalizedMessage()); if (Trace.error) { t.printStackTrace(); } } finally { CompilerAPI.removePathResolver(); } }
public static void main(String[] args) { swcDependencies(args); System.exit(ThreadLocalToolkit.errorCount()); }
public void extractStyles(StyleSheet styleSheet, boolean local) throws Exception { RuleList sheetRules = styleSheet.getCssRules(); if (sheetRules != null) { // aggregate rules by selector Iterator ruleIterator = sheetRules.iterator(); while (ruleIterator.hasNext()) { Rule rule = (Rule) ruleIterator.next(); if (rule instanceof StyleRule) { // for each selector in this rule SelectorList selectors = ((StyleRule) rule).getSelectorList(); int nSelectors = selectors.getLength(); for (int i = 0; i < nSelectors; i++) { Selector selector = selectors.item(i); int lineNumber = rule.getStyle().getLineNumber(); if (selector instanceof AbstractSelector) { lineNumber = ((AbstractSelector) selector).getLineNumber(); } if (selector.getSelectorType() == Selector.SAC_CONDITIONAL_SELECTOR) { Condition condition = ((ConditionalSelector) selector).getCondition(); if (condition.getConditionType() == Condition.SAC_CLASS_CONDITION) { String name = ((AttributeCondition) condition).getValue(); assert name != null : "parsed CSS class selector name is null"; addStyleClassSelector(name, rule, lineNumber); } else { ConditionTypeNotSupported conditionTypeNotSupported = new ConditionTypeNotSupported( compilationUnit.getSource().getName(), lineNumber, condition.toString()); ThreadLocalToolkit.log(conditionTypeNotSupported); } } else if (selector.getSelectorType() == Selector.SAC_ELEMENT_NODE_SELECTOR) { // pick up type selectors only from root (application) if (compilationUnit.isRoot()) { String name = ((ElementSelector) selector).getLocalName(); // Batik seems to generate an empty element // selector when @charset, so filter those out. if (name != null) { addStyleTypeSelector(name, rule, local, lineNumber); } } else { // [preilly] This restriction should be removed once the // app model supports encapsulation of CSS styles. ComponentTypeSelectorsNotSupported componentTypeSelectorsNotSupported = new ComponentTypeSelectorsNotSupported( compilationUnit.getSource().getName(), lineNumber, selector.toString()); ThreadLocalToolkit.log(componentTypeSelectorsNotSupported); } } else { SelectorTypeNotSupported selectorTypeNotSupported = new SelectorTypeNotSupported( compilationUnit.getSource().getName(), lineNumber, selector.toString()); ThreadLocalToolkit.log(selectorTypeNotSupported); } } } else if (rule instanceof FontFaceRule) { addFontFaceRule((FontFaceRule) rule); } } } }